Laravel Packages

Serialization for Eloquent's QueryBuilder

Published
Serialization for Eloquent's QueryBuilder image

Eloquent Serialize is a Laravel package to serialize and unserialize Eloquent query builder objects. The EloquentSerialize service has two methods, serialize and unserialize.

Given the following simple query, you can serialize the builder results:

$data = \EloquentSerialize::serialize(
App\Models\Post::with('author')->limit(1)
);
 
// => "O:36:"AnourValar\EloquentSerialize\Package":1:{s:42:"\0AnourValar\EloquentSerialize\Package\0data";a:4:{s:5:"model";s:15:"App\Models\Post";s:10:"connection";N;s:8:"eloquent";a:3:{s:4:"with";a:1:{s:6:"author";a:16:{s:8:"bindings";a:9:{s:6:"select";a:0:{}s:4:"from";a:0:{}s:4:"join";a:0:{}s:5:"where";a:0:{}s:7:"groupBy";a:0:{}s:6:"having";a:0:{}s:5:"order";a:0:{}s:5:"union";a:0:{}s:10:"unionOrder";a:0:{}}...

From serialized data, you can get back an Eloquent builder instance:

\EloquentSerialize::unserialize($data)->get();
 
foreach ($builder->get() as $item) {
// ...
}
 
/*
=> Illuminate\Database\Eloquent\Collection {#4430
all: [
App\Models\Post {#4423
id: 1,
author_id: 1,
title: "Hello World",
body: "This is a test post.",
created_at: "2021-10-05 04:14:31",
updated_at: "2021-10-05 04:14:31",
author: App\Models\Author {#3483
id: 1,
name: "Paul Redmond",
created_at: "2021-10-05 04:13:36",
updated_at: "2021-10-05 04:13:36",
},
},
],
*/

This package could be helpful if you need to cache or store a query for users as serialized data and later need to retrieve the results back into an Eloquent builder object.

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article