1

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();
1
  • As @Martin Adiputra said you need to use DB::select and pass parameters as shown in answer Commented Sep 12, 2018 at 4:57

3 Answers 3

2

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

yes, i have no problem with this. but I'm looking to possibility of other way which I think is easier for me
0

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

1 Comment

definitely will learn about this but I have no time at the moment so I'm still looking to other solution closer to what I expect
0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.