Search code examples
modellaravel-5.3

Get specific property of a model returns error: Undefined property: Illuminate\Database\Eloquent\Builder::$id


I want to check existence of a model in my Users table and then get it's id property to insert a new record, but get Undefined property error. I read the documentation and some similar questions but they did not work. Can someone please say me how to handle it?

Controller:

$checkExist=Users::where('codeMeli', $codeMeli);

     if (!empty($checkExist))
     {
          $checkOwner=DB::table('user_admin')->whereRaw('userid='.$checkExist->id.' and adminid='.$CurrentUSerID)->get();
          if($checkOwner>0)
          {
               //alert user was added before
          }
          else
          {
               $result= DB::table('user_admin')->insert(['userid'=>$checkExist->id,'adminid'=>$CurrentUSerID]);
          }
      }

error:

Undefined property: Illuminate\Database\Eloquent\Builder::$id


Solution

  • you should use first or get

    $checkExist=Users::where('codeMeli', $codeMeli)->first();