I have a query that looks like this where I fetch data for various businesses in a particular location and I need to be able to tell that each business has (or does not have) a female employee.
$business = Business::where('location', $location)
->with(['staff'])
->get();
return MiniResource::collection($business);
My Mini Resource looks like this:
return [
'name' => $this->name,
'location' => $this->location,
'staff' => PersonResource::collection($this->whenLoaded('staff')),
];
This is what a sample response looks like:
{
"id": 1,
"name": "XYZ Business"
"location": "London",
"staff": [
{
"name": "Abigail",
"gender": "f",
"image": "https://s3.amazonaws.com/xxxx/people/xxxx.png",
"role": "Project Manager",
},
{
"name": "Ben",
"gender": "m",
"image": "https://s3.amazonaws.com/xxxx/people/xxxx.png",
"role": "Chef",
},
]
}
I really don't need the staff array, I just want to check that a female exists in the relation and then return something similar to this:
{
"id": 1,
"name": "XYZ Business"
"country": "USA",
"has_female_employee": true;
}
Is there an eloquent way to achieve this ?
NB: In my original code I have more relations that I query but I had to limit this post to be within the scope of my problem.
If you are only looking for male or female staff members, you can achieve it like so:
$someQuery->whereHas('staff', function ($query) {
$query->where('gender', 'f');
})
If you want both genders, I wouldn't go through the hassle of achieving this in the query, but recommend reducing your results collection in your MiniResource:
return [
'name' => $this->name,
'location' => $this->location,
'has_female_employee' => $this->whenLoaded('staff')->reduce(
function ($hasFemale, $employee) {
$hasFemale = $hasFemale || ($employee->gender === 'f');
return $hasFemale;
}, false),
];
Even better would be to create it as a method on your MiniResource for readability.
Change your code like below and see
$business = Business::where('location', $location)
->with(['staff'])
->where('gender', 'f')
->get();
return [
'name' => $this->name,
'location' => $this->location,
'has_female_employee' => empty($this->whenLoaded('staff')) ? false : true,
];
Related
i have a problem for the response, i want to change the response API because i need for my mobile APP, the feature have filter object based on date. So i hope you all can help me to solve the problem
i wanna change the response for my API
before:
{
"tasks": [
{
"id": 7,
"user_id": 1,
"title": "gh",
"date": "2022-02-10 13:05:00",
"deskripsi": "gfh",
"created_at": "2022-02-09T06:05:56.000000Z",
"updated_at": "2022-02-09T06:05:56.000000Z"
},
{
"id": 5,
"user_id": 1,
"title": "ghf",
"date": "2022-02-17 16:05:00",
"deskripsi": "fghf",
"created_at": "2022-02-09T06:05:12.000000Z",
"updated_at": "2022-02-09T06:05:12.000000Z"
},
{
"id": 6,
"user_id": 1,
"title": "fgh",
"date": "2022-02-17 18:05:00",
"deskripsi": "gh",
"created_at": "2022-02-09T06:05:40.000000Z",
"updated_at": "2022-02-09T06:05:40.000000Z"
}
]
}
here is the code for the response API above
return response([
'tasks' => Task::where('user_id', auth()->user()->id)->where('date','>',NOW())->orderBy('date','asc')->get(),
],200);
and i want to change it my response API into this response
{
"tasks": [
{
"date": "2022-02-10",
"task": [
{
"id": 7,
"user_id": 1,
"title": "gh",
"date": "2022-02-10 13:05:00",
"deskripsi": "gfh",
"created_at": "2022-02-09T06:05:56.000000Z",
"updated_at": "2022-02-09T06:05:56.000000Z"
},
{
"id": 7,
"user_id": 1,
"title": "gh",
"date": "2022-02-10 15:05:00",
"deskripsi": "gfh",
"created_at": "2022-02-09T06:05:56.000000Z",
"updated_at": "2022-02-09T06:05:56.000000Z"
}
]
},
{
"date": "2022-02-12",
"task": [
{
"id": 7,
"user_id": 1,
"title": "gh",
"date": "2022-02-12 13:05:00",
"deskripsi": "gfh",
"created_at": "2022-02-09T06:05:56.000000Z",
"updated_at": "2022-02-09T06:05:56.000000Z"
}
]
},
]
}
Do groupBy on the resulting Collection from the query (see docs: https://laravel.com/docs/9.x/collections#method-groupby)
For example, you could do:
$tasksGroupedByDate = Task::where(.......)
->get()
->groupBy(fn (Task $task) => $task->date->format('Y-m-d'));
(Note: above uses PHP 7.4 arrow functions. Also, add a date cast on the date column in your Task model to be able to use ->format( directly on the date field)
The above code results to:
{
'2022-01-01' => [
{ Task object },
{ Task object },
{ Task object },
],
'2022-01-02' => [
{ Task object },
{ Task object },
{ Task object },
],
}
(used Task object for brevity, but that will be ['id' => 1, 'title' => 'Task name', .....])
To morph that to the structure you want, you can use map and then values to remove the keys and turn it back to an ordered array:
$tasksGroupedByDate->map(fn ($tasksInGroup, $date) => [
'date' => $date,
'task' => $tasksInGroup
])->values();
If you want to combine everything into one method chain:
return [
'tasks' => Task::where(......)
->get()
->groupBy(fn (Task $task) => $task->date->format('Y-m-d'))
->map(fn ($tasksInGroup, $date) => [
'date' => $date,
'task' => $tasksInGroup
])
->values(),
];
It sounds like you want to create a human friendly date field based on the date column, then group by it.
While solutions do exists to accomplish this at the database level, I believe you'd still need to loop around it again afterwards to get the hierarchy structure you're looking for. I don't think it's too complicated for PHP to loop through it.
My suggestion is as follows:
Before:
return response([
'tasks' => Task::where('user_id', auth()->user()->id)
->where('date','>',NOW())->orderBy('date','asc')->get(),
],200);
After:
$out = [];
$tasks = Task::where('user_id', auth()->user()->id)
->where('date','>',NOW())->orderBy('date','asc')->get();
foreach($tasks as $task) {
$date = strtok((string)$task->date, ' ');
if (empty($out[$date])) {
$out[$date] = (object)['date' => $date, 'task' => []];
}
$out[$date]->task[] = $task;
}
$out = array_values($out);
return response(['tasks' => $out], 200);
Note in the above I'm using the function strtok. This function might look new even to the most senior of php developers.... It's a lot like explode, except it can be used to grab only the first part before the token you're splitting on. While I could have used explode, since the latter part after the token isn't needed, strtok is better suited for the job here.
$task = Task::where('user_id', auth()->user()->id)->where('date','>',NOW())->orderBy('date','asc')->get();
foreach($task as $item){
$date[] = item->date;
$result = Task::where('user_id', auth()->user()->id)->where('date','=', $date)->get();
}
return response([
'tasks' =>
['date' => $date,
'task' => $task]
],200);
maybe something like this
I am trying to insert data but unfortunately i am getting error Array to string conversion please help me how can i resolve that thanks.
please check error https://flareapp.io/share/x5Mznjem
return request
{
"_token": "3qLsIoNwWiOuze8aurlSQGqU4FsgttXgY6sMFYnw",
"icon": "0AKj2DRZii6yhJsoWKLNUbmOWKrXzOqKoFJTF4LI.jpg",
"name": "fdgdfg",
"person_name": "dfg",
"contact_number": "43543543",
"city": [
"2",
"3",
"4",
"5"
],
"location": [
"1",
"3",
"4"
],
"address": "A-232 Gulshan-e-hadeed ph 2"
}
controller
public function store(Request $request)
{
// return $request->all();
$request->validate([
'name' => "required",
'icon' => 'nullable',
'person_name' => 'required',
'contact_number' => 'required',
]);
$agency = Agency::create($request->except('_token'));
foreach ($request->city as $key => $value) {
$agencyCityLocation = new AgencyCityLocation;
$agencyCityLocation->agency_id = $agency->id;
$agencyCityLocation->city_id = $value;
$agencyCityLocation->location_id = $request->location;
$agencyCityLocation->save();
}
return redirect()->route('agency');
}
Replace this
$agencyCityLocation->location_id = $request->location;
By
$agencyCityLocation->location_id = $request->location[$key]
The issue is this line:
$agencyCityLocation->location_id = $request->location;
As you wrote $request->location is an array...
"location": [
"1",
"3",
"4"
],
...and I assume, that in $agencyCityLocation->location_id only one string is expected and not an array.
One solution would be to iterate through the locations as well (as you do with the cities), but actually we don't know how you want to save your data into the database. Do you want one DB entry for each city - location combination or is the city combined with the location?
I have a collection:
{
"2020-09-06 12:00:00": [
{
"usage_point_id": "12345678912345",
"key": "0.7680189"
},
{
"usage_point_id": "12345678912346",
"key": "0.29539188"
},
]
}
I would like to transform it to:
[{
"timestamp": "2019-12-18T10:30:00Z",
"keys": [
{
"usage_point_id": "12345678912345",
"key": "12,5"
},
{
"usage_point_id": "12345678912346",
"key": "0.29539188"
},
]
}]
They question is how to change:
"2020-09-06 12:00:00": [
with
"timestamp": "2019-12-18T10:30:00Z",
I get this collection with the query:
$measures = Measure::where('operation_id', $operation->name)
->whereBetween('time', [$from, $to])
->select(['time AS timestamp', 'meter_id AS usage_point_id', 'repartition_rate AS key'])
->get()->groupBy('timestamp');
is there a special helper for collections for that purpose ?
The easiest solution to your problem would be to map through all entries and modify their contents:
$measures
->map(function ($item, $key) {
return [
"timestamp" => Carbon\Carbon::make($key)->toISOString(),
"keys" => $item,
];
})
->values();
In Juliatzin case it constantly overwrites the key so it only returns the last entry if you have multiple entries from your database result.
I got the solution, with mapWithKeys
$measures = $measures->mapWithKeys(function ($measure, $key) {
return [
'timestamp' => $key,
'keys' => $measure
];
});
I have a problem with the Laravel Query Builder. When I try to bind a variable, which would include some sort of sql code, into my binding parameter, it returns no results. If I run enableQueryLog() I can see that the query and the binding is correct. So the code provides a perfectly fine query but yet it does not perform accordingly.
I've already tried printing out all the variables that matter. I enabled a query log to see if everything is set correctly, which it is. When I put in the variable in my whereRaw() just as it is without binding, it works fine. Just not with the binding.
This is the code I run:
public function getCarbrands() {
$name = 'name != Ford';
try {
$brands = DB::table('ni_carbrands')
->whereRaw(':name',['name'=>$name])
->select('id','name')
->get();
echo json_encode( array('info' => 1 ,'status' => 'Successfully found car brands', 'details' => $brands));
} catch(Exception $e){
echo json_encode( array('info' => 0 ,'status' => 'Error finding car brands', 'e' => $e));
}
}
I know that this use of the binding feature is unnecessary, it is merely a test for some other functions I wanna build.
This is what my Query Log returns:
array:1 [▼
0 => array:3 [▼
"query" => "select `id`, `name` from `ni_carbrands` where :name"
"bindings" => array:1 [▼
0 => "name != Ford"
]
"time" => 190.25
]
]
The components of the query all seem correct, but yet it seems to have some trouble producing it.
The expected results would be something like this:
{
"info": 1,
"status": "Successfully found car brands",
"details": [
{
"id": 1,
"name": "Toyota"
},
{
"id": 2,
"name": "Fiat"
},
{
"id": 3,
"name": "Iveco"
},
{
"id": 4,
"name": "Citroën"
},
{
"id": 5,
"name": "Opel"
},
{
"id": 6,
"name": "Mercedes"
},
{
"id": 8,
"name": "Volkswagen"
},
{
"id": 9,
"name": "Renault"
},
{
"id": 10,
"name": "MAN"
},
{
"id": 11,
"name": "Nissan"
},
{
"id": 12,
"name": "Hyundai"
},
{
"id": 13,
"name": "Peugeot"
}
]
}
But the actual result is:
{"info":1,"status":"Successfully found car brands","details":[]}
I'd greatly appreciate some help.
It seems like you cant bind a string containing an operator.
Have a look into this one Can I bind a parameter to a PDO statement as a comparison operator?
And this one binding not null in pdo
Bad raw condition:
whereRaw(':name',['name'=>$name])
Just like this:
$brands = DB::table('ni_carbrands')
->select('id','name')
->whereRaw($name)
->get();
you can this use this kind of also
$brands = DB::table('ni_carbrands')
->select('id','name')
->where('name', '!=', 'Ford')
->get();
otherwise you can set where condition in dynamic field
like
->where($name, '!=', 'Ford')
$name = 'name != Ford';
$brands = DB::table('ni_carbrands')
->whereRaw(':name',['name'=>$name])
->select('id','name')
->get();
this is equivalent query
select from ni_carbrands where 'name != Ford'
of course it doesn't work, because you have so
select from ni_carbrands where name != Ford
problem in quotes
Hiii
I have 2 database tables with the columns table :1 "id, invoice_id, subject, total" table:2 "id, invoice_id, item_name, price".whenever i try to update record with the help of invoice_id if record doesn't exist in item table it will not insert new item in item table.
here i attached my JSON data
{
"date": "2019-06-08",
"client_id": "1",
"currency_id": 4,
"total_amount": null,
"subject": "RD Management",
"items": [
{
"item_name": "Saving",
"price": "500"
},
{
"item_name": "Fix",
"price": "500"
},
{
item_name": "Current",
"price": "200"
}
]
}
here one problem is also
my JSON can not send item_id also
so without item id how can i update my record...???
here 3rd item is not present in my table
here is my controller
foreach ($request->items as $key => $items)
{
$item_update = [
'item_name' => $items['item_name'],
'price' => $items['price']
];
DB::table('items')
->where('invoice_id', $id)
->update($item_update);
}
I Except output like this
"items": [
{
"id": 1,
"invoice_id": "1",
"item_name": "Saving",
"price": "500",
},
{
"id": 2,
"invoice_id": "1",
"item_name": "Fix",
"price": "500",
},
{
"id": 3,
"invoice_id": "1",
"item_name": "current",
"price": "200",
},
]
but my actual output is
"items":[
{
"id":"1"
"item_name": "Fix",
"price": "500",
},
{
"id":"2"
"invoice_id": "1",
"item_name": "Fix",
"price": "500",
}
]
this output override item_name at update time.
there are any way to solve this both problem.
If you can't identify which items already exist and which ones are new, your remaining option is to identify items by item_name+invoice_id. The downside is that you cannot update item_name this way.
If you have Eloquent models properly set up, you can use updateOrCreate().
<?php
foreach ($request->items as $key => $items)
{
$itemAfterUpdate = App\Item::updateOrCreate(
[
'invoice_id' => $id,
'item_name' => $items['item_name']
],
[ 'price' => $items['price'] ]
);
}
If not, you will basically have to do what Eloquent does behind the scenes, which is check if the item already exists based on item_name and invoice_id, and then insert or update accordingly.
<?php
foreach ($request->items as $key => $items)
{
$alreadyExists = DB::table('items')
->where('invoice_id', $id)
->where('item_name', $items['item_name'])
->exists();
}
if($alreadyExists){
DB::table('items')
->where('invoice_id', $id)
->where('item_name' => $items['item_name'])
->update(['price' => $items['price']);
}
else{
DB::table('items')->insert([
'invoice_id' => $id,
'item_name' => $items['item_name'],
'price' => $items['price']
]);
}
}