Jack Hales
Jack Hales

Reputation: 1654

Laravel 5: How to run a RAW MySQL statement?

So I have been moving from framework to framework and one feature that I liked about CodeIgniter over Laravel was that it supplys Raw statements.

I did some research on Laravel and the statements that they can supply and I found the DB::raw($sql) statement.

I tried initially to do the statement like so:

$query = DB::raw("SELECT * FROM users WHERE username = 'admin');
foreach ($query as $q) {
  $id = $q['id'];
}

but that didnt manage to work, so I did some more research looking at stack overflow questions and I managed to find the structure was a bit different, so I tried:

$query = DB::select(DB::raw("SELECT * FROM users WHERE username = 'admin');

then used the same foreach loop as I did in the first part to try to loop the data.

If this is the wrong way of using this method please let me know, also, I'm not planning on keeping this method for using raw statements and getting user data, I just am trying to know that is it able to be used.

Upvotes: 1

Views: 1760

Answers (1)

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

use get() function :

DB::table('users')->select('*')->where('username', '=', 'admin')->get();

Upvotes: 3

Related Questions