Laravel query builder example


Instead of hand coding SQL code on your application, you should try to use query builder in laravel, in this article i will show some of the query builder example, so you can learn them.

Using query builder not only makes your code easier to read and cleaner, but also there are something that laravel do behind the scene, such as prevent sql injection.

The benefit of using query builder is that you can use it without having to create a model, normally you need to create a model for each table if you want to do query using eloquent. But with query builder you just need to specify the table name.

SQL query code
select * from users

Laravel query builder code 
DB::table('users')->get();

More examples of query builder:

Add where statement to query builder
$users = DB::table('users')->where('id', '=', 1)->get();

Add multiple where statement to query builder
$users = DB::table('users')->where('id', '=', 2)->where('email', 'like', '%yahoo.com%')->get();

Add orWhere statement
$users = DB::table('users')->where('id', '=', 1)->orWhere('id', '=', 2)->get();

Getting only one record
$users = DB::table('users')->first();

Getting all matching record
$users = DB::table('users')->get();

Counting the record
$users = DB::table('users')->count();

Selecting specific fields
$users = DB::table('users')->select('id', 'name')->get();

inner join
$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();

left join
$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();



EmoticonEmoticon