You know that, we can use and write SQL queries without calling the PHP PDO object in Laravel. But do you know that you can create PDO objects and write raw SQL queries in Laravel application. We can pool database connections in Laravel by using a connection manager like PDO in the Laravel application.

In this tutorial, I will show you how to use and how to create PDO objects and using it how we can write SQL queries in the Laravel application. Let's see the example code of how to use a PDO object to write an SQL query in Laravel:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;

class TutorialController extends Controller
{
    public function __invoke()
    {   
        $pdo = DB::connection()->getPdo();
        $statement = $pdo->prepare('SELECT * FROM users');
        $statement->execute();
        $results = $statement->fetchAll();

        return $results;
    }
}

 

Read also: Laravel Carbon Fetch Current Month Records Query Example

 

Conclusion

In this blog post, we've learned how to use pdo object to write sql query in laravel. By utilizing this PHP PDO object, we can write sql queries in Laravel. Hope this how to use PDO in Laravel tutorial will help you.

Category : #laravel

Tags : #laravel , #laravel query