Skip to content

Instantly share code, notes, and snippets.

@Thirdwrist
Last active March 15, 2018 01:12
Show Gist options
  • Save Thirdwrist/46f2f753297b745da542f6039bdaf2b5 to your computer and use it in GitHub Desktop.
Save Thirdwrist/46f2f753297b745da542f6039bdaf2b5 to your computer and use it in GitHub Desktop.
How to pass data to mail in Laravel 5

A couple of times when I had to write an application on laravel 5 and I have to send a mail, almost every single time I run into issues passing data to my mail views, and I have to go back to my old codes to find out How I passed data previously, after doing this again a couple of days I decided to document it, might help someone too.

The way to go about this is to inject an instance of a model while instantiating the send mail class. like so:

 public static function clientSendUserMail($Request, $id){

    	$Email =Email::findOrFail($id); 
    	$reciever = User::where("id", $Request->id)->firstOrfail()->Profile->email;
    	
    	Mail::to($reciever)->Send(new ClientSendUserMail($Email));

    	return true;
    }

Here I have the mail I want to send to the user stored in a table called email, I fetch the row from the database then pass it as parameter to my mail class called ClientSendUserMail(),

Then in theClientSendUserMail() class:

{
  use Queueable, SerializesModels;

 
  public $Email;

  public function __construct(Email $Email)
  {
      $this->Email = $Email;
      
  }

  public function build()
  {
      
      return $this->from("[email protected]","Request for interaction")
                   ->view('emails.clientSendUerMail');
  }
}

You create a public variable, then assign the parameter you passed into the class to the public variable in the construct method $this->Email = $Email; (Dependency injection).

This then becomes automatically available to your view like so:


<br><br>Company name : {{$Email->company_name}}

<br><br>Email: {{$Email->company_email}}

<br><br>Mail body: {{$Email->content}}

You can read up on dependency injection in PHP here: http://fabien.potencier.org/what-is-dependency-injection.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment