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?

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

3 Comments

@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, 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]
Thanks, Haisum I posted that in 2018 :) Laravel 5 newly arrived at that time. Thanks anyways :)
1

You can try this for retrieving the single value

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

Comments

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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.