Search code examples
phplaravelnotifications

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 Company

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!');
}

Olá, { $user } Obrigado por se cadastrar. Sua conta já está ativa!

    Obrigado por usar nossa plataforma!

    Regards,<br>Laravel

Solution

  • In this case your user is the $notifiable object which is passed to the toMail method, so you can access the user like so:

    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!');
    }
    

    ->name being the field from your users table which contains the users name.