Reman Bala
Reman Bala

Reputation: 107

Trying to get property 'description' of non-object Laravel 6

I am new to Laravel and I am currently trying to make a Todos application. However, when I try to read from the model and show it in the Blade file, this error appears:

"Trying to get property 'description' of non-object"

web.php

Route::get('/{todo}', 'TodosController@show');

TodosController.php

public function show($todoId){
    $todos = Todo::find($todoId);

    return view('todos.show', compact('todos'));
}

show.blade.php

 @foreach ($todos as $todo)
     <li class="list-group-item">
         {{ $todo->description }}
     </li>
 @endforeach

The error is in {{ $todo->description }}

I had seen similar questions but I could not understand therefore please help me. I want to know why is this error occurring and how can I solve it?

Upvotes: 1

Views: 3956

Answers (4)

Dev Love
Dev Love

Reputation: 1

Your code is correct but also add a model name like

public function show(Todo $todoId){
    $todos = Todo::find($todoId);

    return view('todos.show', compact('todos'));
}

This is the laravel default that used if you are on the same controller

Upvotes: 0

Jon White
Jon White

Reputation: 1010

$todos = Todo::find($todoId);

will get you a single instance of a Todo. In your view you are looping through what looks like you are expecting an array or collection of Todos

You can either remove the foreach loop in your view or change your Todo query to:

$todos = Todo::where('id', $todoId)->get()

This will give you a single Todo wrapped in a collection allowing your loop to get the single Todo instance in the collection.

The problem is that when you pass an instance of a model to a loop it starts looping through the properties. You're then trying to get the property on another property which doesn't exist. You need to pass an array or collection to the loop so each item is an instance with valid properties.

It might be helpful to do a dump to see the results of the methods available for getting data

dump(
    Todo::all(),
    Todo::where('id', $todoId)->get(),
    Todo::find($todoId)
);

You'll see the first two return collections which work when you pass then to your foreach. The second returns an instance of Todo which can be passed to your loop but the loop then pulls properties from the instance instead if instances form the collection. You want the latter.

Upvotes: 3

Abdul Wahab
Abdul Wahab

Reputation: 25

TodosController.php

    public function show($todoId){
    $todos = Todo::find($todoId)->get()->first();
    return view('todos.show', compact('todos'));
}

show.blade.php

    <li class="list-group-item">
       {{ $todos['description'] }}
    </li>

no need to use foreach loop

Upvotes: 0

VIKAS KATARIYA
VIKAS KATARIYA

Reputation: 6005

Try this

public function show($todoId){
        $todos = Todo::where('id', $todoId)->get();
        return view('todos.show', compact('todos'));
    }

Upvotes: 0

Related Questions