9
votes

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 :

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() }}

Error is :

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

thanks for your attention and your help..

4

4 Answers

25
votes

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();
4
votes
$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

0
votes

Try this in your controller method:

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

And just pass it to the view.

0
votes

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();