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
Related
I have a React-based web application that's being supported on the back-end by a REST API written in Laravel. I need to display the count of from a specific column in a collection in the database, after which it will be displayed on the dashboard. This should be retrieved from the back-end via a Mongo DB query and an API call to the back-end. Being new to Laravel/MongoDb, I run into a blocker when trying to get this implementation done on my controller - this is the part I need ideas on the implementation - basically how to make the request to the db and retrieving the result. The code below shows what I have so far:
My mongodb query which works on the mongo shell and returns 167 as the count:
db.users.distinct('policy_scheme').length
php code:
api.php:
Route::get('totalSchemes', [CollectionController::class, 'numberOfSchemes']);
Controller:
`
public function numberOfSchemes(Request $request)
{
$schemeCount = DB::collection('users')::distinct()->get(['policy_scheme'])->count();
if(!empty($schemeCount)){
return response()->json([
'message'=>'data',
'data'=> $schemeCount], 201);
}
else{
return response()->json([
'message'=>'No data',
'data'=>[] ], 201);
}
}
`
I am not sure but try this one.
$schemeCount = DB::collection('users')::unique('id')->get(['policy_scheme'])->count();
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());
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.
My scenario is:
PHP Script 1:
$user = User::find(1);
$user->email = 'email#emailness.com';
$user->save();
PHP Script 2:
$user = User::find(1);
while ($user->email != 'email#emailness.com') {
/** Do stuff **/
}
Now my question is, does the email variable get updated when it's updated from another script? For example, Script 2 runs, while it runs, Script 1 also runs. Will the while statement update and move since the condition isn't true anymore?
I think the simplest way to achieve something like this is to run a query every minute or so checking for updated columns. The alternative would be to make your daemon run some sort of server which gets pinged by a model event.
If you only need to monitor a single user's email, it's easy enough - User::find($id); then sleep(60). If you need to monitor more than one user it gets a bit trickier.
If your model uses timestamps (created_at and updated_at), it's possible to query only for models that have been updated recently. Let's say you want to re-query the database every 60 seconds - what we want to do is query all User models that have an updated_at greater than 60 seconds ago.
I'll use the Carbon class, which is an extension of DateTime included with Laravel, but you can also construct a normal DateTime object or a datetime string manually.
$dt = Carbon\Carbon::now()->subSeconds(60);
$users = User::where('updated_at', '>=', $dt)
->get();
foreach ($users as $user) {
// do something with users that have been updated
}
sleep(60);
You can also replace get() with lists('email') if you only want a flat array of emails of updated users.
There may also be more efficient ways than using sleep(60), maybe using Symfony's Process class, but I'll not get into that here.
I've just picked up laravel after deciding to move to a php framework. I'm retrieving a result set of articles from a database using an eloquent query:
$posts = Article::select(array('articles.id','articles.article_date','articles.image_link','articles.headline','articles.category', 'articles.published'));
this works fine and results come out as expected.
However I now want to change the format of the article date from the mysql date format to another for the entire collection.
I thought about iterating through the object and changing using the usual php methods but wondered if there was an easier way to manipulate the data either when initiating the query or en mass with the object itself.
I've looked at mutators? but wasnt sure if this was appropriate or how to implement
Any help, pointers appreciated
You're right, mutators are the way to go. (Laravel 3 syntax)
Getter and Setter documentation for Eloquent models
public function get_article_date()
{
return date('d-m-Y H:i:s', strtotime($this->get_attribute('article_date'));
}
Getting the attribute
$articles = Articles::get(array(
'article_date',
'image_link',
'headline',
'published'
));
foreach($articles as $article)
{
echo $article->article_date;
}
Every time you get the date from your model it will run through the mutator first returning your modified result.
Absolutely no need to run raw queries for something like this.
EDIT got set and get mixed up... more coffee needed (answer edited)
Im not sure if this is working, but give it a try
$posts = Article::select(array('articles.id',DB::raw('CAST(articles.article_date as date)'),'articles.image_link','articles.headline','articles.category', 'articles.published'));