Ad

How Could I Return A View With [email protected] In Laravel?

- 1 answer

I need to send data of Category::all() to a view. But I can't to use the @index() of controller. I think to use something like this, but it's a wrong way 'cause this will not to be used in other views.

$categories = Category::all();
return view('view')->with('categories', $categories)

What is the right way to return all to a .blade view?

Ad

Answer

it's a wrong way 'cause this will not to be used in other views.

I understood this question as you want to call all categories in all view files.

You can either create your own service provider (ViewServiceProvider name is common) or you can use the existing AppServiceProvider.

In your selected provider, put your code in the boot method.

public function boot() {
    $categories = Category::all();
    view()->share('categories ', $categories);
}

This will make a $categories variable accessible in all your views.

If you rather want to use the facade instead of the helper, change view()-> to View:: but don't forget to have use View; at the top of your file.

Ad
source: stackoverflow.com
Ad