Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: how to run a raw SQL?

I want to rename a table in Laravel 4, but don't know how to do that.

The SQL is alter table photos rename to images. If there is an Eloquent solution, I'd also like to know how to run a raw SQL, cause sometimes there's just no alternative.

like image 526
duality_ Avatar asked Feb 04 '13 13:02

duality_


People also ask

What is DB :: Raw in Laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.

What is raw query?

On the other hand, RawQuery serves as an escape hatch where you can build your own SQL query at runtime but still use Room to convert it into objects. RawQuery methods must return a non-void type. If you want to execute a raw query that does not return any value, use RoomDatabase#query methods.

Should I use raw SQL or ORM?

ORM is good only for developers and maintenance because most developers aren't very good at SQL, but if you're actually talking about performance, SQL completely trumps it.


1 Answers

In the Laravel 4 manual - it talks about doing raw commands like this:

DB::select(DB::raw('RENAME TABLE photos TO images')); 

edit: I just found this in the Laravel 4 documentation which is probably better:

DB::statement('drop table users'); 

Update: In Laravel 4.1 (maybe 4.0 - I'm not sure) - you can also do this for a raw Where query:

$users = User::whereRaw('age > ? and votes = 100', array(25))->get(); 

Further Update If you are specifically looking to do a table rename - there is a schema command for that - see Mike's answer below for that.

like image 165
Laurence Avatar answered Sep 28 '22 01:09

Laurence