robspin
robspin

Reputation: 811

The difference between the model and query builder method when using get and first on laravel?

if I just want to get the only one column name

--use model--------

$model_use_get  =Model::select('name')->where('id','=',10)->get();

$want=$model_use_get[0]['name'];

$model_use_first=Model::select('name')->where('id','=',10)->first();

$want=$model_use_first['name'];

---use query builder-----

$query_use_get  =DB::table('a1)->select('name')->where('id','=',10)->get();

$want=$query_use_get[0]->name;

$query_use_first=DB::table('a1)->select('name')->where('id','=',10)->first();

$want=$query_use_first->name;

what's the difference? Does not both model or query method make a collection? or object?(array?) I confused!!! Is there any direct method to just get the one select ,not need to process again? like below (I confirm the result is only one because I use where id=xxx)

$want=model::select('name)->.... 
$want=DB::table('a1')->select('name').....

Upvotes: 0

Views: 1347

Answers (2)

Tim Lewis
Tim Lewis

Reputation: 29278

To answer the question, the combination of Model, DB::table(), ->get() and ->first() all return different things.

1st instance, Model and ->get():

$collection = Model::get(); 
// Returns a `Collection` of `Model` records, constrained to your additional query logic.

2nd, Model and ->first():

$model = Model::first(); 
// Returns a single `Model`, or `null`, based on your query logic.

3rd, DB::table() and ->get():

$collection = DB::table("table")->get(); 
// Returns a `Collection` of `stdClass` objects, based on your query logic.

4th, DB::table() and ->first():

$record = DB::table("table")->first(); 
// Returns a single `stdClass`, or `null`, based on your query logic.

Hopefully that clears everything up. There are additional closures, such as find(), findOrFail(), paginate(), etc, that all return similar things, so play with those and see what works best for your needs.

Upvotes: 2

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

The difference is pretty simple:

  • first() gets single record from database
  • get() gets collection of items (similar to array)

So for first() you can get model property using $model->property but for get you have multiple items, so you can get properties using loop:

foreach ($models as $model) {
   $model->property;
}

When you run get() and later first like this you run 2 queries, but you can call first also on items you already got from database:

$models = Model::select('name')->where('id','=',10)->get();

foreach ($models as $model) {
   echo $model->name;
}

$firstModel = $models->first();

$want = $firstModel->name;

Upvotes: 3

Related Questions