1

I have something like this in my controller:

$item = item::where('id',1)->first();

I get a Collective object.

I want to retrieve a specific table from such item.

$item->only(['name]);

So I can give it to the view. However it won't work.

BadMethodCallException in Builder.php line 2508: Call to undefined method Illuminate\Database\Query\Builder::only()

How do I retrieve this concrete variable?

prgrm
  • 3,734
  • 14
  • 40
  • 80

3 Answers3

3

When you're using first() method, you get an object, so you can just access it's properties:

$item = item::where('id',1)->first();
$name = $item->name;
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • @alexyMezenin , when I use ->get() collection colud not return on $item->name , that return on $item[0]->name, can you explain this please thank you – Noni Apr 10 '18 at 08:33
  • @noni, when you use first() instead of get() you will always get the root level object instead of array of object therefore $item instead of $item[0] – Haisum Usman Jul 25 '22 at 21:18
  • Thanks, Haisum I posted that in 2018 :) Laravel 5 newly arrived at that time. Thanks anyways :) – Noni Jul 27 '22 at 07:16
1

You can try this for retrieving the single value

$name = item::where('id',1)->value('name');
Vikash
  • 3,391
  • 2
  • 23
  • 39
0

You can use any way that you want like as select or pluck

So if you wish to retrieve only column name you can try :

$item = item::where('id', 1)->select('name')->first();
$item->name;

or

$item = item::where('id', 1)->pluck('name')->first();

I hope it can help you to retrieve data for difference situation.

Thanks !

Ratana Dev
  • 66
  • 5