Call to a member function extension() on null

 public function store(Request $post)
    {  
        $validated = $post->validate(['eId'=>'required','about'=>'required']);
        
        $edocsId = $post->id;
        
        if($edocsId){
            
            $edocs = Edocs::find($edocsId);
            
            if($post->hasFile('scan')){
                $file = time().'.'.$post->scan->extension();
                $post->scan->storeAs('public/uploads/images',$file);
                $edocs->scan = 'storage/uploads/images/'.$file;     
            }   
         }else{
            $file = time().'.'.$post->scan->extension();
            $post->scan->storeAs('public/uploads/images',$file);
            $edocs = new Edocs;
            $edocs->scan = 'storage/uploads/images/'.$file;
         }
         
        $edocs->eId = $post->eId;
        $edocs->about = $post->about;
        $edocs->user_id = Auth::user()->id;
        $edocs->save();
            
        return response()->json($edocs);
    }

Выдает эту ошибку при редактировании: Call to a member function extension() on null, выдает поле картинки пустым


Ответы (1 шт):

Автор решения: gregman
  1. Предположу что в строчке

    $file = time().'.'.$post->scan->extension();

есть обращение к extension() к объекту scan, которого нет в объекте $post.

  1. В коде присутствует дублирование кода - это плохо, поэтому в коде возникла эта ошибка.

    if($post->hasFile('scan')){
        $file = time().'.'.$post->scan->extension();
        $post->scan->storeAs('public/uploads/images',$file);
        $edocs->scan = 'storage/uploads/images/'.$file;     
    }
    
  2. Чтобы этого избежать в laravel есть элегантный метод firstOrNew тогда код станет еще и короче.

    public function store(Request $post) 
    {
        $validated = $post->validate(['eId'=>'required','about'=>'required']);
        $edocsId = $post->id;
        $edocs = Edocs::firstOrNew($edocsId);
        if($post->hasFile('scan')){
             $file = time().'.'.$post->scan->extension();
             $post->scan->storeAs('public/uploads/images',$file);
             $edocs->scan = 'storage/uploads/images/'.$file;
         }
        $edocs->eId = $post->eId;
        $edocs->about = $post->about;
        $edocs->user_id = Auth::user()->id;
        $edocs->save();
    
        return response()->json($edocs);
    }
    
→ Ссылка