How to Select Custom Column with Value in Laravel Query?
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent Order By Query Example
- Laravel Eloquent orWhere() Condition Example
- Laravel Eloquent WhereIn Query Example
- How to display query log in Laravel 7/6?
- Laravel Eloquent Group By with Multiple Columns Example
- Laravel Select with Sum Query Example
- How to Get Query Strings Value in Laravel?
- Laravel Query Builder Where Exists Example
- Example of unionAll in Query Builder Laravel
- Laravel Join with Subquery in Query Builder Example
- How to Get Query Log in Laravel Eloquent?