Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

johnn's avatar
Level 2

Laravel 5.4 From Scratch: Working With the Query Builder - PHP Error Undefined variable: task

https://laracasts.com/series/laravel-from-scratch-2017/episodes/6

When browsing to blog.test/tasks/1, /tasks/2, or /tasks/3, I receive the following error from show.blade.php

{{ $task->body }}

ERROR: "Undefined variable: task (View: /resources/views/tasks/show.blade.php)"

It looks to be defined here in web.php, yes?..

Route::get('/tasks/{id}', function ($id) {

$task = DB::table('tasks')->find($id);

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

If I browse to blog.test/tasks, the Unordered List displays correctly.

I have every file in the correct directory too, I believe. resources/views/welcome.blade.php resources/views/tasks/index.blade.php resources/views/tasks/show.blade.php

Why isn't show.blade.php unable to define $task?

0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67
$task = DB::table('tasks')->find($id);

return view('tasks.show', compact('tasks'));

See anything wrong there? $task and compact('tasks')? You're passing $task as $tasks to the view.

So change

return view('tasks.show', compact('task'));
1 like
johnn's avatar
Level 2

Good eye! That fixes it. Thanks!

Please or to participate in this conversation.