Search code examples
laraveldatabaseeloquent

Using conditions in laravel accessors


To show application_status in result, I'm using DB::raw statement in my query.

DB::raw('
        CASE
            WHEN status = 0 THEN "Pending"
            WHEN status = 1 THEN "Approved"
            WHEN status = 2 THEN "Declined"
        END AS application_status'
                )

How can I convert or write this in accessor?

Is there any other way to write above in laravel way.

$leave_applications = LeaveApplication::select('leave_type','total_days',DB::raw(
                    '
        CASE
            WHEN status = 0 THEN "Pending"
            WHEN status = 1 THEN "Approved"
            WHEN status = 2 THEN "Declined"
        END AS application_status'
                )
            ))->where('employee_id', $employee_id)->get();

This is my full query.

I read the laravel documentation and search google for above, but did not found anything.

I found the solution which uses ternary operators. But what if we have more than 2 conditions?


Solution

  • In my opinion, in case you're not storing the status in the database you should store it in a constant or config variable. We wanna avoid at all cost having different application_status for a given ID and consistency is the key for a project.

    class LeaveApplication extends Model
    {
    
    public const PENDING_STATUS_NAME = 'Pending';
    public const APPROVED_STATUS_NAME = 'Approved';
    public const DECLINED_STATUS_NAME = 'Declined';
    
    protected $appends = ['application_status'];
    
    public function getApplicationStatusAttribute()
    {
        return match ($this->level) {
            0 => $this::PENDING_STATUS_NAME ,
            1 => $this::APPROVED_STATUS_NAME ,
            2 => $this::DECLINED_STATUS_NAME 
        };
    }
    

    With this you will achieve your dessired application_status in the model.

    I hope I understood your issue correctly.