romulo27's avatar

Notification with Laravel, with the name of the user.

I have a little problem. When the user creates their company on the platform, they receive a notification via email.   The notification is going, and I want to put the user name inside the body of the message, how do I?

Controller-> CompanyController

public function store(CompanyRequest $request)
    {
        $dataForm = $request->all();
        $dataForm['user_id'] = auth()->user()->id;

        // Upload de imagem do S3
        if ($request->hasFile('photo_url')) {
            $file = $request->file('photo_url');
            $name = $file->getClientOriginalName();

            $filepath = 'company/photo_url/' . $name;
            Storage::disk('s3')->put($filepath, file_get_contents($file), 'public');
            $url = Storage::disk('s3')->url($filepath);

            $dataForm['photo_url'] = $url;
        }

        $company = $this->company->create($dataForm);

        // Conveniando o empresa criada para o usuário que está logado
        $user = User::with('company')->find(auth()->user()->id);
        $user->update(['company_id' => $company->id,]);

        // Notifica o usuário quando ele cria a Empresa
        try{
            $user->notify(new CreateNewCompany());
        }
        catch (\Error $error) {
            $company->delete();
            return response()->json(['message' => 'Não foi possivel notificar o Usuário']);
        }


        // Testa a empresa foi criada ou não.
        if (!$company) {
            return response()->json(['message' => 'Não foi possível cadastrar a Empresa']);
        }
        return response()->json(['user' => $user], 201);
    }

Notification -> CreateNewCompany

 public function toMail($notifiable)
    {

        return (new MailMessage)
            ->subject('Sua empresa foi criada!')
            ->greeting('Olá, { $user }')
            ->line('Obrigado por se cadastrar. Sua conta já está ativa!')
            ->line('Obrigado por usar nossa plataforma!');
    }
0 likes
5 replies
Cronix's avatar

$notifiable should be the user object?

->greeting('Olá, ' . $notifiable->name)
romulo27's avatar

I dont Know, look.

class CreateNewCompany extends Notification
{
    use Queueable;

    private $user;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {

        return (new MailMessage)
            ->subject('Sua empresa foi criada!')
            ->greeting('Olá,' . $this->user->name)
            ->line('Obrigado por se cadastrar. Sua conta já está ativa!')
            ->line('Obrigado por usar nossa plataforma!');
    }
Cronix's avatar
Cronix
Best Answer
Level 67

Did you look at what I did? All I did was use the $notifiable object being passed into the toMail() method.

    public function toMail($notifiable)
    {

        return (new MailMessage)
            ->subject('Sua empresa foi criada!')
            ->greeting('Olá,' . $notifiable->name)
            ->line('Obrigado por se cadastrar. Sua conta já está ativa!')
            ->line('Obrigado por usar nossa plataforma!');
    }
1 like
romulo27's avatar

Yes, i saw. So I do not need the Method Construct()?

romulo27's avatar

I'll leave the other way here for someone to need.

Controller
public function store(CompanyRequest $request)
    {
        $dataForm = $request->all();
        $dataForm['user_id'] = auth()->user()->id;

        // Upload de imagem do S3
        if ($request->hasFile('photo_url')) {
            $file = $request->file('photo_url');
            $name = $file->getClientOriginalName();

            $filepath = 'company/photo_url/' . $name;
            Storage::disk('s3')->put($filepath, file_get_contents($file), 'public');
            $url = Storage::disk('s3')->url($filepath);

            $dataForm['photo_url'] = $url;
        }

        $company = $this->company->create($dataForm);

        // Conveniando o empresa criada para o usuário que está logado
        $user = User::with('company')->find(auth()->user()->id);
        $user->update(['company_id' => $company->id,]);

        // Notifica o usuário quando ele cria a Empresa
        try{
            $user->notify(new CreateNewCompany($user));
        }
        catch (\Error $error) {
            $company->delete();
            return response()->json(['message' => 'Não foi possivel notificar o Usuário']);
        }


        // Testa a empresa foi criada ou não.
        if (!$company) {
            return response()->json(['message' => 'Não foi possível cadastrar a Empresa']);
        }
        return response()->json(['user' => $user], 201);
    }

class CreateNewCompany extends Notification
{
    use Queueable;

    private $user;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {

        return (new MailMessage)
            ->subject('Sua empresa foi criada!')
            ->greeting('Olá, ' . $this->user->name)
            ->line('Obrigado por se cadastrar. Sua conta já está ativa!')
            ->line('Obrigado por usar nossa plataforma!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

I passed a parameter in the notify class and construct the construct in the notification class.

Please or to participate in this conversation.