[英]How to access object Property inside the controller in laravel?
Hello I wanted to know how to access and store a property of a gotten object in laravel controller and here is my code:- 您好我想知道如何在laravel控制器中访问和存储获取的对象的属性,这是我的代码:-
$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.
在这里,我想将id属性存储在
$test
变量中,但是会出现此错误:- Property [id] does not exist on this collection instance.
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);
}
$phonebooks
is variable type of collection so you must acces each phonebook with foreach or just index. $phonebooks
是集合的可变类型,因此您必须使用foreach或仅索引来访问每个电话簿。 with foreach : 与foreach:
$i = 0;
foreach($phonebooks as $phonebook){
$test[$i] = $phonebook->id;
$i++;
}
or with defined index: 或具有定义的索引:
$test = $phonebooks[0]->id;
$phonebooks = Phonebook::with('client')->get();
This return instance of \\Illuminate\\Database\\Eloquent\\Collection
. 此返回实例
\\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 否则您只能使用db获得一个记录
$phonebooks = Phonebook::with('client')->first(); // if need some condition
$test = $phonebook->id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.