Home > Mobile >  How to handle the if statement in a view called from multiple places when passing a variable to comp
How to handle the if statement in a view called from multiple places when passing a variable to comp

Time:08-11

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 >
@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?

CodePudding user response:

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

CodePudding user response:

If You are using $client_name in different blade, Try to share your variable using View::share() in the AppServiceProvider it will act as component and you can use it across all the blade template

from AppServiceProvider class

$tasks = $client->tasks;
$client_name = $client->name;

ex: View::share(['client_name'=>$client_name] i already use it in my project

  • Related