ehmhrgelcighsawmlv
ehmhrgelcighsawmlv

Reputation: 309

How to change collection column value in laravel

I have a laravel collection that's like this:

$loan = Loans::where([
            ['OL_TEMP_APP_NO', $appNo]
        ])
        ->get();

The $loan collection returns principal, terms, code. The code corresponds to a string. Example 1 = new, 2 = processing, 3 = approved.

How do I parse the values under code before sending them to the view?

Upvotes: 0

Views: 330

Answers (2)

Piash
Piash

Reputation: 1131

if you already know the value of code, or code will always have some fixed values, then you can use like following:

public function getAll(){
   // ...
    $loans = Loans::where([['OL_TEMP_APP_NO', $appNo]])->get();
    $data = [];
    foreach($loans as $loan){
        $code = Code::getValue($loan->code);
        $data[] = [
              'principal' => $loan->principal, 
              'terms' => $loan->terms, 
              'code' => ($loan->code == 1) ? 'new' : ( ($loan->code == 2) ? 'processing' : 'approved') 
              ]
    }

    return $data;
}

Upvotes: 1

TsaiKoga
TsaiKoga

Reputation: 13394

You can use CASE WHEN to convert the integer to string code:

$loan = Loans::where([
            ['OL_TEMP_APP_NO', $appNo]
        ])
        ->select('principal', 'terms', DB::raw("
           (CASE code
            WHEN 2 THEN 'processing'
            WHEN 3 THEN 'approved'
            ELSE 'new' END) AS code
        "))
        ->get();

Upvotes: 1

Related Questions