Laravel 将数据保存到两个位置

我正在开发一个用户可以创建约会的 larvel 项目。此外,我还创建了另一个名为 clients 的模型,因此当用户创建约会时,会保存用户的“client”数据。


在我的约会控制器中,我有以下内容:-


  public function store(Request $request)

    {


        $this->validate($request, [

            'name' => 'required',

        ]);


        //create appointment

        $apt = new Appointment;

        $apt->name = $request->input('name');

        $apt->user_id = auth()->user()->id;

        $apt->save();


        //create client

        $client = new Client;

        $client->first_name = $request->input('name');

        $client->user_id = auth()->user()->id;

        $client->save();


        return redirect('/appointments')->with('success', 'Appointment created');

    }

保存数据时,它可以工作并将数据存储在客户表中,但是我知道这不是保存数据的最干净的方法,但是这样做的“laravel”方法是什么?


梦里花落0921
浏览 92回答 1
1回答

BIG阳

你的代码没有问题。保持这种状态完全没问题。我更喜欢说 Model::create() 在一个语句中创建模型。public function store(Request $request){    $this->validate($request, [        'name' => 'required',    ]);    Appointment::create([        'name' => request('name'),        'user_id' => auth()->id()    ]);    Client::create([        'first_name' => request('name'),        'user_id' => auth()->id,    ]);    return redirect('/appointments')->with('success', 'Appointment created');}您还可以使用tap()函数:public function store(Request $request){    $this->validate($request, [        'name' => 'required',    ]);    tap(Appointment::create(['name' => request('name'), 'user_id' => auth()->id()]), function ($newAppoinment) {        Client::create([            'first_name' => $newAppoinment->name,            'user_id' => auth()->id,        ]);    });    return redirect('/appointments')->with('success', 'Appointment created');}或者最好的方法可能是使用模型事件:class Appointment extends Model{    public static function boot()    {        parent::boot();        static::created(function ($appointment) {            Client::create([                'user_id' => $appoinment->user_id,                'first_name' => $appoinment->name,             ])        });    }}
打开App,查看更多内容
随时随地看视频慕课网APP