将变量从控制器传递到Laravel中的通知

时间:2019-10-26 12:09:56

标签: laravel notifications

我发现很难理解文档中的示例以及所遇到的情况。在我的项目中,我有一个由用户填写的申请表,然后一旦申请被批准,取消等,管理员将更新该表。

现在我想通知用户他/他的申请已被批准,取消等。

在我的控制器中:

public function update(Request $request, $id)
{
    $this->validate($request, [
        'status' => 'required'
    ]);
    $requestData = $request->all();

    $loanapplication = LoanApplication::findOrFail($id);

    $loanapplication->update([
        "status"        => $request->status,
        "admin_notes"   => $request->admin_notes,
        "date_approval" => $request->date_approved
    ]);    

    if($request->notifyBorrower = 'on') {

        $user_id = $loanapplication->user_id;
        $status = $request->status;
        $this->notify(new AdminResponseToApplication($user_id));   
    }

    return redirect()->back()->with('flash_message', 'LoanApplication updated!');
}

在我的AdminResponseToApplication.php中,我想要实现这一目标

<?php
namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class AdminResponseToApplication extends Notification implements ShouldQueue
{
    use Queueable;  
    public function __construct()
    {
        //
    }

    public function via($notifiable)
    {
        return ['mail','database'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->line(.$user->nameHere. 'your application has been '.$statusHere.'.')
            ->action('check it out', url('/'))
            ->subject('Regarding with your loan application')
            ->line('This is system generated. Do not reply here.');
    }

    public function toDatabase($notifiable)
    {
        return [
            'user_id' => $user->nameHere,
            'status' => $statusHere,
            'title' => .$user->nameHere. 'your application has been '.$statusHere.'.',
            'url' => '/'
        ];
    }
}

我该如何实现?预先谢谢你!

1 个答案:

答案 0 :(得分:2)

获取用户对象并在其上调用函数notify()。 $ this-> notify()将不起作用,因为 $ this 不是User类的实例。

$user = User::find($user_id);
通知类中的$user中的

$user->notify(new AdminResponseToApplication($data))$notifiable中可用。

您可以使用 $ notifiable-> name 等获取该对象的任何值。

记住

AdminResponseToApplication 是一个类,您可以使用php类可以执行的任何操作。

因此,您可以根据需要将任意数量的变量传递给构造函数中的 AdminResponseToApplication 类并执行所需的操作。

$user->notify(new AdminResponseToApplication($data))

如上所示,我正在向构造函数中可用的类发送 $ data 对象。

在班上

class AdminResponseToApplication extends notification implements ShouldQueue{
    use Queueable;

    public $myData;
    public function __construct($data)
    {
        $this->myData = $data;  //now you have a $data copied to $this->myData which
        // you can call it using $this->myData in any function of this class.
    }

}