Pages

LARAVEL Running Raw SQL Queries

In Laravel, Once you have configured your database connection, you may run queries using the  DB facade. The DB facade provides methods for each type of query: select, update,  insert, delete, and statement.

Running A Select Query
To run a basic query, you may use the select method on the DB facade:
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    /**
     * Show a list of all of the application's users.
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::select('select * from users where active = ?', [1]);

        return view('user.index', ['users' => $users]);
    }
}


the first argument passed to the select method is the raw SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the where clause constraints. Parameter binding provides protection against SQL injection.

The select method will always return an array of results. Each result within the array will be a PHP stdClass object, allowing you to access the values of the results:
foreach ($users as $user) {
    echo $user->name;
}
Using Named Bindings
Instead of using? to represent your parameter bindings, you may execute a query using named bindings:
$results = DB::select('select * from users where id = :id', ['id' => 1]);

1 comment:

  1. I hope you would be doing well. Dear admin your site is really easy to understand and one of the best in the town. I had gone through your site and I can confidently say that your site is free of bugs. Therefore, everyone should use this website. However, we also provide website development tools. Here is the link of our site jsononline

    ReplyDelete

Popular Posts