query string with laravel - php

i have a problem with a query string in Laravel 5.6
I have this two entities, ER Schema:
and related model:
Note model
Location model
My problem is that I have to select all notes in a certain location passing as query string parameters latitude and longitude.
A query string could be:
homestead.test/api/notes?lat=45.5432&long=43.6543&max_distance=1.1
I try to build a query Here the NoteController code, but there is a problem:
Actually the output show me every note.
This is a postman output and in addition to the notes in the right location, I also return those with location = null. Going to see in the database these notes have only one parameter that coincides with those passed in query string. Theoretically it should not return them and I can not take them off in any way. could someone help me?
I hope I was clear enough, thanks in advance

Node::with(['location' => function($query) use ($latitude, $longitude){
$query->where('latitude', $latitude);
$query->where('longitude', $longitude);
}])->get()

If it can help someone, I solved the problem in this way.
public function index(Request $request) {
if($request->has('lat') &&
$request->has('long')) {
$lat1 = $request->query('lat');
$long1 = $request->query('long');
$max_distance = $request->query('max_distance');
$notes = Note::All();
foreach ($notes as $key => $value) {
if($value->location != null) {
$lat2 = $value->location->latitude;
$long2 = $value->location->longitude;
$distance = sqrt(pow($lat2-$lat1, 2) + pow($long2-$long1, 2));
if($distance > $max_distance) {
$notes->forget($key);
}
} else {
$notes->forget($key);
}
}
return $notes;
}
return Note::All();

Related

Laravel. Exporting results from database problems

As short as possible. My code runs through multiple databases counts objects and matches name - number of objects
It runs like a script(command in laravel) that exports the results in .csv file.
$formatted_data = array();
$providers = provider::where('del', 'no')->get();
foreach($providers as $provider){
$formatted_data[$provider['id']]['name'] = $provider['name'];
}
$objectMappingsModels = array((new objectMapping1), (new objectMapping2),
(new objectMapping3), (new objectMapping4), (new objectMapping5),
(new objectMapping6), (new objectMapping7), (new objectMapping8));
foreach($objectMappingsModels as $objectMappingsModel){
$totals = $objectMappingsModel::select('providerFK', DB::raw('count(*) as total'),
DB::raw('monthName(ut) as month_name')
)
->where('userFK', '!=', 1)
->where('del', 'no')
->whereMonth('ut', $this->option('month'))
->whereYear('ut', $this->option('year'))
->groupBy('providerFK', 'month_name')
->get()
->toArray();
foreach($totals as $total){
$formatted_data[$total['providerFK']]['count'] = $total['total'];
}
}
$responce = Excel::store(new UsersExport($formatted_data), 'testNameDate.csv',null, \Maatwebsite\Excel\Excel::CSV);
return true;
That's what my code looks like.
class UsersExport implements FromArray
{
protected $invoices;
public function __construct(array $invoices)
{
$this->invoices = $invoices;
}
public function array(): array
{
return $this->invoices;
}
}
And that's what my export class looks like.
Unfortunately, it's not working flawlessly. It gives me wrong results from time to time. Some records a correct and some are not. Also, the last row is always with just a random number(without a name attached to it). Any idea why such problems occur and can you suggest me some code optimizations?
Thanks!
I added this if-else in the last loop
if(isset($formatted_data[$total['providerFK']]['count'])){
$formatted_data[$total['providerFK']]['count'] += $total['total'];
}else{
$formatted_data[$total['providerFK']]['count'] = $total['total'];
}
And it seems to have fixed some issues

Passing a variable to a query creates the error "Trying to get property 'name' of non-object" with Laravel

I am using Laravel 6. I am trying to create a validation system with a form to create a meeting.
When a user creates a meeting with participants that are already occupied in another meeting, a message should appear in the view with the name of the participants already occupied.
For some reason the function that should find the name of the participants doesn't work. I pass an id during a foreach loop but when I run the form appears the following message: "Trying to get property 'name' of non-object".
The strange thing is that the id passed to the function are OK, but if I write a number (for example "8") in place of $id in the query appears correctly the name "Chris" in the view.
The format of the column "id_participants" in the table meetings is the following "23;7;6".
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use DB;
use App\User;
class CheckParticipant implements Rule
{
protected $participants_occupied = array();
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$participants = request('participants');
foreach($participants as $participant) {
$meetings = DB::table('meetings')
->where('is_active', '1')
->where('date', request('date_meeting'))
->where(function ($query) {
$query->where(function($sub_q) {
$sub_q->where('start_hour', '>=', request('start'))
->where('start_hour', '<', request('end'));
})
->orWhere(function($sub_q) {
$sub_q->where('start_hour', '<', request('start'))
->where('end_hour', '>=', request('end'));
})
->orWhere(function($sub_q) {
$sub_q->where('end_hour', '>', request('start'))
->where('end_hour', '<=', request('end'));
});
})
->where(function ($query) use($participant) {
$query->where('id_participants', $participant)
->orWhere('id_participants', 'like', '%;'.$participant)
->orWhere('id_participants', 'like', $participant.';%')
->orWhere('id_participants', 'like', '%;'.$participant.';%');
})
->get();
if(count($meetings) > 0) {
array_push($this->participants_occupied, $participant);
}
}
if(count($this->participants_occupied) > 0) {
return false;
} else {
return true;
}
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
for($i = 0; $i < count($this->participants_occupied); $i++) {
$this->participants_occupied[$i] = $this->getNameSurnameById($this->participants_occupied[$i]);
}
return 'The participants are already occupied at that time: ' . implode(',', $this->participants_occupied);
}
public function getNameSurnameById($id)
{
$users = User::all()->where('id', 18)->first(); //if I write a number in place of $id everything works
return $users->name;
}
}
I would like that this program works dynamically. I suppose there is something wrong in the query with the variable $id. Is someone able to help me?
UPDATE:
I solved the problem modifying the message function as follows:
public function message()
{
$arr_names = array(); //I created this array
for($i = 0; $i < count($this->participants_occupied); $i++) {
array_push($arr_names, $this->getNameSurnameById($this->participants_occupied[$i]));
}
return 'The following participants are already occupied at that time: ' . implode(', ', $arr_names);
}
I suppose that the problem consisted that I gave a string value (the name of the participant) to an array that had integers values (The id of the participant). I solved creating a new empty array and I pushed the names to the new array.
You may find it much easier to grab your ids based on some type of Laravel object, rather than an array. I suspect that the array has an incorrect value (not an id) at the index of $i during the loop at some point. And, as pointed out in the comments by #Cristóbal Ramos Merino, you are setting the variable to a potential string (the user name) at the same time as you are trying to pass the possible id through to the getNameSurnameById() method.
I would grab all of the ids passed from the form, do a DB query on User to see who is already occupied, and then just pull the name from the resulting collection.
Something like:
$allFormUsers = User::whereIn('id', $formIds)->get();
Then loop on this to get the names of those occupied:
$occupiedNames = [];
foreach($AllFormUsers->where('occupied', 1) as $u){
$occupiedNames[] = $u->name;
}
I have no idea how you are tracking the occupied - and so the above code is little more than pseudo code, but hopefully will give you an idea of how to do this without the array / concurrency. This also is a little less work on the Database, since you have one query, instead of looping on individual queries each time. You can even pull all users first so you have them stored, and then do a where('occupied', 1) against the collection if you like, as in the above loop. (Assuming that's how you track occupied)

How to show Nearby Places with Laravel API

I'm creating REST API with Laravel 5.6 (I have to say I'm new because I might have used the wrong terms. I'm sorry about that,I'm improving myself. I need to hear my faults :) )
I have one function for find nearby places in my controller
public function index(\Illuminate\Http\Request $request) {
if($request->has('party_category')){
$parties = Parties::where('party_category', $request->party_category)->get();//your new query here
}
else if($request->has('lat') && $request->has('long')){
$parties = Parties::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10");
}else {
$parties = Parties::all();
}
return Fractal::includes('places')->collection($parties,new PartyTransformer);
}
and I'm using this url for send current location but when I giving them , laravel showing to me all parties not nearby.I want to show nearby places
http://127.0.0.1:8000/api/parties?lat=37.043237&long=27.392445
but when I sending my parameter to url it showing
{"data":[]}
I can't show any nearby places
also in my database I'm keeping lat and long like this :
public function up()
{
Schema::create('parties', function (Blueprint $table) {
$table->increments('id');
$table->integer('places_id')->unsigned();
$table->string('slug');
$table->string('party_title');
$table->string('party_category');
$table->string('rating')->nullable();
$table->date('party_date');
$table->string("latitude")->nullable();
$table->string("longitude")->nullable();
$table->integer('fav_count')->nullable();
$table->longText('image_path');
$table->longText('party_desp');
$table->timestamps();
});
}
How can I show the nearby ones ?
I fixed , I hope it will help somebody
class PartiesController extends Controller
{
public function index(\Illuminate\Http\Request $request) {
if($request->has('lat') && $request->has('long')){
$lat = $request->lat;
$long = $request->long;
$parties=DB::select(DB::raw("SELECT *,111.045*DEGREES(ACOS(COS(RADIANS(':lat'))*COS(RADIANS(`latitude`))*COS(RADIANS(`longitude`) - RADIANS(':long'))+SIN(RADIANS(':lat'))*SIN(RADIANS(`latitude`)))) AS distance_in_km FROM parties ORDER BY distance_in_km asc LIMIT 0,5"), array(
'lat' => $lat,
'long' => $long
));
$hidacik = Parties::hydrate($parties);
return Fractal::includes('places')->collection($hidacik,new PartyTransformer);
}
else {
$parties = Parties::all();
}
return Fractal::includes('places')->collection($parties,new PartyTransformer);
}
}
In $parties = Parties::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10");
you are missing ->get(). you need to add get() in order to return a collection which you can then work with
//this returns a collection now since we added get()
$parties = Parties::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10")->get();

