Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB::update laravel 5 raw query

I intend to use laravel db update which equivalent to sql.

update users set username = "admin", status = "active" where user_id = 1

This is the query I test to run. Any wrong?

$username = "admin";
$status = "active";

DB::update('update users set username = '  .$username. ',
status = '.$status.'  where user_id = ?' ,['1']);
like image 448
JohnnyCc Avatar asked Jun 15 '17 05:06

JohnnyCc


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.

How do I get the latest updated record in Laravel?

cust_id') ->select('cust_info.id', DB::raw('MAX(cust_info. updated_at)')) ->orderBy('cust_info.id','DESC') ->first(); In the above query, I write select to get the id of last updated record.

How can I see SQL queries in Laravel?

Simply you can do following stuff using toSql() method, $query = DB::table('users')->get(); echo $query->toSql(); If it's not working you can set-up the thing from laravel documentation.


2 Answers

You should update your query like :

Eloquent Query:

User::where('user_id',1)->update(array(
                         'username'=>$username,
));

Fluent Query:

DB::table('users')->where('user_id',1)->update(array(
                                 'username'=>$username,
));

Hope this helps you

like image 75
AddWeb Solution Pvt Ltd Avatar answered Oct 13 '22 06:10

AddWeb Solution Pvt Ltd


The correct query would be

DB::update('update users set username = ? , status = ? where user_id = ?', ["admin" , "active" , 1]);

OR

User::where('user_id', 1)->update( array('username'=>'admin', 'status'=>'active') );

Where "User" is the model name of "users" table.

like image 45
Anwar Khan Avatar answered Oct 13 '22 06:10

Anwar Khan