0

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
   ]);
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
  • What is `MediaSite`? What is being passed to your function for the `$mediaSite` argument? Presumably, `$mediaSite->auction` is `null`. Should you perhaps move your `if($auction == null) $auction = new Auction();` up above `$auction->fill()`? – Phil Nov 28 '18 at 04:00
  • MediaSite is a model that also has link to Auction model. I want to edit the auction data through media site model – Adilah Abdullah Nov 28 '18 at 04:04
  • You should check for null and give an error the earliest you can. The validating code should check external output, being only in the outer parts of the code not in the inner code. **Avoid Defensive Programming, Fail Fast Instead** https://stackoverflow.com/a/490500/2739274 – David Lemon Nov 28 '18 at 09:05

1 Answers1

1

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
   ]);
}
Emtiaz Zahid
  • 2,645
  • 2
  • 19
  • 35