B
B
bizgrof2018-02-10 15:26:44
Laravel
bizgrof, 2018-02-10 15:26:44

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;
    }

Is this normal, or are there better ways to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-02-10
@bizgrof

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];
}

further use:
And of course, this array will come in handy for you, for example, in the admin panel in the drop-down list to display a list of statuses:
Posts::STATUSES

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question