Reputation: 2000
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.
Upvotes: 1
Views: 16606
Reputation: 4992
$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;
Upvotes: 2
Reputation: 8618
$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;
Upvotes: 3
Reputation: 2748
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);
}
Upvotes: 4