Search code examples
phplaravelruntime-errornull-pointerlaravel-controller

Call to a Member Function fill() on Null Laravel


I've been trying to edit a record. My code will create a new record if the data is null. However, I get the following error:

Call to a member function fill() on null.

I'm not sure what I did wrong; maybe I didn't declare?

Controller

<?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
   ]);
}

Solution

  • You should check if auction is null before fill()

    your modified script

    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
       ]);
    }