Search code examples
laravelviewlaravel-8laravel-9

How to handle the if statement in a view called from multiple places when passing a variable to compact


I have the following function in the controller:

public function tasks(Client $client)
{
$tasks = $client->tasks;
$client_name = $client->name;
return view('task.index', compact('tasks','client_name'));
}

and as task_index is called from multiple places, I am handling h1 as shown below:

<div class="col-12 col-md-10 d-flex justify-content-center">
@if($client_name)
<h1>List of overall customer tasks {{$client_name}}</h1>
@else
<h1>List of tasks</h1>
@endif
</div>

only when I click on the button to show all the tasks I get the error

Undefined variable $client_name

so the if is not working.

Can anyone tell me how to do please?


Solution

  • Use the Blade @isset directive rather than @if:

    @isset($client_name)
        <h1>List of overall customer tasks {{$client_name}}</h1>
    @else
        <h1>List of tasks</h1>
    @endisset