未定义属性:Illuminate \ Database \ Eloquent \ Collection :: $ id Laravel 4

时间:2014-09-28 14:30:11

标签: php collections properties undefined

我正在使用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)

感谢您的关注和帮助..

4 个答案:

答案 0 :(得分:25)

您要获得的是一组模型之间的关系,该关系存在于该集合中的对象上。您可以使用first()返回第一个,或者您需要使用循环来获取每个项目

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

答案 1 :(得分:4)

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

return a colllection of object where the id is equal to $id. in this case will return a collection of 1 element and not the object itself of course if the id is unique, so when you do:

$matakuliahs->id

you are triying to acess the id properties of the $matakuliahs object but the $matakuliahs in this case is not a object is a collection. to solve this problem you can do:
1.

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

or

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

to get the object and acess the properties.

2. on you view:

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

hope this help. thanks

答案 2 :(得分:0)

在你的控制器方法中试试这个:

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

然后将其传递给视图。

答案 3 :(得分:0)

方法

MyModel::find($id); 

或者与雄辩的关系在Laravel 4.2上无法解决,只是下一个解决方案

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