Laravel 4 : How to display SQL queries ran? - php

In my app/config/app.php file, I have turned on 'debug'=>true.
I have tried
//run eloquent functions
$allMessages = Messages::with('User')->whereIn('conv_id',$conv_id)->orderBy('created_at','aadesc')->take(10);
$q= DB::getQueryLog();
dd($q);
but it returns an empty array. So I guess it is useless to do end($q) as suggested.
I have also tried the accepted answer to a question and added it to the end of my routes file but nothing happened. I'm still new to Laravel and need some guidance. Thank you!

A popular method is to monitor the Event for Eloquent, and output any queries run on the database as you are going along:
Event::listen('illuminate.query', function($query, $params, $time, $conn)
{
dd(array($query, $params, $time, $conn));
});
$allMessages = Messages::with('User')->whereIn('conv_id',$conv_id)->orderBy('created_at','aadesc')->take(10);
That will output the query that is run.
Another option is to use a Laravel4 Debugger package, which automatically shows you the queries run: https://github.com/barryvdh/laravel-debugbar

Related

Laravel api response time are slow?

I have simple app with simple query to MySQL (select from table without any join). My database records doesn't even reach 1000 record, but the time taken by laravel to get response of a simple select query is over 300-400ms. When i tried in MySQL console, it took no longer than 5ms. Is laravel really that slow? Or something was wrong with my code? Tried using eloquent, query builder, raw query all of them always took over 300ms.
My controller :
public function search(Request $request){
$origin = $request->get('origin');
$destination = $request->get('destination');
$o = explode(",",$origin);
$d = explode(",",$destination);
$response = DB::table('saved_routes')->where([
'from_lat'=>$o[0],
'from_lng'=>$o[1],
'to_lat'=>$d[0],
'to_lng'=>$d[1],
])->get('value');
if($response->isEmpty()){
return response()->json([
['value'=>'Data not found']
]);
}elseif($response[0]->value){
return $response;
}
}
My js api call :
axios.get("/api/savedroutes/search?"+=${origin.lat},${origin.lng}&destination=${destination.lat},${destination.lng}`)
.then(res => {res;})
PS: Im still learning Laravel.
Thanks!
In this case, MySQL has been checked without problems, the query database is not a problem but it takes time to fetch all the data that has been queried on the application => Should use pagination.
You can try using return 1; statement after explode and then after query. Watch the API response time in all 3 scenarios, you will surely get what statement is taking time.
PS: If you want to use full potential of Laravel you should use Eloquent

Laravel query logging missing update queries

I have this code in a controller (Laravel 5.6):
\DB::enableQueryLog();
$foo->update($data);
dd(\DB::getQueryLog());
The problem is that in the dump there is no update query. I know the update command is running (I can see the updated data in the database). What am I missing?
You might have better luck with:
\DB::connection()->enableQueryLog();
$foo->update($data);
dd(\DB::getQueryLog());
Personal choice, but I would even modify it a bit more to:
\DB::connection()->enableQueryLog();
$foo->update($data);
print_r(\DB::getQueryLog());
die();
You might like the output better.
Try Query Builder:
DB::connection()->enableQueryLog();
DB::connection('your-connection')->update($data);
$queries = DB::getQueryLog();
dd($queries);
If that doesn't work out, you might want to check this out.

Why suddenly I started getting No query results for model error in Laravel?

I don't know why I started getting the following error while working on Laravel application.
No query results for model [App\Hotspot].
Here is my Model Function to get user's hotspots.
public function hotspots()
{
return $this->hasManyThrough(Hotspot::class, Operator::class, 'id', 'operator_id');
}
and here is how I am executing the query to get data.
$hotspotId = $id;
$hotspot = Auth::user()->hotspots()->findOrFail($hotspotId);
I started getting this error suddenly. I don't know what went wrong! I tried to find solution on internet but they are totally different cases.
As shown in https://laravel.com/docs/5.4/eloquent-relationships, section Has Many Through.
return $this->hasManyThrough(Hotspot::class, Operator::class, 'user_id', 'operator_id', 'id');
This is necesary due to you are first connecting the Hotspots to he User, after that you are connecting he operations to the Hotspots. therefor his order is correct.
Reason for it working certain times, is because of id clashes, if you used Uuids this code would never work. You can also debug this solution with he following.
DB::enableQueryLog();
// General i feel like Auth::user()->hotspots->where('id', $hotspotId)->first() is more Laravel'sh.
// Like this you will query a lot, if used in wrong cases.
$hotspot = Auth::user()->hotspots()->findOrFail($hotspotId);
dd(DB::getQueryLog());
Or you can get the raw sql, sometimes provides you with a different view.
dd(Auth::user()->hotspots()->toSql());

what is difference between where and find in laravel

when I write this $thread = Thread::find($id); then I write {{$thread->title}} it gives me the title of the thread, but when I write $thread = Thread::where('id','=',$id); then I write {{$thread->title}} it gives me an error.why is that happening?
You should write:
$thread = Thread::where('id','=',$id)->first();
to get one column, else laravel will understand it as array.
You need to call the get() (or any of its variants) method to execute the actual query when using where.
Thread::where('id','=',$id)->get();
Otherwise Thread::where('id','=',$id) just gets you an instance of eloquent's query builder.
find() on the other hand will automatically run a query for whatever it is you want to find by you can't do all sorts of useful stuff (e.g. orderBy, paginate, etc.) that you can very easily pull of using the query builder.

Memcache with Symfony/Doctrine is reloading data

In my symfony project, I have a "complex" query that looks like:
$d = Doctrine_Core::getTable('MAIN_TABLE')
// Create the base query with some keywords
->luceneSearch($keywords)
->innerJoin('w.T1 ws')
->innerJoin('ws.T2 s')
->innerJoin('w.T3 piv')
->innerJoin('piv.T4 per')
->innerJoin('w.T5 st')
...
->innerJoin('doc.T12 docT')
->innerJoin('w.Lang lng')
->execute();
I added all those innerJoin to reduce the number of query due to my data model. Actually all data are recovered with this only query.... but the query took from 2 to 20 sec. depends on keywords.
I decided to use memcache because data are not changing all the time.
What I've done is configuring memcache and adding
...
->useResultCache(true)
->execute();
to my query.
What is strange is that :
The first time (when the cache is empty/flushed), only one query is execute
The second time, ~130 ares executed and it take more time than the first...
Those "new" queries are retrieving data from "inner join" for each record.
What I don't undestand is why "innerjoined" data are not saved in the cache?
I tried to change the hydrate mode but it seems not to be influent.
Someone has an idea?
After a whole day to googlise, to analyse doctrine and become desperate, I found an article that explain the solution:
class User extends BaseUser{
public function serializeReferences($bool=null)
{
return true;
}
}
The problem was the profile object was not getting stored in the result cache and thus causing a query each time it was called from the user object. After much hunting around, a long time in #doctrine, and a few leads from a couple of people, it turns out, by default, Doctrine will only serialize the immediate relation to the main object. However, you can make it so that it will serialize objects further down the line by overriding the function serializeReferences to return true in the class you want to serialize references from. In my example this is the User class. Since our application will never only need the ‘User’ class to be serialized on a result cache I completely overrode the function and made it always return true
http://shout.setfive.com/2010/04/28/using-doctrine-result-cache-with-two-deep-relations/

Categories