Home > Enterprise >  Improving the `switch` code with many cases php
Improving the `switch` code with many cases php

Time:03-30

Using: Laravel 8 with Yajra Datatables.

I want to have colors in the column based on the case type!

Currently I am doing it like this:

@switch($report->caseType)
    @case($report->caseType == 'Death')
    @case($report->caseType == 'Theft')
        <span >High</span>
        @break
    @case($report->caseType == 'Bad behavior')
        <span >Medium</span>
        @break
    @default
@endswitch

There will be lots of cases to add into this code (20 cases), is there a way to refactor it/ have less lines of code?

CodePudding user response:

create an associative array and store it in config

$caseType=['Death'=>'High','Theft'=>'High','Bad behavior'=>'Medium'];

so you can just do the following

  <span >{{$caseType[$report->caseType]}}</span>

CodePudding user response:

And why dont just declare an Array with caseTypes as keys?. You can pass this via controller.

$testArray[
    'Death' => [
        'color' => 'danger',
        'text' => 'High'
    'Theft' => [
        'color' => 'danger',
        'text' => 'High'
    ],        
    'Bad behavior' => [
        'color' => 'warning',
        'text' => 'Medium'
    ],
    'Other cases' => [
        'color' => 'other colors',
        'text' => 'text'
    ]
];

So in your blade you can do this:

@foreach ($report->caseTypes as $caseType)
    <span >{{ $testArray[$caseType]['text'] }}</span>
@endforeach

CodePudding user response:

You can refactor your switch cases to using arrays.

  • Create an associative array of all cases with keys as cases and value as color codes.
$cases = [
'Death' => 'danger',
'BadBehaviour' => 'warning',
'Theft' => 'info',
'Life' => 'success'
]; 

  • Then in your view

<span >High</span>

  • Related