-1

I was wondering if it is possible to query using DB facade but returned as an Eloquent Model.

For example i have this query using db query builder

\DB::table('users')->first();

But after the query I want all results to be an Eloquent model from App\User

same results of this

\App\User::first()

my goal for this question is what if I have complex query that returns a sets of users. Using eloquent model is not really efficient i think that's why I use the query builder for raw querying but I also want the results to be a Eloquent model instance.

4
  • @TsaiKoga I don't think it is duplicated. I want to return it as a eloquent model like App\User not as a collection Commented Nov 22, 2019 at 6:31
  • It will have the same efficiency. The slowness added on Eloquent when you do a query is almost from some data processing when you instantiate the model. If you are going to instantiate it, so you will have the same efficiency. Commented Nov 22, 2019 at 9:48
  • @Don'tPanic thank you for pointing out. let me check it. Commented Nov 22, 2019 at 12:16
  • @EliasSoares I thought of that also but maybe there are some small differences i'll have to check it my self Commented Nov 22, 2019 at 12:19

1 Answer 1

-2

Maybe you can use the collect function, It can help you to have many methods like what eloquent return to you. You can see all the methods here.

The code would look like :

use Illuminate\Support\Facades\DB;

collect(DB::table('users')->first())
Sign up to request clarification or add additional context in comments.

4 Comments

unfortunately collect function is not what I am looking for. collect function convert an array into collection. What I want is to return the query into a eloquent model
collect() makes a collection, it does not magically convert an array to a Model instance.
Yeah, I said it just like, but of course it's not a model instance
DB already returns a collection

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.