How to search for multiple values in a single field of mysql table using codeigniter active record?

I have to search for multiple values in a field using mysql in codeigniter. Here follows my code.
In Controller
public function vpsearch()
{
$data['info'] = $this->psearch_m->emp_search_form();
$this->load->view("employer/result",$data);
}
IN Model
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
$jrole = $this->input->post('ps_jobrole'));
if ( $jrole !== NULL)
{
return $this->db->get('js_edu_details');
$this->db->like('js_skills','$skill');
}
}
In view i.e, (../employer/result)
foreach($info->result() as $row)
{
echo $row->js_id."<br/><br/>" ;
}
However I am getting all the records in 'js_edu_details' table instead of fields having searched 'skills'.
Where I am going wrong? Any help wud b appreciated, thanx in advance.
Try:
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
//$skill = $this->input->post('ps_skills', true); other short way of getting the above result with `xss clean`
if ( $jrole !== NULL)
{
$this->db->like('js_skills',$skill); #remove the single quote around the `$skill`
$res = $this->db->get('js_edu_details');
echo $this->db->last_query(); #try to print the query generated
return $res;
}
}
Return statement should be after the like statement
You should arrange the code properly like this
public function emp_search_form()
{
$ps_skills = $this->input->post('ps_skills')
$skill = $this->security->xss_clean($ps_skills);
if ( $jrole !== NULL)
{
$this->db->like('js_skills','$skill');
return $this->db->get('js_edu_details');
}
}
Also you should note the condition will never meet. It will always give error undefined variable $jrole

Codeigniter Extracting Data From Database With Function

I have to extract two separate pieces of information from my mysql database. I'm having a hard time trying to figure out how to extract two different sets of information via function(s) I'm writing. I'm trying to figure out a solution but I'm not getting it. Below is my syntax so far. My goal here is to get both of the functions (getPrice and getOtherPrice) all within the same function working. If I // one, the other one works. If both are active, just one is working. How would you guys go about correcting this issue, what do you think I'm doing wrong? Thanks Everyone.
function getJoinInformation($year,$make,$model)
{
$data = $this->getPrice($year,$make,$model);
$data = $this->getOtherPrice($year,$make,$model);
return $data;
}
function getPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
function getOtherPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
you are returning only last function result you should put the the result of both function by making an array of $data
function getJoinInformation($year,$make,$model)
{
$data['getPrice'] = $this->getPrice($year,$make,$model);
$data['getOtherPrice'] = $this->getOtherPrice($year,$make,$model);
return $data;
}
You're replacing the result in the variable $data.
$data = $this->getPrice($year,$make,$model);
$data = $this->getOtherPrice($year,$make,$odel);
$data will always just contain the result of the last function.

Categories