Home > Software design >  How to get an ID from the collection in laravel?
How to get an ID from the collection in laravel?

Time:10-19

I am writing one database query it's returning the matching record that's stored in one variable called $store,i want to get the id of the particular record which is stored in the $store variable.


$store=DB::table('books')->where('bookName','dummy')->get();

books migration table structure

$table->increments('id');
$table->string('bookName');  //it's uniqe
$table->int('price');

what i am trying is when i try to get the id of a particular book based on $store [$store->id]variable it's throwing an error called

Propert id doesnot exist on collection instance

CodePudding user response:

it's showing clearly collection so you have to call the following way

$store[0]->id

CodePudding user response:

Try this

$store=DB::table('books')->where('bookName','dummy')->get();
foreach($store as $str){
   echo $id = $str->id;
}

CodePudding user response:

If you need only the id, the common way will be use select. Model::select('id')->get();

And in the view you can iterate the ModelCollection and use $item->id or '$item['id']'

CodePudding user response:

foreaxample, getting first book id with specific price:

$id = $store->where('price', 100)->first()->id;
  • Related