skip to Main Content

When I’m going to update the SEO as admin from the frontend it shows me the error

Attempt to read property "id" on null

enter image description here

This is my controller code

public function updateSEO(Request $request)
    {
        // first, get the language info from db
        $language = Language::where('code', $request->language)->first();
        $langId = $language->id;

        // then, get the seo info of that language from db
        $seo = SEO::where('language_id', $langId)->first();

        // else update the existing seo info of that language
        $seo->update($request->all());

        $request->session()->flash('success', __('Updated successfully!'));

        return redirect()->back();
    }

This is my view code

<div class="form-group">
    <label>{{ __('Meta Description For Home Page') }}</label>
    <textarea class="form-control" name="home_meta_description" rows="5"
        placeholder="{{ __('Enter Meta Description') }}">{{ $data->home_meta_description }}</textarea>
</div>

2

Answers


  1. i think the error is in this line

     $language = Language::where('code', $request->language)->first();
    

    before using the $language first check if the above return any data or not when it doesn’t return something then it will show error
    do like this try this code hope you get

    if($language){
    
       $langId = $language->id; 
    }else{
      echo 'no data found';
      exit;
    }
    
    Login or Signup to reply.
    1. Use early exit
    2. You may use session flash message like success,error and warning.
        public function updateSEO(Request $request)
        {
            // first, get the language info from db
            $language = Language::where('code', $request->language)->first();
            if($language === null) {
                $request->session()->flash('error', __('No Language found!'));
    
                return redirect()->back();
            }
            $langId = $language->id;
    
            // then, get the seo info of that language from db
            $seo = SEO::where('language_id', $langId)->first();
    
            // else update the existing seo info of that language
            $seo->update($request->all());
    
            $request->session()->flash('success', __('Updated successfully!'));
    
            return redirect()->back();
        }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search