From d9a6dfa4f46a10feceb67921b78c60a905b7c28c Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Wed, 15 Mar 2017 16:29:57 -0500 Subject: [PATCH] Allow mailable to be rendered directly to views. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This also makes Mailables “Renderable” allowing you to return them directly from a route for easier viewing, etc. --- src/Illuminate/Mail/Mailable.php | 17 ++++++++++++++++- src/Illuminate/Mail/Mailer.php | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Mail/Mailable.php b/src/Illuminate/Mail/Mailable.php index 0d22517f9d46..723d45f6d947 100644 --- a/src/Illuminate/Mail/Mailable.php +++ b/src/Illuminate/Mail/Mailable.php @@ -8,11 +8,12 @@ use Illuminate\Support\Str; use Illuminate\Support\Collection; use Illuminate\Container\Container; +use Illuminate\Contracts\Support\Renderable; use Illuminate\Contracts\Queue\Factory as Queue; use Illuminate\Contracts\Mail\Mailer as MailerContract; use Illuminate\Contracts\Mail\Mailable as MailableContract; -class Mailable implements MailableContract +class Mailable implements MailableContract, Renderable { /** * The person the message is from. @@ -159,6 +160,20 @@ public function later($delay, Queue $queue) ); } + /** + * Render the mailable into a view. + * + * @return \Illuminate\View\View + */ + public function render() + { + Container::getInstance()->call([$this, 'build']); + + return Container::getInstance()->make('mailer')->render( + $this->buildView(), $this->buildViewData() + ); + } + /** * Build the view for the message. * diff --git a/src/Illuminate/Mail/Mailer.php b/src/Illuminate/Mail/Mailer.php index 94f91dda225c..7c2b9ec78c31 100755 --- a/src/Illuminate/Mail/Mailer.php +++ b/src/Illuminate/Mail/Mailer.php @@ -171,6 +171,25 @@ public function plain($view, array $data, $callback) return $this->send(['text' => $view], $data, $callback); } + /** + * Render the given message as a view. + * + * @param string|array $view + * @param array $data + * @return \Illuminate\View\View + */ + public function render($view, array $data = []) + { + // First we need to parse the view, which could either be a string or an array + // containing both an HTML and plain text versions of the view which should + // be used when sending an e-mail. We will extract both of them out here. + list($view, $plain, $raw) = $this->parseView($view); + + $data['message'] = $this->createMessage(); + + return $this->renderView($view, $data); + } + /** * Send a new message using a view. *