abraham foto abraham foto - 23 days ago 8
PHP Question

laravel,how i can change the code to return an array?

i have this controller which access the pivot table in many to many relationships. the columns in the pivot table are values and created_at. i want this controller to return me an array of values and created_at

public function status($s_type)
{

$o_health_status = Status::where('name', 'health')->first();
$o_speed_status = Status::where('name', 'speed')->first();

if ($s_type === 'health'){

$o_response = $this->statuses()->where('status_id', $o_health_status->id)
->select('values','created_at')->orderBy('created_at','ASC')->first();

if($o_response === null){
return 'unsigned';
}
$o_response = $o_response->values;
return $o_response;
}else{

$o_response = $this->statuses()->where('status_id', $o_speed_status->id)
->select('values','created_at')->orderBy('created_at', 'desc')->first();
if($o_response === null){
return 'unsigned';
}

$o_response = $o_response->values;
return $o_response;


}

Answer

In laravel, if you need to return an array from the query, you can use pluck() instead of select()

$o_response = $this->statuses()->where('status_id', $o_health_status->id)
    ->pluck('values','created_at')->orderBy('created_at','ASC');// ->first();
//I think you no need to use ->first(); here.