Laravel Eloquent selectRaw() Query Example

By Hardik Savani | July 22, 2020 | Category : Laravel


Hello all! In this article, we will talk about laravel selectraw example. you'll learn selectraw query in laravel example. it's simple example of laravel add select raw. I’m going to show you about laravel selectraw field. you will do the following things for laravel eloquent selectraw.

In this example i will give you very simple example of how to use selectRaw in laravel application. you can easily use it with laravel 6, laravel 7 and laravel 8 application.

So, let's see bellow examples that will help you how to use selectRaw() eloquent query in laravel.

Example 1:

SQL Query:

select *, amount + ? as amount_with_bonus

from `users`

Laravel Query:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$users = User::select("*")

->selectRaw('amount + ? as amount_with_bonus', [500])

->get();

dd($users);

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[name] => Prof. Josiane Jast MD

[email] => [email protected]

[email_verified_at] => 2020-07-01T09:34:13.000000Z

[created_at] => 2020-07-03T09:34:13.000000Z

[updated_at] => 2020-07-01T09:34:13.000000Z

[status] => 1

[first_name] =>

[last_name] =>

[point] =>

[points] => 0

[amount] => 1000

[amount_with_bonus] => 1500

)

[1] => Array

(

[id] => 2

[name] => Mr. Donavon Beer

[email] => [email protected]

[email_verified_at] => 2020-07-01T09:34:13.000000Z

[created_at] => 2020-07-02T09:34:13.000000Z

[updated_at] => 2020-07-01T09:34:13.000000Z

[status] => 1

[first_name] => Hardik

[last_name] => Savani

[point] =>

[points] => 0

[amount] => 1000

[amount_with_bonus] => 1500

)

)

Example 2:

Laravel Query:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use DB;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$users = User::select("*")

->select('*', DB::raw('amount + 500 as amount_with_bonus'))

->get();

dd($users);

}

}

I hope it can help you...




Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. 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, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: