Bits Please
Bits Please

Reputation: 897

Laravel Notification Email - Multiple Data

I have this multiple data, I need to send whole data into an email, can anyone help me out?

stdClass Object
(
    [0] => stdClass Object
        (
            [post_id] => 1452
            [No_Of_Workers] => 2
        )

    [1] => stdClass Object
        (
            [post_id] => 1445
            [No_Of_Workers] => 1
        )

)

I need to show

Hi, Below are my data:

Post id: 1452
No of workers: 3

--------------------

Post id: 1445
No of workers: 1

How can I send an array to mail data?

This is my code which I tried:

public function toMail($notifiable)
    {
        echo '<pre>';print_r($this->msg->data); die;
        $mailMessage = (new MailMessage)
            ->replyTo($this->msg->email, 'Hi' . ' ' . 'Jaymin')
            ->subject('Daily Report email')
            ->line($this->msg->data);


        echo '<pre>';print_r($mailMessage); die;
        $mailMessage->line(nl2br('This is peace'));

        return $mailMessage;
    }

This line(), consists of email data which I need to send, I can sent like this:

->line(t('Email Address') . ': ' . $this->msg->email);

But I need to send it in above format, can anyone help me out?

Upvotes: 1

Views: 1395

Answers (1)

mdexp
mdexp

Reputation: 3567

You better use markdown for that. You can generate the notification with the associated markdown view with this artisan command (use it on the root of your laravel project from the console)

php artisan make:notification DailyPostsReportNotification --markdown=mail.posts.report

This will create two files:

  • The notification class in App\Notifications\DailyPostsReportNotification.php
  • The email view that will be rendered in resources\views\mail\posts\report.blade.php

In the notification's toMail method if not already there, you gotta pass the data to your markdown view:

/**
 * Get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
        ->subject('Daily Report Email')
        ->replyTo($this->msg->email)
        ->markdown('mail.posts.report', ['posts' => $this->msg->data]);
}

Important: edit $this->msg->data (if needed) with the variable or property where you have your array of data that you want to print out in the email, since isn't clear how's called from your code.

You can now edit the email view file to display the correct data in your format with markdown syntax:

@component('mail::message')

Hi, below is my data:

@foreach ($posts as $post)
Post id: {{$post->post_id}}<br>
No of workers: {{$post->No_Of_Workers}}<br>

@unless ($loop->last)
--------------------<br>
@endunless
@endforeach

@endcomponent

Upvotes: 2

Related Questions