How to use queries in pdo way with laravel


Posted on 21 Mar 16 by Vickey

Laravel provide us powerful interface for building SQL queries. We can use a query by using table method.

$myRowQuery = DB::table('users');

Laravel provide other method also 

$userData = DB::first('select * from users where id = 1199');

But in some cases we need to use our row query in pdo way. In laravel we can do this very easily. By getting pdo database connection we can use mysql queries in pdo way. Here are some example

Get pdo database conection

$databaseConection 	= 	DB::connection()->getPdo();
$queryStatement = 	$databaseConection->prepare("SHOW TABLES");
$tables 	= $queryStatement->fetchAll();

For fetch data from a table

$tables = 	$queryStatement->fetchAll();
$queryStatement = $databaseConection->prepare("select * from users where email = :email");
$queryStatement->execute(array(':email' => ""));
$row = $queryStatement->fetch();

Insert record in a table

$queryStatement = $databaseConection->prepare("insert into users (email) values (:email)");
$queryStatement->execute(array(':email' => ''));


If this post help you reduce time to develop, you can help me to maintain this website :)