Laravel : Handle findOrFail( ) on Fail

后端 未结 6 1875
灰色年华
灰色年华 2021-02-13 17:31

I am looking for something which can be like findOrDo(). Like do this when data not found. Something could be like

Model::findOrDo($id,function(){
   return \"Da         


        
6条回答
  •  遇见更好的自我
    2021-02-13 18:24

    A little later for the party, from laravel 5.4 onward, Eloquent Builder supports macros. So, I would write a macro (in a separate provider) like follows.

    Builder::macro('firstOrElse', function($callback) {
       $res = $this->get();
    
       if($res->isEmpty()) {
           $callback->call($this);
       }
    
       return $res->first();
    });
    

    I can then do a retrieval as follows.

    $firstMatchingStudent = DB::table('students')->where('name', $name)
        ->firstOrElse(function() use ($name) {
            throw new ModelNotFoundException("No student was found by the name $name");
        });
    

    This will assign the first object of the result set if it is not empty, otherwise will adapt the behaviour I pass into the macro as a closure (throw Illuminate\Database\Eloquent\ModelNotFoundException in this case).

    For the case of a model also this would work, except that models always return the builder instance.

提交回复
热议问题