Home > Blockchain >  Laravel: Trying to get property 'id' of non-object
Laravel: Trying to get property 'id' of non-object

Time:02-17

this is my code and i dont know where is the problem $evaluationjob = evaluation_elements_jobs::where('job_id', $user->job_id)-> first();

    if($evaluationjob !==null && isset($evaluationjob["element_degree"]))
    {
      $items = json_decode($evaluationjob["element_degree"]);
    }
  

    $evaluation_keies = [];

    foreach ($items as $index => $item)
    {

       $key = evaluation_element::where('id',$index)->where('status',0)->first();
                 //error in the above line
        $reuslt["id"] = $key->id;
        $reuslt["title"] = $key->title

CodePudding user response:

Check if key is an object before access the attributes, I think your query is not returning records then null is returned.

$key = evaluation_element::where('id',$index)->where('status',0)->first();


if(!is_null($key)) {
    $reuslt["id"] = $key->id;
    $reuslt["title"] = $key->title
}

CodePudding user response:

In addition to the answer above, I would like to advise you to use the firstOrFail() method and Eloquent local scopes. From the official docs:

Not Found Exceptions

The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

$key = evaluation_element::where('id',$index)->where('status',0)->firstOrFail();

Query Scopes:

/**
 * Scope a query to only include items with status is 0.
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return void
 */
public function scopeInActive($query)
{
    $query->where('status', 0);
}

Usage scopes:

$key = evaluation_element::where('id',$index)->inActive()->firstOrFail();
  • Related