Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Annaro's avatar

How to share a PHP variable with different pages (using same layout) and components?

I am working on this web app 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!

0 likes
3 replies
sr57's avatar

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

https://laravel.com/docs/8.x/blade#building-layouts

How to write code for the auth user ?

https://laravel.com/docs/8.x/blade#authentication-directives

How to get the user?

https://laravel.com/docs/8.x/authentication#retrieving-the-authenticated-user

How to retrieve data for a user ?

https://laravel.com/docs/8.x/eloquent#building-queries

You should do what you want with these 4 "bricks"

Please or to participate in this conversation.