twigg
twigg

Reputation: 3993

PHP run a raw SQL query in eloquent model

I'm trying to use Eloquent ORM from Laravel in my own legacy project. I have the models set-up and Eloquent is working fine but I can't understand how to run a raw SQL query using the eloquent database connection inside the model. I need to run raw SQL queries for now until I can refactor the entire code base over to use the ORM.

namespace App\Providers;

use Illuminate\Database\Capsule\Manager;
use League\Container\ServiceProvider\AbstractServiceProvider;

class DatabaseServiceProvider extends AbstractServiceProvider
{

    protected $provides = [
        Manager::class
    ];

    public function register()
    {

        $container = $this->getContainer();

        $config = $container->get('config');

        $config = $config->get('db.mysql');

        $capsule = new Manager;

        $capsule->addConnection([
            $config
        ]);

        $capsule->setAsGlobal();
        $capsule->bootEloquent();

        $container->share(Manager::class, function () use ($capsule){
            return $capsule;
        });

    }

}

Now in my model I have the following:

namespace App\Models;

use Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent
{
    protected $table = '_users';
}

Then I'm trying to call that model in my controller:

namespace App\Controllers;

use App\Views\View;
use App\Models\User;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class HomeController
{

    protected $view;

    public function __construct(View $view)
    {
        $this->view = $view;
    }

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        $user = User::find(1);

        dump($user);

    }
}

So this all works nicely but I can't figure out how to run a raw query inside of the model? Obviously the below won't work but I want something like that, creating a new function and it returns the result:

Model:

public function customQuery()
{
    $query = 'SELECT * FROM _users';
    return $query;
}

Controller:

$user = new User;
$user->customQuery();

Upvotes: 2

Views: 22080

Answers (5)

Vipul
Vipul

Reputation: 941

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. Check this ref. link, with more details: http://fideloper.com/laravel-raw-queries

Example of \DB::raw and \DB::select

Upvotes: 2

Amitesh Bharti
Amitesh Bharti

Reputation: 15713

Laravel makes interacting with databases extremely simple across a variety of database backends using either raw SQL, the fluent query builder, and the Eloquent ORM.

All three has there own standard syntax format.

Recommendation : You should not create raw SQL inside model instead you can create even in controller (Though its recommended to follow repository pattern) but as a beginner following step will give you your expected result

Update your HomeController for following

  1. Use the Illuminate\Support\Facades\DB;
  2. Update the index method

    public function index()
    {
        $users = DB::select('SELECT * FROM users');
    
        dd($users);
    }
    

Reference : https://laravel.com/docs/5.6/database#running-queries

Laravel is great framework. Keep learning !!

Upvotes: 9

FULL STACK DEV
FULL STACK DEV

Reputation: 15961

use Laravel scopes() this way you can easily use eloquent syntax.

$user = new User::customQuery();

public function scopeSustomQuery($query)
{
    $query = $query->where('You condition');
    return $query;
}

Upvotes: 0

Piterden
Piterden

Reputation: 789

Try this and never use any raw queries in Laravel

/* @var User $query */
$user = new User();

/* @var Builder $query */
$query = $user->newQuery();

dd($query->select('*')->from('_users')->get());

Upvotes: 0

mehlichmeyer
mehlichmeyer

Reputation: 154

try the whereRaw() function

https://laravel.com/docs/5.6/queries

From Documentation:

The whereRaw and orWhereRaw methods can be used to inject a raw where clause into your query. These methods accept an optional array of bindings as their second argument:

$orders = DB::table('orders') ->whereRaw('price > IF(state = "TX", ?, 100)', [200]) ->get();

Upvotes: 0

Related Questions