Saturday, 8 October 2016

How to use DB Facade for query in laravel

Facades : It provide a "static" interface to classes that are available in the application's service container.The facades serve as "static proxies" to underlying classes in the service container , providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

Laravel raw query


In this post i will show you how to use DB facade for db operations. In sometime you need to use direct query without using model class. So you can use the direct DB facade for all the insert, update,select operation in database.

You can use it by adding a namespace.

use DB;

Or


$result = \DB::table('tablename')->get();//You have to tell PHP it is in the root namespace.
echo "<pre>";print_r($result);

Laravel insert query :


DB::table('users')->insert(array("name"=>'Mac',"email"=>'mac@wantcode.in',"age"=>18));

Laravel insert multiple records :


DB::table('users')->insert(array(
array("name"=>"mac","email"=>"mac@wantcode.com"),
array("name"=>"john","email"=>"john@wantcode.com"),
array("name"=>"jimmy","email"=>"jimmy@wantcode.com")
);


Laravel update query example:


DB::table('users')->update
    ->where("id",'10')
    ->update(array("name"=>'Mac'));

Laravel where clause query:


DB::table('users')->where('age', '>',10)->get();

Laravel group by query:


DB::table('users')->groupBy('age')->get();

Laravel delete query : 


DB::table('users')->where('id', '=', 1)->delete();

Laravel truncate table :


DB::table('users')->tuncate();

I hope you like the post . please comment below for help or suggestion.


Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts