簡體   English   中英

如何在Laravel中訪問控制器內部的對象屬性?

[英]How to access object Property inside the controller in laravel?

您好我想知道如何在laravel控制器中訪問和存儲獲取的對象的屬性,這是我的代碼:-

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

在這里,我想將id屬性存儲在$test變量中,但是會出現此錯誤:- Property [id] does not exist on this collection instance.

它是一個集合

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

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

而是嘗試這樣做

foreach($users as $user) {
    dd($user->id);
}

$phonebooks是集合的可變類型,因此您必須使用foreach或僅索引來訪問每個電話簿。 與foreach:

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

或具有定義的索引:

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

$phonebooks = Phonebook::with('client')->get(); 此返回實例\\Illuminate\\Database\\Eloquent\\Collection
在這種情況下使用

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

否則您只能使用db獲得一個記錄

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM