Abaij
Abaij

Reputation: 873

How to run sql query stored in a variable with Laravel Eloquent?

I want to run a sql query that I store in a variable in Laravel. It's really easy to do in CodeIgniter with just running $this->db->sql($sql). I wonder if there is a way like this in Laravel.

  $sql = "SELECT u.*,c.city_name,prov.province_name FROM users u ".
        "LEFT JOIN cities c ON c.city_id=u.city_id".
        "LEFT JOIN provinces prov ON prov.province_id=u.province_id".
        "WHERE u.id= ?";

I tried to execute it using DB::table($sql) but I guess that's not the way.

EDIT: Using the following is working fine but I still wonder if I just can run something like I do in CI with running $this->db->query($sql).

$user = User::select('users.*','cities.city_name','provinces.province_name')
           ->where('users.id', Auth::id())
           ->leftJoin('cities','cities.city_id','=','users.city_id')
           ->leftJoin('provinces','provinces.province_id','=','users.province_id')
           ->get()->first();

Upvotes: 1

Views: 2245

Answers (3)

PHP Geek
PHP Geek

Reputation: 4033

Try this:

$rows = DB::select(
    DB::raw($sql, array($stringids))
);

Upvotes: 0

Martin Adiputra
Martin Adiputra

Reputation: 189

you can use this

$users = DB::select('select * from users where active = ?', [1]);

refer the docs https://laravel.com/docs/5.7/database#running-queries

so if you

$sql = "SELECT u.*,c.city_name,prov.province_name FROM users u ".
        "LEFT JOIN cities c ON c.city_id=u.city_id".
        "LEFT JOIN provinces prov ON prov.province_id=u.province_id".
        "WHERE u.id= ?";

just try

$query_result = DB::select($sql, [your parameter variable]);

Upvotes: 2

Gio Rodriguez
Gio Rodriguez

Reputation: 146

Create eloquent relationships in models. When there is a relationship between models, you do not have to create a long sql query. You can refer to their documentation. It is really easy to understand. https://laravel.com/docs/5.6/eloquent-relationships

Upvotes: 0

Related Questions