90

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.

BenjaminRH
  • 11,974
  • 7
  • 49
  • 76
duality_
  • 17,738
  • 23
  • 77
  • 95

7 Answers7

163

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.

s33h
  • 183
  • 1
  • 8
Laurence
  • 58,936
  • 21
  • 171
  • 212
  • 4
    There's an actual Schema::rename($from, $to) function an Mike Branski mentioned underneath. Use that and it will work regardless of the database. – trm42 Feb 24 '14 at 09:35
  • Why is this the accepted answer when it does not use the proper L4 method `Schema::rename($from, $to)`, as mentioned by me, @trm42, and @Mike Branski ? Please consider changing it to provide other viewers with an up-to-date answer. – Sean the Bean Jan 09 '15 at 23:31
  • 2
    Because the title is "how to run a raw SQL?" but the question includes an example on renaming the table. The question also says `I'd also like to know how to run a raw SQL` - so my answer is for that part. You are correct that the `Schema::rename()` function is useful for the specific case of table renames. – Laurence Jan 10 '15 at 03:27
  • That much is true, but my question was directed toward the OP, @duality_. (BTW, the reason I'd question whether this should be the accepted answer is because it does not provide viewers with the now-standard methods for running raw queries, as documented at http://laravel.com/docs/4.2/database#running-queries. In fact your statement that "There are also some commands to do Schema changes - but renaming a table is not one of them." has not been true since ~Feb 2013. If you want this to remain the accepted answer, I suggest you update it to be more useful to future viewers.) – Sean the Bean Jan 13 '15 at 16:58
17

Actually, Laravel 4 does have a table rename function in Illuminate/Database/Schema/Builder.php, it's just undocumented at the moment: Schema::rename($from, $to);.

Mike Branski
  • 677
  • 1
  • 7
  • 21
  • 4
    And nowadays it's documented in the Laravel 4 and Laravel 4.1 [documentation](http://laravel.com/docs/schema#creating-and-dropping-tables). – trm42 Feb 24 '14 at 09:33
15

You can also use DB::unprepared for ALTER TABLE queries.

DB::unprepared is meant to be used for queries like CREATE TRIGGER. But essentially it executes raw sql queries directly. (without using PDO prepared statements)

https://github.com/laravel/framework/pull/54

smitrp
  • 1,292
  • 1
  • 12
  • 28
  • It works for me when I want to use `DB::query("SET foreign_key_checks=0")`; – swdev Jan 15 '14 at 04:37
  • 1
    @swdev: PDO supports `SET` [queries](http://docs.php.net/pdo#78962). However with `DB::query` (`PDO::query`) it will create a prepared statement unnecessarily because above query has no variable. – smitrp Jan 15 '14 at 09:21
11

The best way to do this I have found so far it to side step Laravel and execute the query directly using the Pdo object.

Example

DB::connection()->getPdo()->exec( $sql );

I usually find it faster and more efficient for a one time query to simply open my database query tool and type the query with full syntax checking then execute it directly.

This becomes essential if you have to work with stored procedures or need to use any database functions

Example 2 setting created_at to a the value you need it to be and side steeping any carbon funkiness

$sql = 'UPDATE my_table SET updated_at = FROM_UNIXTIME(nonce) WHERE id = ' . strval($this->id);
DB::statement($sql);

I found this worked in a controller but not in a migration

Abelgo
  • 129
  • 1
  • 3
  • Awesome, finally a solution that works. I had to use this because I was doing `DB::connection()->getPdo()->exec('USE '.$dbConfig['database']);`. I was dropping and recreating the DB in a Laravel command and needed to do this. – Aditya M P Sep 20 '14 at 16:15
  • 1
    Thanks for your response. We find the easiest way to execute raw create table query – sujivasagam Jul 07 '15 at 05:02
  • 1
    Depending where what the $this-> id is it might be vulnerable to sql injection. – North-Pole May 29 '16 at 23:02
  • Having the ability to execute multiple SQL commands in one string is extremely dangerous if you're injecting any sort of user input into any of the queries. This should be noted in the answer. (See http://php.net/manual/en/function.pg-escape-string.php or http://php.net/manual/en/mysqli.real-escape-string.php for how to prevent this.) In addition, this only answers half of the OP's question (how to run a raw SQL query, not how to rename a table in Laravel 4) or indicate that there is a official solution (see http://laravel.com/docs/4.2/schema#creating-and-dropping-tables). Downvoting. – Sean the Bean Nov 03 '16 at 13:36
9

The accepted way to rename a table in Laravel 4 is to use the Schema builder. So you would want to do:

Schema::rename('photos', 'images');

From http://laravel.com/docs/4.2/schema#creating-and-dropping-tables

If you really want to write out a raw SQL query yourself, you can always do:

DB::statement('alter table photos rename to images');

Note: Laravel's DB class also supports running raw SQL select, insert, update, and delete queries, like:

$users = DB::select('select id, name from users');

For more info, see http://laravel.com/docs/4.2/database#running-queries.

Sean the Bean
  • 5,222
  • 5
  • 38
  • 40
3

This is my simplified example of how to run RAW SELECT, get result and access the values.

$res = DB::select('
        select count(id) as c
        from prices p 
        where p.type in (2,3)
    ');
    if ($res[0]->c > 10)
    {
        throw new Exception('WOW');
    }

If you want only run sql script with no return resutl use this

DB::statement('ALTER TABLE products MODIFY COLUMN physical tinyint(1) AFTER points;');

Tested in laravel 5.1

Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
2

Laravel raw sql – Insert query:

lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .

put below code in your web.php file inside routes directory :

Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});

Now fire above insert query from browser link below :

localhost/yourprojectname/insertintodb

You can see output of above insert query by going into your database table .you will find a record with id 1 .

Laravel raw sql – Read query :

Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .

put below code in your web.php file inside routes directory :

Route::get('/readfromdb',function() {
    $result =  DB::select('select * from posts where id = ?', [1]);
    var_dump($result);
});

now fire above read query from browser link below :

localhost/yourprojectname/readfromdb