簡體   English   中英

未定義屬性:Illuminate \ Database \ Eloquent \ Collection :: $ id Laravel 4

[英]Undefined property: Illuminate\Database\Eloquent\Collection::$id Laravel 4

我正在使用laravel v 4.2 ..我想創建更新記錄。 你可以幫助我..這段代碼有什么問題......這是我的代碼:

MatakuliahsController.php

public function edit($id)
    {
        //$matakuliahs = $this->matakuliahs->find($id);
        $matakuliahs = Matakuliah::where('id','=',$id)->get();

        if(is_null($matakuliahs)){
            return Redirect::route('matakuliahs.index');
        }

        return View::make('matakuliahs.edit',compact('matakuliahs'));
    }

edit.blade.php

{{ Form::open(array('autocomplete' => 'off', 'method' => 'PATCH', 'route' => array('matakuliahs.update', $matakuliahs->id))) }}
...
{{ Form::close() }}

錯誤是:

Undefined property: Illuminate\Database\Eloquent\Collection::$id (View: C:\xampp\htdocs\Laravel 4\projectLaravel\app\views\matakuliahs\edit.blade.php)

感謝您的關注和幫助..

你想要得到的是一組模型上的關系,該關系存在於該集合中的對象上。 您可以使用first()返回第一個,或者您需要使用循環來獲取每個項目

    $matakuliahs = Matakuliah::where('id','=',$id)->get()->first();
$matakuliahs = Matakuliah::where('id','=',$id)->get(); 

返回id等於$ id的對象的colllection。 在這種情況下,如果id是唯一的,那么將返回1個元素的集合而不是對象本身,所以當你這樣做時:

$matakuliahs->id

你正在試圖獲取$ matakuliahs對象的id屬性,但在這種情況下$ matakuliahs不是一個對象是一個集合。 要解決這個問題你可以做到:
1。

$matakuliahs = Matakuliah::where('id','=',$id)->get()->first(); 

要么

$matakuliahs = Matakuliah::where('id','=',$id)->first(); 

獲取對象並獲取屬性。

2.在你看來:

@foreach( $matakuliahs as $matakuliah)
//your code here
@endforeach

希望這個幫助。 謝謝

在控制器方法中嘗試這個:

$matakuliahs = Matakuliah::find($id);

然后將它傳遞給視圖。

方法

MyModel::find($id); 

或者與Eloquent的關系沒有適用於Laravel 4.2下一個解決方案

$myModel= new MyModel;
$myModel->setConnection('mysql2');
$myModel= $myModel->where('id', $id)->first();

暫無
暫無

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

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