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

Danny971's avatar

Undefined variable $tasks

Im working on a todo list for my application but i keep getting the error at subject "Undefined variable $tasks"

here is my code

CONTROLLER

public function list_task() {
    // Get the currently authenticated user
    $user = Auth::user();

    // Initialize an empty array for tasks
    $tasks = [];

    // Check if the user is authenticated
    if ($user) {
        // Retrieve tasks for the authenticated user
        $tasks = todolist::where('posted_by', $user->id)->get();
    } else {
        // Handle the case where the user is not authenticated
        session()->flash('notification', ['type' => 'error', 'message' => 'User not authenticated']);
        return redirect()->route('login'); // Redirect to the login page or handle as needed
    }

    return view('dashboard', ['tasks' => $tasks]);
}

Javascript

  $(document).ready(function() {
  // Add CSRF token to all AJAX requests
    $.ajaxSetup({
     headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });

     // Handle Enter key press on the input field
     $('.tdl-new').keypress(function(event) {
     if (event.which === 13) { // Check if the key pressed is Enter (key code 13)
        event.preventDefault(); // Prevent the default behavior of the Enter key (form submission)

        // Get the task from the input field
        var task = $(this).val().trim();

        if (task !== '') {
            // Make an Ajax request to save the task
            $.ajax({
                url: '{{ route("save-todo") }}', // Use the correct route name
                method: 'POST',
                data: { todo: task },
                success: function(response) {
                    // Rest of the code...
                },
                error: function(error) {
                    // Rest of the code...
                }
            });
        }
    }
});

// Handle checkbox change event
$('input[type="checkbox"]').change(function() {
    var taskId = $(this).data('task-id');
    var status = $(this).is(':checked') ? 1 : 0;

    // Make an Ajax request to update the task status
    $.ajax({
        url: '{{ route("update-todo-status", ["id" => ":id"]) }}'.replace(':id', taskId), 
        method: 'POST',
        data: { status: status },
        success: function(response) {
        
        },
        error: function(error) {
          
        }
    });
});


$.ajax({
    url: '{{ route("tasks.index") }}', // Use the correct route name for displaying tasks
    method: 'GET',
    success: function(response) {
        console.log(response);  // Log the response to the console
        // Update the task list based on the response
        $('#todo_list').html(response);
    },
    error: function(error) {
        console.log(error);  // Log the error to the console
        // Rest of the code...
    }
});

});

Routes

// Route to display tasks Route::get('/tasks', [ToDoListController::class, 'list_task'])->name('tasks.index');

HTML

                 <div class="col-xl-4 col-xxl-6 col-lg-6 col-md-12 col-sm-12">
                     <div class="card">
                         <div class="card-header">
                            <h4 class="card-title">Todo</h4>
                         </div>
                        <div class="card-body px-0">
                            <div class="todo-list">
                                <div class="tdl-holder">
                                    <div class="tdl-content widget-todo2 mr-4">
                                        <ul id="todo_list">
                                        @foreach ($tasks as $task)
                                        </ul>
                                    </div>
                                    <div class="px-4">
                                        <input type="text" name="todo" class="tdl-new form-control" placeholder="Write new item and hit 'Enter'...">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                
                </div>
            </div>

the error point to this section of the html

@foreach ($tasks as $task)

my view name is dashboard.blade.php

any help would be appricated

0 likes
14 replies
kevinbui's avatar

What is the name of the blade file that contains the JavaScript code?

Danny971's avatar

@kevinbui it's not in a blade file its in a separate file called todolist.js

and the todo list where I want the tags to show is on dashboard.blade.php

DhPandya's avatar

@Danny971 Did you checked that you passed $tasks variable from your controller to your dashboard.blade.php ?

Danny971's avatar

@DhPandya I have this line in my controller

return view('dashboard', ['tasks' => $tasks]);

enadabuzaid's avatar

in dashboard.blade.php check if the $tasks already passed

@dd($tasks)
Snapey's avatar

my guess is that you are returning the dashboard view from more than one place, and its in some other place where you dont pass tasks

list-tasks does not seem the right name for something that returns the dashboard

Danny971's avatar

@Snapey yes there are other parts of the application I return the dashboard view cause I want the data to be displayed there.is this conflicting

Snapey's avatar

@Danny971 yes if course, if you don't pass $tasks wherever you use dashboard view

Danny971's avatar

@Snapey but I pass task to the dashboard from the controller. thus line does it return view('dashboard', ['tasks' => $tasks]);

Snapey's avatar

@Danny971 but you said you return dashboard from other functions also.

You can use this to prevent errors when you don't supply $tasks

 @foreach ($tasks ?? [] as $task)
Danny971's avatar

@Snapey I'll try that but I also use dd($task) in the controller to see if I'm getting any response and it does I do get a response

Snapey's avatar
Snapey
Best Answer
Level 122

@Danny971 you are totally missing the point

yes there are other parts of the application I return the dashboard view

In each of these other parts, you must also pass tasks

Please or to participate in this conversation.