Vishal Tarkar
Vishal Tarkar

Reputation: 826

Difference between View Composer and Helper in Laravel?

I don't know if same question asked or not. but can any one explain difference between these 2 Laravel feature ? & Which one to use and when ?

Upvotes: 0

Views: 292

Answers (1)

lesssugar
lesssugar

Reputation: 16181

In the context of Laravel, a Helper is a global function you can use to perform specific operations on arrays, strings, etc. For example, let's say, you need to slugify a string:

$title = str_slug('Laravel 5 Framework', '-');

// laravel-5-framework

-- easily done with the str_slug() helper (function).

View composers, on the other hand...

...are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

In other words, they are not simple functions, but the framework's construct used when you need to make sure that a variable (resource) is available across multiple views.

For example, the code below will make sure that every time the sidebar.blade.php view is rendered, it will have access to the $navigation variable:

// Using Closure, within a Service Provider...

View::composer('sidebar', function ($view) {
    $navigation = array(/*...*/);
    $view->with('navigation', $navigation);
});

This means you've just centralized the navigation source, as opposed to passing the navigation items from each controller that handles a page with the sidebar.

Upvotes: 2

Related Questions