1

Hello I wanted to know how to access and store a property of a gotten object in laravel controller and here is my code:-

 $phonebooks = Phonebook::with('client')->get();
    $test = $phonebooks->id;
    return view('admin.phonebooks.index', compact('phonebooks'))->with('current_time',$current_time);

Here I want to store the id property in $test variable but I get this error:- Property [id] does not exist on this collection instance.

2
  • You are using get() method not first() Commented Jun 7, 2018 at 9:09
  • ->get(); would return a collection of objects, use ->first() or $test = $phonebooks[0]->id; or a loop. Commented Jun 7, 2018 at 9:13

3 Answers 3

4

Its a collection

$users = User::with('posts')->get();

then $userId = $users->id // this will always throw error

instead try doing this

foreach($users as $user) {
    dd($user->id);
}
Sign up to request clarification or add additional context in comments.

Comments

3

$phonebooks = Phonebook::with('client')->get(); This return instance of \Illuminate\Database\Eloquent\Collection.
For this case use

foreach ($phonebooks as $phonebook) {
    $test = $phonebook->id;
}

Or you must be get only one recorde in db using

$phonebooks = Phonebook::with('client')->first(); // if need some condition
$test = $phonebook->id;

Comments

2

$phonebooks is variable type of collection so you must acces each phonebook with foreach or just index. with foreach :

$i = 0;
foreach($phonebooks as $phonebook){
    $test[$i] = $phonebook->id;
    $i++;
}

or with defined index:

$test = $phonebooks[0]->id;

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.