It seems that everyone is asking how to convert Query\Builder to Eloquent\Builder. I need the opposite - I have a Model with some scopes defined which I create a query from. The result that it returns is an instance of my model. I want it to be a a plain object.
Fetching a model and the converting to an stdClass doesn't seem right to me.
Is this possible?
Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.
Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.
Using Laravel Eloquent methods The first method to get the query of an Eloquent call is by using the toSql() method.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
Yes. You can build up the query using the Eloquent query builder, but then you can actually execute the query using the base query builder, which will return stdClass objects.
Below is an example. Obviously you can chain all this stuff together into one line, but I broke it out into multiple lines to explain what's going on. Assume you have an active()
scope on your User
model:
// start an eloquent query but don't execute it yet
$query = User::active();
// add any other conditions...
// get the base builder for the eloquent builder
$baseQuery = $query->getQuery();
// will return a standard array of stdClass objects
$users = $baseQuery->get();
Another example to just return one object:
// will return a stdClass object
$user = User::active()->getQuery()->first();
Be aware, though, that you do lose Eloquent query functionality, such as relationships and eager loading.
For example:
$user = User::with('posts')->active()->getQuery()->get();
This will not run the query for the posts for the users, and the posts will not be attached to the stdClass objects returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With