Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

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..

like image 232
Febry Damatraseta Fairuz Avatar asked Sep 28 '14 14:09

Febry Damatraseta Fairuz


2 Answers

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();
like image 199
KAS Avatar answered Oct 03 '22 10:10

KAS


$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

like image 43
Ornelio Chauque Avatar answered Oct 03 '22 11:10

Ornelio Chauque