Laravel Eloquent Run two update requests?

I was curious to know if laravel eloquent runs only one row refresh request. So I tried the following

Route::get('/cli', function(){ DB::enableQueryLog(); $client = Client::findOrFail(1); $client->first_name = 'Noob'; $client->save(); return response()->json([ 'client' => $client->first_name, 'query' => DB::getQueryLog() ], 200); }); 

This gave me the following result:

 { "client": "Noob", "query": [{ "query": "select * from `clients` where `clients`.`id` = ? limit 1", "bindings": [ 1 ], "time": 0.71 }, { "query": "update `clients` set `first_name` = ?, `updated_at` = ? where `id` = ?", "bindings": [ "Noob", "2017-10-07 12:03:05", 1 ], "time": 3.36 } ] } 

So, I thought about using DB Facade.

 Route::get('/cli', function(){ DB::enableQueryLog(); $client = DB::select("update clients set first_name= 'Admin test' WHERE id=1"); return response()->json([ 'client' => $client->first_name, 'query' => DB::getQueryLog() ], 200); }); 

and result

 { "client": [], "query": [ { "query": "update clients set first_name= 'Admin test' WHERE id=1", "bindings": [], "time": 3.2 } ] } 

In this case, only one request was executed, although it did not return a client instance. My question is, for a high traffic server, which method or strategy do you need to use? Are there any other best practices or techniques for eloquent use?

+5
source share
1 answer

You can change the query below to eloquent

 $client = DB::select("update clients set first_name= 'Admin test' WHERE id=1"); 

to

 $data=['first_name'=>'Admin test']; Client::where('id', '=', 1)->update($data); 

If I understand your question correctly, then in the first request, you select and then update the value so that it certainly executes two requests. In your second method, you donโ€™t think about db, so it will be faster than the first

+4
source

Source: https://habr.com/ru/post/1272419/


All Articles