Skip to content
Advertisement

Laravel: Collections gives error because of appends when that perticular field is not selected

Laravel version: 5.7

I have one class Sessions. where I have used appends for the attribute.

class Session extends Model
{
  protected $appends    = ['session_type'];

  public function getSessionTypeAttribute()
  {
     $startTime = $this->getOriginal()['start_time'];
     return $startTime;
  }
}

My query:

$sessions = Session::groupBy(DB::raw('YEAR(created_at), MONTH(created_at), visibility'))
                ->select(DB::raw('COUNT(id) as total,MONTH(created_at) as month,MONTHNAME(created_at) as month_name,visibility'))
                ->orderBy('created_at', 'ASC')
                ->get();

Here I have selected fields that I need but it gives me the following error.

Undefined index: start_time

So here appends are giving error because I have not selected start_time. How to solve this issue?

Advertisement

Answer

Here I got a solution. I make it optional

public function getSessionTypeAttribute()
  {
     $startTime = $this->getOriginal()['start_time'] ?? '';
     return $startTime;
  }

This works properly. It gives the proper results.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement