Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting random variable into every View in Laravel

Tags:

php

laravel

I am just getting started with Laravel and working on porting a mess of a site to the framework.

One feature of the site is a dynamically added image in the header. I am using a common Blade template and was wondering if there is any way to inject a random variable (an integer between 1 and 4 would do) into every View that uses that layout.

What I would like to do is to be able to add something like so in the the common template-

<img src="img/cutouts/cutout-<?= $randomInt;?>.jpg" alt=""/>

with $randomInt sent to every View

like image 204
NightMICU Avatar asked Sep 11 '25 11:09

NightMICU


2 Answers

You could look into View composers

So you would have something like:

View::composer('your.view', function($view)
{
    $view->with('randomInt', rand(1,4));
}

That will pass the $randomInt variable in everytime you use the 'your.view' (or whatever) View.

like image 155
TerryMatula Avatar answered Sep 13 '25 00:09

TerryMatula


It's also possible to add a variable to all views through View::share().

For example, you could modify the __construct method in Base_Controller with:

View::share('randomInt', rand(1,4));
like image 41
avr Avatar answered Sep 13 '25 02:09

avr