Shady Ibrahim
Shady Ibrahim

Reputation: 25

how to execute php code on every time load website on laravel 4.2?

I have dynamic menu on header which i get its content form database, so i want to know WHERE & HOW can implement code to get data form database to be defined on whole web application? without need to put code on each class responsible for load view.

$categuries_list = DB::table('categories')
                            ->where('parent', '=', 2)
                            ->lists('name', 'id');

I think to cache what i need but on this case i will put code on each class load view(so that is bad solution).

Upvotes: 1

Views: 374

Answers (1)

user1669496
user1669496

Reputation: 33048

This is exactly what view composers are for.

View::composer('header', function($view)
{
    $categuries_list = DB::table('categories')
        ->where('parent', '=', 2)
        ->lists('name', 'id');

    $view->with('categuries_list', $categuries_list);
});

Just swap out the header with the actual name of the view which contains the header.

This code can go anywhere which is being autoloaded.

Can read about view composers in the documentation. http://laravel.com/docs/4.2/responses#view-composers

Upvotes: 2

Related Questions