Home > Blockchain >  Laravel 8: How to share a PHP variable with different pages (using same layout) and components?
Laravel 8: How to share a PHP variable with different pages (using same layout) and components?

Time:12-13

I am working on this web app (Laravel 8) in which users can choose their color themes. Basically, to make it simple, let's say each user can choose their primary_color.

On home page (which does not need authentication), the primary_color will come from config (whether user is authenticated or not). On authenticated pages, the primary_color comes from the users table (for the authenticated user). I also have a bunch of pages that use the guest layout if user is not authenticated, and the app layout if user is authenticated. Those would use the primary_color from config if user is not authenticated, and the primary_color chosen by the user if they are authenticated.

All those pages use some components (buttons, nav-links, etc) that need to know the primary_color.

I currently have this line on top of EACH php file that needs to know the primary_color:

$primary_color = (Auth::user() && Route::current()->getName() !== 'home') ? Auth::user()->config->color_theme : "yellow";

(Color "yellow" is hard coded here, just ignore it.)

I would love to avoid that much code replication, but i can't seem to find a way to share this variable from the layout (guest.blade.php or app.blade.php) to the page. I can't seem to be able to include a style.blade.php view that contains the variable, either. The variables declared in this included view do not exist in the rest of the page. I managed to pass the variable to components using a prop. It's not so nice, but it works fine. But it's not so nice, i'd rather use a cleaner solution.

But most importantly, how do i avoid having to copy the same bit of code on top of each page?

Thank you!

CodePudding user response:

If you want to share data with all the views you can use laravel's view composer. it can attach data to all view or multiple views simultaneously. source: https://laravel.com/docs/5.0/views#view-composers alternately: see here https://www.digitalocean.com/community/tutorials/sharing-data-between-views-using-laravel-view-composers

CodePudding user response:

You can use view composers. Under the boot method of AppServiceProvider add the folowing code.

\Illuminate\Support\Facades\View::composer('*',function($view){
            $userPrimaryColor = (Auth::user() && ! Route::is('home')) ? Auth::user()->config->color_theme : "yellow";
            $view->with('primary_color', $userPrimaryColor);
        });

The first argument * indicates that it needs to be shared to all the views. If you need those in few pages you can pass the list of pages as array

  • Related