在 Null Laravel 上调用成员函数 fill()

Call to a Member Function fill() on Null Laravel

我一直在尝试编辑一条记录。如果数据为空,我的代码将创建一条新记录。但是,我收到以下错误:

Call to a member function fill() on null.

我不确定我做错了什么;也许我没有申报?

控制器

<?php

public function auctionUpdate(Request $request, MediaSite $mediaSite)
{
    $auction = $mediaSite->auction;

    DB::transaction(function() use ($request, $mediaSite, $auction){
        $auction->fill($request->only([
           'status', 'start_time', 'end_time', 'period_start_date'
        ]));

        if($auction == null)
            $auction = new Auction();

        $auction->save();
   });

   return view('admin.media-site.show', [
       'mediaSite' => $mediaSite,
       'auction' => $auction
   ]);
}

你应该在 fill() 之前检查 auction 是否为 null

你修改后的脚本

public function auctionUpdate(Request $request, MediaSite $mediaSite)
{
    $auction = $mediaSite->auction;

    DB::transaction(function() use ($request, $mediaSite, $auction){
        if($auction == null)
            $auction = new Auction();

        $auction->fill($request->only([
           'status', 'start_time', 'end_time', 'period_start_date'
        ]));

        $auction->save();
   });



   return view('admin.media-site.show', [
       'mediaSite' => $mediaSite,
       'auction' => $auction
   ]);
}