How to Select Custom Column with Value in Laravel Query?

By Hardik Savani November 5, 2023 Category : Laravel

Hi,

This tutorial will provide example of laravel query add custom column. you'll learn add custom column in laravel query. I’m going to show you about add a new column with a value to the select query in laravel. I’m going to show you about laravel query static value with column name. follow bellow step for how to select custom column values in laravel query.

Sometime, we need to add column with static value like tax and any for calculation on your laravel eloquent query. so here, i will give you very simple example for adding custom column with value.

let's see bellow example:

Example:

<?php

namespace App\Http\Controllers;

use App\Models\Product;

use DB;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$products = Product::select([

"id",

"name",

DB::raw("'10%' as tax"),

DB::raw("1 as active")

])->get();

dd($products->toArray());

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[name] => Samsung Galaxy

[tax] => 10%

[active] => 1

)

[1] => Array

(

[id] => 2

[name] => Apple iPhone 12

[tax] => 10%

[active] => 1

)

[2] => Array

(

[id] => 3

[name] => Google Pixel 2 XL

[tax] => 10%

[active] => 1

)

[3] => Array

(

[id] => 4

[name] => LG V10 H800

[tax] => 10%

[active] => 1

)

)

i hope it can help you...

Shares