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

45,443

Solution 1

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

Solution 2

$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

Share:
45,443
Febry Damatraseta Fairuz
Author by

Febry Damatraseta Fairuz

Updated on September 11, 2020

Comments

  • Febry Damatraseta Fairuz
    Febry Damatraseta Fairuz over 3 years

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