Laravel Eloquent Query causes Application to continuously load - php

I wrote the following eloquent query for a table in my application and now the application won't stop loading. what i need is to understand what is wrong with it and how to fix it
$customer_purchased_1_time=DB::table("data as t1")->select('vin','last_service')
->where('type',1)->distinct('vin')
->whereRaw("(select count(*) from data where t1.vin=data.vin and data.type=1)=1")
->count();
It is the only code in my controller method along with the return statement. the incrementing of x was for debugging

I solved it already. and this code worked fine for me
$customer_purchased_1_time=count(DB::table("data as t1")
->select('vin','last_service',DB::raw("count(*) as count"))
->where('type',1)
->distinct('vin')
->having("count","=",1)
->get());

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

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());

Call to undefined method query\builder::with()

The following code worked fine but now i need to select only particular set of records from the table based on the authenticated user. How can i achieve this? thank you.
Worked code
$spares = \App\Spares::with('brand','model')->paginate(5);
New code that i need to get(need to select only the spares that are related to a particular retailer )
$spares = DB::table('spares')->where('retailer_id', '=', $retailer_id)->with('brand','model')->paginate(5);
When i run the code it gets me the error as follows
You cannot use with() with the Class DB - QueryBuilder, if you want to make it work then convert it into Models which should extends Eloquent class, this is how you can do this:
Spare::with('brand', 'model')
->where('retailer_id', $retailer_id)
->paginate(5);
Hope this helps!

GroupBy and OrderBy Laravel Eloquent

Building a chat application with a dashboard and am trying to get a notification of the last message the that other user sent.
Here is my Model relationships:
public function messages() {
return $this->hasMany('App\Message', 'author_id');
}
public function lastMessage() {
return $this->hasMany('App\Message', 'recipient_id')->orderBy('created_at', 'DESC')->groupBy('author_id');
}
On thing I cant figure out is instead of returning the last message as it should be sorted by using orderBY, it returns the first record of that group that exists in the database.
Looked around online but cant seem to find any info on this. The only thing I found is a post by someone who said that orderBy and groupBy in laravel don't play well together.
Any help is appreciated!
Instead of redefining the relationship in lastMessage, you might try calling messages from it and then running your query from that.
Without seeing more of your model schema (ie: where are these relationships defined??), this might not be perfect, but it's a start:
public function lastMessage()
{
return $this->messages() // <-- Notice the ()...this creates a query instead of immediately returning the relationship
->where('recipient_id', $this->id) // Not sure if this is correct, might need to adjust according to how you have defined the tables
->orderBy('created_at', 'desc')
->first();
}
It will query the messages relationship with the chained constraints that are listed. And by returning first() it returns only one record as opposed to a collection.

Laravel 5 Using orderBy() with Models

So I can't for the life of me figure out why I can't use orderBy. I'm getting the error:
Call to undefined method Illuminate\Database\Eloquent\Collection::orderBy()
Here is my code:
Route::get('/teams', function(){
$page = 'Teams';
$teams = App\Team::all()->orderBy('teamFirstName')->get();
return view('teams')->with('page', $page)->with('allTeams', $teams);
});
I have tried removing the ->get(); I have tried using just Team::all. I'm using a Laravel cheat sheet and I seem to be following the Model syntax. I have also double checked that it is the right column name in my DB and have even tried using just id.
If I remove the ->orderBy() the query works fine and I can get all of the teams. So what am I doing wrong?
It's because all() returns a Collection which does not have an orderBy method (though it does have a sortBy method which you could use). The following is a bit simpler though and should perform better.
$teams = App\Team::orderBy('teamFirstName')->get();
Once you call all(), the query is ran and results are fetched and any ordering done after this would be done by PHP. It's usually best to let the database handle the ordering though so use orderBy() first before fetching the results with get().
This line:
$teams = App\Team::all()->orderBy('teamFirstName')->get();
Need to be:
$teams = App\Team::orderBy('teamFirstName')->get();
Note:
user3158900 has a good explanation.

Categories