How to customize/change the header logo of notification mail (laravel) - laravel

I have no idea where could I found the header logo example below(squared):
My content code:
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.'.$user->name)
->line('Hey Now hey now')
->action('Notification Action', route('register.select'))
->line('Thank you for using our application!');
}
EDITED: in email.blade.php:
#component('mail::message')
{{-- Greeting --}}
#if (! empty($greeting))
# {{ $greeting }}
#else
#if ($level === 'error')
# #lang('Whoops!')
#else
# #lang('Hello!')
#endif
#endif
{{-- Intro Lines --}}
#foreach ($introLines as $line)
{{ $line }}
#endforeach
... and so on, and so forth
I want to customize that logo header, my problem I can't find where exactly. Need your help Sirs.

You just have to customize mail templates.
Run this command:
php artisan vendor:publish --tag=laravel-notifications
After that you'll find templates in resources/views/vendor/notifications.
If you want to customize mail components used in templates:
php artisan vendor:publish --tag=laravel-mail
You'll find components in resources/views/vendor/mail. The ones you want are message.blade.php and header.blade.php.

It only shows the Laravel logo if the APP_NAME in the .env is set as "Laravel".
So once you change this setting it will omit the default logo. if you want to change it to display something else you can publish the mail components as other answers showed and customize it.

Related

Diff for humans not working in laravel blade

