How to pass a variable to Blade?

Asked

Viewed 7,222 times

-1

I have the following scenario: Some types of user may have access to the site, say USERTYP1, USERTYP2 or USERTYP3.

My application menu changes according to user type.

I have a master template homeMaster.blade.php and the menu was created in the file home.blade.php who inherits the master template.

In traditional php should have a if in home.blade.php to test a variable $usertype. According to the type we would have the appropriate menu.

I was reading the Blade documentation and created this code to test the user:

@if ($usertype === "USERTYP1")
    menu 1
@elseif ($usertype === "USERTYP2")
    menu 2
@else
    menu 3
@endif

I didn’t understand how to pass this variable $usertype for home.blade.php, or even if that would be the best approach for such implementation.

--

Updating

I’ll post it here for whoever needs it. I found a link which exactly answers my question.

  • You can’t pass a variable to the view, whether it’s a partial or not, or you can’t pass a homeMaster.blade.php variable to home.blade.php? Be more specific please.

  • homeMaster is just a template. Who should treat the conditions is the home page.blade. Then it should be this page that will receive the variable, when calling the view.

  • That is, how to pass a controller variable to the view? That’s what I understood, I’m sorry if it has nothing to do with your question.

  • Actually I’m starting with Laravel. I know how to move the controller variable to the view. But I’m using - in my view, I’m extending the master view. Then I would have two options: 1- make ifs inside the view and call @Yield appropriate for that usertype or 2- have ifs inside the master. In that second case I would have to pass the variable to the master. But I’m concluding that the best option - or maybe the right option is the approach at 1.

2 answers

2

You can also use Compact

ex:

public function edit($id) {

      $categorias = Categorias::all();
      $posts =  Posts::all();

       return view('edit')->with(compact('categorias','posts'));

}

and in your Voce view you can capture this value normally

{{ $categorias }}
{{ $posts }}

1


Hello,

You can pass an array when you call the view, as the second parameter, containing the variables you want to use in your view. Example:

view('home', ["usertype" => "USERTYP1"]);

If you want to pass the variable in a include call, you can follow the example:

@include("home", ["usertype" => "USERTYP1"])

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.