简体   繁体   中英

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

i'm using laravel v 4.2.. i want to create update record. can you help me.. what's wrong with this code... this is my code :

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'));
    }

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

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

thanks for your attention and your help..

What you are trying to get is a relationship on a collection of models, the relationship exists on the object in that collection. You can use first() to return the first one or you need to use loop for each one get their items

    $matakuliahs = Matakuliah::where('id','=',$id)->get()->first();
$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

Try this in your controller method:

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

And just pass it to the view.

The method

MyModel::find($id); 

Or relationship with Eloquent no works on Laravel 4.2 just next solution

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM