Answer the question
In order to leave comments, you need to log in
Need advice. Is this a normal switch case in Laravel 5.4 controller?
I want to ask for advice on using switch case in laravel controller.
The bottom line is this: I have a Posts table where the status column is stored.
For my convenience, I put the following possible options in the statuses ('published', 'approval', 'draft')
In the controller, I created a function in which I will check the status and translate into human language:
public function status($status) {
switch ($status) {
case 'draft':
$status = 'Черновик';
break;
case 'published':
$status = 'Опубликовано';
break;
case 'approval':
$status = 'На утверждении';
break;
default:
$status = null;
break;
}
return $status;
}
Answer the question
In order to leave comments, you need to log in
it’s better to make an array constant in the model, in which you translate this case, and also make a method right there in the model to get the status
public const STATUSES = [
'draft' => 'Черновик',
'published' => 'Опубликовано',
'approval' => 'На утверждении',
];
public function getRuStatus(string $status): string
{
if(!isset(self::STATUSES[$status])){
throw new InvalidArgumentException('Status not found.');
}
return self::STATUSES[$status];
}
Posts::STATUSES
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question