0
 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 ответ 1

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

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.