Home > database >  (error )Trying to get property 'id' of non-object laravel8
(error )Trying to get property 'id' of non-object laravel8

Time:01-03

I am trying to store data by using id as primary key in Laravel 8, I used following code in controller :

  public function store(Request $request)
    {
        $job = new Job();
        $job->employeer_id = Auth()->user('employeer')->id;
      
        $job->category = $request->category_name;
        $job->job_context = $request->job_context;
        $job->keywords = $request->keywords;
        $job->title = $request->title;
        $job->vacancy = $request->vacancy;
        $job->deadline = $request->deadline;
        $job->employment_type = $request->employment_type;
        $job->location = $request->location;
        $job->gender = $request->gender;
        $job->age = $request->age;
        $job->responsibilities = $request->responsibilities;
        $job->education = $request->education;
        $job->requirements = $request->requirements;
        $job->additional_requirements = $request->additional_requirements;
        $job->salary = $request->salary;
        $job->benifits = $request->benifits;
        $job->apply_instruction = $request->apply_instruction;

        $job->save();
        Category::where('category_name', '=' , $request->category_name)->increment('no_jobs', 1);
        return redirect('/jobs');
    }

The error says that : Trying to get property 'id' of non-object in this line :

        $job->employeer_id = Auth()->user('employeer')->id;```

CodePudding user response:

Instead of

Auth()->user('employeer')->id;

use

Auth::guard('employeer')->id();

or

auth('employeer')->user()->id;

CodePudding user response:

Check if you get the user first

Auth::guard('employeer')->check();

Then put your code in condition if the user object exist.

So basically you should do this

if(Auth::guard('employeer')->check()){
    $job = new Job();
    $job->employeer_id = Auth::guard('employeer')->user()->id;

    // rest of the code
    
}else{
    // handle as you want 
}
  • Related