Search code examples
phplaravellaravel-5.3

Include PHP variables in a Laravel 5.3 view within a layout


Based on the Laravel notification email template, here is what I'm trying to do.

I try to have a layout for emailings, with variables, in order to have some styles, defined in my layout, but accessible in my email views.

Here is an example:

emails/layout.blade.php

<!DOCTYPE html>
<html>
<head> [...]
</head>
@php
$style = ['body' => 'font-size:12px;color:#000;', 'paragraph' => 'font-size:10px;color:#eee;'];
@endphp
<body style="{{ $style['body'] }}">
@yield('content')
</body>
</html>

And in my email view :

@extends('emails.layout')

@section('content')

<p style="{{ $style['paragraph'] }}">
   Hi there!
</p>

@endsection

BUT this is not working as the $style variable is not accessible in my section.

SO, the only way I make it working is including a PHP file in both my layout and my view, and I'm pretty sure this is not the way I should do this with Laravel...

<?php include_once(base_path('resources/views/emails/variables.php')); ?>

Is there a way to achieve this? Thanks guys!


Solution

  • Ideally, you shouldn't be trying to include PHP variables in this way. When returning your view from your controller, you should be passing it all the variables it needs to render the view:

    class YourController
    {
        public function yourMethod()
        {
            $styles = getYourStyles();
    
            return view('emails.view')->with([
                'styles' => $styles
            ]);
        }
    }
    

    This will make your styles available in the $styles variable throughout your view.

    Alternatively, you could use the config to house your variables and then you can simply access them whenever you need them.

    In config/styles.php

    return [
        'paragraph' => 'font-size: 12px; font-weight: bold;'
    ];
    

    In your template:

    <p style="{{ config('styles.paragraph') }}">