Alright, I threw on a pot of coffee and here we are. Throw these into your component or a trait:
public function putBuilderInSession($builder)
{
$query = $builder->getQuery();
session(['builder.connectionName' => $query->connection->getConfig('name')]);
unset($query->connection);
session(['builder.query' => $query]);
$model = $builder->getModel();
session(['builder.model' => $model]);
$eagerLoads = array_keys($builder->getEagerLoads());
session(['builder.eagerLoads' => $eagerLoads]);
}
public function getBuilderFromSession()
{
$query = session()->pull('builder.query');
$connectionName = session()->pull('builder.connectionName');
$query->connection = DB::connection($connectionName);
$model = session()->pull('builder.model');
$builder = new EloquentBuilder($query);
$builder->setModel($model);
$eagerLoads = session()->pull('builder.eagerLoads');
foreach ($eagerLoads as $eagerLoad) {
$builder = $builder->with($eagerLoad);
}
return $builder;
}
In your hydrate() method:
$this->data = $this->getBuilderFromSession()
And in your render() method before you return the view:
$this->putBuilderInSession($this->data)
When your component hydrates, it will have an almost exact copy of the builder object you passed into mount(). The only caveat is I can’t figure out how to get any of the constraints for an eager loaded relationship, so unfortunately it’s going to load the whole relationship.
For example, if you have something like ->with('author:id,name')
somewhere in the pipeline, or if you are registering that in your model in the $with array, the relation won’t contain only the id and name.
That constraint information is stored in a closure which you can’t serialize. I’m assuming there is some way to make use of it, but I don’t know how. If someone does, I can fix that issue. This closure is the only place I can find where you have access to the constraints without creating a modified Eloquent\Builder class. It looks something like this:
"author" => Closure($query) {
class: "Illuminate\Database\Eloquent\Builder"
use: {
$name: "author:id,name"
}
file: ".../laravel/framework/src/Illuminate/Database/Eloquent/Builder.php"
line: "1137 to 1139"
}
Let me know if you run into any issues.