Laravel Query Builder

Laravel Query Builder provides a easy interface to creating and running database queries. It uses PDO parameter binding throughout so our application is protected against SQL injection attacks.

Select

Retrieving All Rows From A Table

$query= DB::table('employee')->get(); // Regular query : SELECT * FROM employee

Using Where Operators

$query= DB::table('employee')->where('salary', '>', 10000)->get(); // Regular query : SELECT * FROM employee Where salary > '10000'

Select Single Row From A Table

DB::table('employee')->where('firstName', 'John')->first(); // Regular query :select * from `student` where `firstName` = 'John' limit 1

Select Single Column From A Row

DB::table('employee')->where('firstName', 'John')->pluck('firstName'); // Regular query :select `firstName` from `student` where `firstName` = 'John' limit 1

Use Distinct in Query

DB::table('employee')->distinct()->select('firstName')->get(); // Regular query :select distinct `firstName` from `student`

Select Two Column From A Table

DB::table('employee')->select('firstName', 'email')->get(); // Regular query :select `firstName`,`email` from `employee`

Using Where Between in Query

DB::table('employee')->whereBetween('id', array(2, 5))->get(); // Regular query :select * from `employee` where `id` between '2' and '5'

Using Order By in Query

DB::table('employee')->orderBy('firstName', 'desc')->get(); // Regular query :select * from `employee` order by firstName desc

Insert

Inserting Records Into A Table

DB::table('employee')->insert(array('email' => '[email protected]','firstName' =>'Maxjoe')); // Regular query :INSERT INTO `employee` (`id`,`firstName`,`email`) VALUES (NULL,'Maxjoe', '[email protected]');

Delete

Deleteing Records Into A Table

DB::table('employee')->where('firstName', '=','Jone')->delete(); // Regular query :delete from `student` where `firstName`='Jone'

Truncating A Table

DB::table('employee')->truncate(); // Regular query :truncate employee

Deleting All Records From A Table

DB::table('employee')->delete(); // Regular query :delete from `employee`

Aggregates Function

Using count() in Query

DB::table('employee')->count(); // Regular query :select count(*) as aggregate from `employee`

Using max() in Query

DB::table('employee')->max(id); // Regular query :select max(`id`) as aggregate from `employee`

Using min() in Query

DB::table('employee')->min('id'); // Regular query :select min(`id`) as aggregate from `employee`

Using sum() in Query

DB::table('employee')->sum('id'); // Regular query :select sum(`id`) as aggregate from `employee`