Hi am trying to use diffForHumans in laravel blade but its not working.please help`enter code here
Heres my code
#foreach($students as #student)
$time=$student->created_at->diffForHumans()
#php echo $time;#endphp
#endforeach
$student->created_at is a string, hence you can't call diffForHumans() function on it. Instead, you should parse it via Carbon instead. Here's how to do it
#foreach($students as #student)
#php
$time= \Carbon::parse($student->created_at)->diffForHumans()
#endphp
//Now do what you need to do
#endforeach
Also, you can't just write php code inside blade. If you do that, you need to contain the code inside #php tags as shown above. Although, it's not really clean to write php code in blade. With that being said, if you just want to display the time, here's how I would do it
#foreach($students as #student)
<p>Created At : {{ \Carbon::parse($student->created_at)->diffForHumans() }}</p>
#endforeach
All You need is to parse the date using Carbon like this
{{ Carbon\Carbon::parse($student->created_at)->diffForHumans() }}

Create anchor tag with route contain under #php script in blade template

Route is not working. How can I write an anchor tag based on some condition? If the condition is true then the anchor tag will be printed with the route. I wrote the code below, but I get an error.
In my blade template:
#php
if (SOMECONDATION) {
echo 'Approve';
}
#endphp
{{ }} is echo-ing. You can use this :
#if($p->name == 0)
Approve
#endif
No need to use echo or anything. Directly use #if #endif and for route use {{ }}
#if($condition)
Approve
#endif

Not receiving the $message variable in view from a Laravel HTML Mailable (NON Markdown)

I've read several similar questions related to this problem but all refer to Markdown mailables.
I'm trying to send inline images in the mailables but I haven't found a way to do it properly (Laravel 5.5).
The documentation says this:
Inline Attachments
Embedding inline images into your emails is typically cumbersome; however, Laravel provides a convenient way to attach images to your emails and retrieving the appropriate CID. To embed an inline image, use the embed method on the $message variable within your email template. Laravel automatically makes the $message variable available to all of your email templates, so you don't need to worry about passing it in manually:
<body>
Here is an image:
<img src="{{ $message->embed($pathToFile) }}">
</body>
But, when doing that I receive this error:
Undefined variable: message (View: /path/to/project/resources/views/mails/new_user_welcome.blade.php)
I know that this has a limitation when using a Markdown message but I'm not using one.
This are the related files:
Mail/NewUserWelcomeEmail.php
class NewUserWelcomeEmail extends Mailable
{
use SerializesModels;
public function build()
{
return $this->view('mails.new_user_welcome');
}
}
Resources/views/mails/new_user_welcome.blade.php
#extends('layouts.mail')
#section('content')
<img src="{{ $message->embed(url("storage/images/inline_image.png")) }}"
alt="An inline image" />
#endsection
App/Http/Controllers/UserController.php
public function register(NewUserRequest $request)
{
// some code
Mail::to($user)->send(new NewUserWelcomeEmail($user));
return 'done';
}
Well, to be honest, I haven't found a way to make this work properly. I mean, as it stands, this should work. Maybe is my Laravel installation (?)..
Anyway, I did make it work with a workaround.
1) Using Eduardokum' Laravel Mail Auto Embed package, this basically generate a CID for each of your media assets.
But after adding this package this didn't work as expected.. so I:
2) change the way I was referencing my assets, from this:
<img src="{{ url('storage/inline_image.png') }}" />
To this:
<img src="{{ asset('storage/inline_image.png') }}" />
Now it works.
In my case (Larvel 5.5), I've managed, to modify header logo, in both html and markdown.
Laravel documentation, although really great, could be better in this regard.
Anyway, follow these steps, and you should be fine...
1 - Publish mail templates via:
php artisan vendor:publish --tag=laravel-mail
so you can easily modify your mail source files.
2 - Modify message.blade.php in resources/views/vendor/mail/html with this:
#slot('header')
#component('mail::header', ['url' => config('app.url')])
<img src="{{asset('assets/img/pathToYourImage...')}}">
#endcomponent
#endslot
3 - All your emails should receive logo via CID from now.
Note:
In this example Laravel, automatically converts assets to CIDs, so you don't need to call $message->embed(... at all...
Please test extensively, with these html/markdown directories and blade directives going on. It is kinda tricky, but it definitely, does its magic...
if you can use like this than it can be work other wise you don't use $message variable in mail blade
Mail::send('emails.welcome', $data, function ($message) {
$message->from('us#example.com', 'Laravel');
$message->to('foo#example.com')->cc('bar#example.com');
});
if you don't want use this method than you can use like this
https://code.tutsplus.com/tutorials/how-to-send-emails-in-laravel--cms-30046
it can be work like this.
You have to define the File Path Variable in your Mailable as public property -> example $pathToFile.
If you have the file path from outside of the mailable you can pass in with the constructor.
class NewUserWelcomeEmail extends Mailable
{
use SerializesModels;
// Must be public
public $pathToFile;
/**
* Create a new message instance.
*/
public function __construct(string $pathToFile)
{
$this->pathToFile= $pathToFile;
}
public function build()
{
return $this->view('mails.new_user_welcome');
}
}
Then it works as expected in your view like this:
#extends('layouts.mail')
#section('content')
<img src="{{ $message->embed(url($pathToFile)) }}" alt="An inline image" />
#endsection
This way you can embed images in markdown Laravel mails (used here to eg embed a logo):
app/Mail/Demo.php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Swift_Image;
class Demo extends Mailable
{
use Queueable, SerializesModels;
public $image_logo_cid;
/**
* Build the message.
*
* #return $this
*/
public function build()
{
// Generate a CID
$this->image_logo_cid = \Swift_DependencyContainer::getInstance()
->lookup('mime.idgenerator')
->generateId();
return $this->withSwiftMessage(function (\Swift_Message $swift) {
$image = Swift_Image::fromPath(resource_path('img/make-a-wish-logo-rev.gif'));
$swift->embed($image->setId($this->image_logo_cid));
})->subject('My awesome markdown mail with an embedded image')
->markdown('emails.demo');
}
}
resources/views/emails/demo.blade.php
#component('mail::message')
{{-- Just embedding this image in the content here --}}
<img src="cid:{{ $image_logo_cid }}">
#endcomponent
Alternatively you could embed the mail::layout component and put the image in your header:
resources/views/emails/demo.blade.php
#component('mail::layout')
{{-- Header --}}
#slot('header')
#component('mail::header', ['url' => config('app.url')])
<img src="cid:{{ $image_logo_cid }}">
#endcomponent
#endslot
{{-- Body --}}
<!-- Body here -->
{{-- Subcopy --}}
#slot('subcopy')
#component('mail::subcopy')
<!-- subcopy here -->
#endcomponent
#endslot
{{-- Footer --}}
#slot('footer')
#component('mail::footer')
<!-- footer here -->
#endcomponent
#endslot
#endcomponent
Or if you always want this header just edit the resources/views/vendor/mail/html/header.blade.php file (available after php artisan vendor:publish --tag=laravel-mail). Then of course you need to create the CID/Image with every mailable as seen in the app/Mail/Demo.php (or have a base controller for that).

Laravel 5.4^ - How to customize notification email layout?

I am trying to customize the HTML email layout that is used when sending notifications via email.
I have published both the mail and notification views.
php artisan vendor:publish --tag=laravel-mail
php artisan vendor:publish --tag=laravel-notifications
If I modify the /resources/views/vendor/notifications/email.blade.php file, I can only change the BODY content of the emails that get sent. I am looking to modify the footer, header, and every other part of the email layout as well.
I tried also modifying the views inside /resources/vendor/mail/html/, but whenever the notification gets sent, it is not even using these views and instead uses the default laravel framework ones.
I am aware I can set a view on the MailMessage returned by my Notification class, but I want to keep the standard line(), greeting(), etc. functions.
Does anyone know how I can get my notifications to send email using the views in /resources/vendor/mail/html ?
The following is my /resources/views/vendor/notifications/email.blade.php file, but it does not have anywhere to customize the header/footer/ overall layout.
#component('mail::message')
{{-- Greeting --}}
#if (! empty($greeting))
# {{ $greeting }}
#else
#if ($level == 'error')
# Whoops!
#else
# Hello!
#endif
#endif
{{-- Intro Lines --}}
#foreach ($introLines as $line)
{{ $line }}
#endforeach
{{-- Action Button --}}
#if (isset($actionText))
<?php
switch ($level) {
case 'success':
$color = 'green';
break;
case 'error':
$color = 'red';
break;
default:
$color = 'blue';
}
?>
#component('mail::button', ['url' => $actionUrl, 'color' => $color])
{{ $actionText }}
#endcomponent
#endif
{{-- Outro Lines --}}
#foreach ($outroLines as $line)
{{ $line }}
#endforeach
<!-- Salutation -->
#if (! empty($salutation))
{{ $salutation }}
#else
Regards,<br>{{ config('app.name') }}
#endif
<!-- Subcopy -->
#if (isset($actionText))
#component('mail::subcopy')
If you’re having trouble clicking the "{{ $actionText }}" button, copy and paste the URL below
into your web browser: [{{ $actionUrl }}]({{ $actionUrl }})
#endcomponent
#endif
#endcomponent
Run this command
php artisan vendor:publish --tag=laravel-notifications
php artisan vendor:publish --tag=laravel-mail
update for laravel 5.7+
php artisan vendor:publish
and then you will get:
[<number>] Tag: laravel-mail
[<number>] Tag: laravel-notifications
and then just type in that number in front to publish the file for editing
and then in
/resources/views/vendor/mail/html/
you can edit all the components and customize anything you want.
For example i have edited the sentence "All rights reserved". to "All test reserved" at the bottom of that image inside this file:
/resources/views/vendor/mail/html/message.blade.php
and this is what i got:
Make sure to have the right configuration in your config/mail.php :
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
]
],
I wrote an article on how to create a notification and modify your template including the header and footer.
It includes the explanation on how the Laravel components work and how to pass your data to a new email template.
https://medium.com/#adnanxteam/how-to-customize-laravel-5-4-notification-email-templates-header-and-footer-158b1c7cc1c
The most important part is placing the following code inside your email template:
#component('mail::layout')
{{-- Header --}}
#slot('header')
#component('mail::header', ['url' => config('app.url')])
Header Title
#endcomponent
#endslot
{{-- Body --}}
This is our main message {{ $user }}
{{-- Subcopy --}}
#isset($subcopy)
#slot('subcopy')
#component('mail::subcopy')
{{ $subcopy }}
#endcomponent
#endslot
#endisset
{{-- Footer --}}
#slot('footer')
#component('mail::footer')
© {{ date('Y') }} {{ config('app.name') }}. Super FOOTER!
#endcomponent
#endslot
#endcomponent
You can check the medium article in case you want more details on how the components work and how to properly pass the data.
#Brian
You can just make change to the #component directives in your template file to use your custom templates. For example:
Replace #component('mail::message') with #component('vendor.mail.html.message'), assuming your template is located at /resources/views/vendor/mail/html/message.blade.php
I ended up just using a custom view rather than trying to get the built in Laravel ones to work.
I added the following use statement to my Notification class
use Illuminate\Support\Facades\View;
use Illuminate\Support\HtmlString;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
Then in the toMail method:
public function toMail($notifiable)
{
$view_file = 'emails.teamInvitation';
$view = View::make($view_file, ['sender' => $this->sender, 'invitationToken' => $this->invitationToken, 'team' => $this->team ]);
$view = new HtmlString(with(new CssToInlineStyles)->convert($view));
return (new MailMessage)
->subject('PreSource Invitation From ' . $this->sender->name )
->view('emails.htmlBlank', ['bodyContent' => $view]);
}
emails.teamInvitation is my actual email template.
I compile the view in to a string, and then convert the stylesheets to be inline.
emails.htmlBlank is a view file but all it does is echo out bodyContent. This is necessary because the MailMessage->view method expects a view file, and not an HtmlString.
Do NOT do what is suggested here.
This works. Just remember that you should edit the templates contained in the 'vendor/mail/html' folder AND NOT the contents of the 'vendor/mail/markdown' folder, unless of course you are using markdown instead of the line() / greeting() email building functions
Instead, run the artisan commands and then edit the generated files in your resources folder that you end up with. Never overwrite the vendor files, as if you are working on a local version, then push it to a live server and run composer install, you will not have those changes anymore.
Laravel's inheritance allows you to easily overwrite pre-defined methods and files, so take advantage of that for cleaner version control and better ability to roll back changes to core functionality.
You are making email based on component #component('mail::message') This is a default and this is only one described in documentation. This component does not allow you to modify header. However if you look into it's file,
\vendor\laravel\framework\src\Illuminate\Mail\resources\views\markdown\message.blade.php
you will see that it uses another component #component('mail::layout'),
Just copy content of message.blade.php file into your .blade.php and replace {{ $slot }} with what you had in your file before.
And now you have all the flexibility in your file.
Plus
if you want to modify styles, go to file \config\mail.php
and change markdown section like so
'markdown' => [
'theme' => 'default0',
'paths' => [
resource_path('views/vendor/mail'),
base_path('resources/views/emails/vendor'),
],
],
In this case I replaced default theme with my own \resources\views\emails\vendor\html\themes\default0.css
or, if you don't want customising paths - put your default0.css into /resources/views/vendor/mail/html/themes - it is a default path and you don't need to mention it.
Tested on Laravel 5.7
Laravel 5.8
I found email layout in file -> vendor/laravel/framework/src/Illuminate/Mail/resources/views/html/layout.blade.php.
Like I don't use markdown to send my emails, i need of layout default of laravel (yes, because i want :)).
What i did? I sent for me email for me of reset password, saved the email like html and then copied html to my editor and it ready to changes \o/.

Laravel Blade check user role

In laravel Blade templating we can exclude some parts of HTML with this code:
#if (Auth::user())
<li>Mein Profil</li>
<li>Admin</li>
#else
<li>Mein Profil</li>
#endif
If user is authenticated then show home and admin links and if user is not authenticated then show only home link.
My question is how to make a check here if user is admin?
I have default login system from laravel and i just added one more column in table users -> ('admin') with tinyint value 1 and in this video
https://www.youtube.com/watch?v=tbNKRr97uVs
i found the code for checking if user is admin
if (!Auth::guest() && Auth::user()->admin )
and it works in AdminMiddleware.php
but it doesn't work in blade. How to make this working??
I find such a long winded, check if logged in, check role, being added all around my blade files to distracting. You may consider adding a custom blade directive. Add something like this to AppServiceProvider boot() function
Blade::if('admin', function () {
return auth()?->user()?->admin === true;
});
in blade just use
#admin
<p>Only admin sees this</p>
#endadmin
#if (!Auth::guest() && Auth::user()->admin)
<li>Mein Profil</li>
<li>Admin</li>
#else
<li>Mein Profil</li>
#endif
this works just to be clear (just add one more column tinyint 'admin' in user table and set to 1)
You can use the method> HasRole
You can call this from artisan tinker from command line, just to see it before writing code:
php artisan tinker
Check if the user with id 1 has role 'user';
User::find(1)->hasRole('user');
Check if the user with id 1 has role 'admin';
User::find(1)->hasRole('admin');
The same way while coding for example in app.blade template:
#if (Auth::user()->hasRole('admin'))
<li>Main Profile</li>
<li>Admin</li>
#else
<li>Main Profile</li>
#endif
The method hasRoles comes from the package spatie/laravel-permission
composer.json:
"spatie/laravel-permission": "^3.16"
full path of the class:
vendor\spatie\laravel-permission\src\Traits\HasRoles.php

Resources