API Resources laravel filter data - php

So i am trying to get some data pass to an array and send to json.
But when i do this i am getting alot of information:
This is the response:
{
"current_page": 1,
"data": [{
"id": 2,
"object_id": 3,
"booking_id": 1,
"sender_id": 1,
"receiver_id": 2,
"message": "It is accepted",
"type_id": 5,
"read": 1,
"archive": 0,
"star": 0,
"created_at": "2019-02-26 11:45:28",
"updated_at": "2019-02-26 12:15:11",
"created_time": "26\/02\/2019",
"host_user": 0,
"guest_user": 1,
"sender": {
"id": 1,
"first_name": "Joe",
"last_name": "Cos",
"email": "email-91#hotmail.com",
"profile_image": null,
"balance": 0,
"status": "Active",
"created_at": "2019-02-21 15:19:26",
"updated_at": "2019-02-21 15:19:26",
"profile_src": "http:\/\/xxx.com\/public\/images\/user_pic-225x225.png"
},
"bookings": {
"id": 1,
"object_id": 3,
"code": "mYuL4p",
"host_id": 1,
"user_id": 2,
"start_date": "2019-02-26",
"end_date": "2019-02-27",
"status": "Accepted",
"guest": 0,
"total_night": 1,
"per_night": 20,
"base_price": 20,
"cleaning_charge": 0,
"guest_charge": 0,
"service_charge": 0,
"security_money": 0,
"host_fee": 0,
"total": 20,
"booking_type": "request",
"currency_code": "EUR",
"cancellation": "Flexible",
"transaction_id": "67427302T32774838",
"payment_method_id": 1,
"accepted_at": "2019-02-26 11:45:28",
"expired_at": null,
"declined_at": null,
"cancelled_at": null,
"cancelled_by": null,
"created_at": "2019-02-26 11:37:36",
"updated_at": "2019-02-26 11:45:28",
"host_payout": 23,
"label_color": "success",
"date_range": "Feb 26 - 27, 2019",
"expiration_time": "2019\/02\/27 11:37:36",
"currency": {
"id": 3,
"name": "Europe",
"code": "EUR",
"symbol": "€",
"rate": "0.88",
"status": "Active",
"default": "0",
"org_symbol": "€"
}
},
"object_address": {
"id": 3,
"object_id": 3,
"address_line_1": "XXXXXXXXX, 4050-352 Porto, Portugal",
"address_line_2": null,
"latitude": "49.999",
"longitude": "-8.88810419921",
"city": "P",
"state": "P",
"country": "P",
"postal_code": "4050-352"
}
}],
"from": 1,
"last_page": 1,
"next_page_url": null,
"per_page": 10,
"prev_page_url": null,
"to": 1,
"total": 1
}
I am using the API Resources
In MY Resource i have:
return parent::toArray($request);
With this i get all that information my problem is i need to filter some data
and when i try to filter for exemple the email.
return [
'email'=> $this->email,
];
it gives error and says
"Property [email] does not exist on this collection instance."
I am learning and i am a newbie i am sorry for this dumb questions.
Thanks to all!

First make a trait
trait ResourceHelpers
{
/**
* Remove null values from Eloquent api resource
* #param array $data
* #return array
*/
public function removeNullValues(array $data)
{
$filtered_data = [];
foreach ($data as $key => $value) {
$filtered_data[$key] = $this->when($value !== null, $value);
}
return $filtered_data;
}
}
Then use it in your resource
class UserResource extends JsonResource
{
use ResourceHelpers;
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return $this->removeNullValues([
"id" => $this->id,
"first_name" => $this->first_name,
"last_name" => $this->last_name,
"phone" => $this->phone,
"email" => $this->email,
"balance" => $this->balance,
'address' => $this->address,
'city' => $this->city,
'state' => $this->state,
'zip_code' => $this->zip_code,
'country' => CountryResource::make($this->whenLoaded('country')),
"joined_at" => $this->created_at,
"updated_at" => $this->updated_at,
]);
}
}

In your resource:
$return = parent::toArray($request);
unset($return['email']);
return $return;
Or, you can explicitly define just what you do want to return, instead of relying on toArray:
return [
'id' => $this->id,
'message' => $this->message,
// and so on...
];
This gives you more control over the final API response, especially if you make database/model changes but need the API to remain unchanged.

Related

How to get latest data with groupBy in Laravel 8

I want to make a chat app. So I can get a list of patient but the top last message doesn't have the patient.
How to solve my problem.
PHP :
$appointment = Appointment::with([
'upcoming.consultant' => function($query) use ($user) {
$query->where('consultant_id', $user->consultant_id);
},
'patient',
'conversation' => function($query) {
$query->latest();
}
])
->groupBy('patient_id')
->get('patient_id');
Result Json Data :
[
{
"appointment_id": 16,
"upcoming_id": 72,
"patient_id": 5,
"payment_id": 22,
"child_id": null,
"time_slot": "2023-02-08 00:47:00",
"is_child": 0,
"is_presented": 0,
"is_rejected": 0,
"meet_at": null,
"diseases": null,
"comments": null,
"created_at": "2023-02-08 22:07:01",
"updated_at": "2023-02-08 22:07:01",
"deleted_at": null,
"upcoming": {
"upcoming_id": 72,
"consultant_id": 1,
"package_id": 1,
"price": "10",
"title": "abcd",
"start": "2023-02-08 00:47:00",
"end": "2023-02-08 01:47:00",
"total_appointment": 2,
"spend_time": 10,
"who_inserted": "3",
"created_at": "2023-02-08 18:48:21",
"updated_at": "2023-02-08 18:48:21",
"deleted_at": null,
"consultant": null
},
"patient": {
"patient_id": 5,
"salutation": "MR",
"first_name": "Apis Technologies",
"last_name": "#NutriInfo",
"email": "apislk.nutriinfo#gmail.com",
"email_verified_at": "2023-02-08 14:28:33",
"dob": "2023-02-08 00:00:00",
"image": null,
"tp": "+1 (935) 591-6866",
"tp_verified_at": null,
"gender": "Male",
"country": "Afghanistan",
"language": "si",
"address": "Exercitation volupta",
"city": "Matale",
"state": null,
"zipcode": null,
"created_at": "2023-02-08 14:28:33",
"updated_at": "2023-02-10 00:56:02",
"deleted_at": null
},
"conversation": {
"id": 2,
"appointment_id": 16,
"sender": 5,
"receiver": 1,
"massege": "a",
"is_read": 0,
"is_document": 0,
"who_inserted": "patient",
"document_link": null,
"created_at": "2023-02-08 22:07:55",
"updated_at": "2023-02-08 22:07:55",
"deleted_at": null
}
}
]
With groupBy
(Actually I want this way with last message)
PHP :
$appointment = Appointment::with([
'upcoming.consultant' => function($query) use ($user) {
$query->where('consultant_id', $user->consultant_id);
},
'patient',
'conversation' => function($query) {
$query->latest();
}
])->get();
Result Json Data :
[
{
"patient_id": 4,
"upcoming": null,
"patient": {},
"conversation": null
},
{
"patient_id": 5,
"upcoming": null,
"patient": {},
"conversation": null
}
]
Thank You
to retrieve a list of appointments grouped by patient ID, with the last conversation message for each patient. However, the resulting JSON data only contains patient ID, upcoming appointment details, patient details, and conversation details, but not the patient name.
To include the patient name in the resulting JSON data, you can modify your code to include the first_name and last_name fields from the patient table in the select statement
$appointment = Appointment::with([
'upcoming.consultant' => function($query) use ($user){
$query->where('consultant_id', $user->consultant_id);
},
'patient' => function($query) {
$query->select('patient_id', 'salutation', 'first_name', 'last_name');
},
'conversation' => function($query) {
$query->latest();
}
])
->groupBy('patient_id')
->get(['patient_id']);
This will select only the patient_id, salutation, first_name, and last_name fields from the patient table, and include them in the resulting JSON data. You can adjust the select statement to include more fields from the patient table if needed.
Note that the resulting JSON data will only include the fields that are selected in the get method. If you need to include more fields in the JSON data, you should add them to the get method. This will include the upcoming, patient, and conversation fields in the resulting JSON data.
$appointment = Appointment::with([
'upcoming.consultant' => function($query) use ($user){
$query->where('consultant_id', $user->consultant_id);
},
'patient' => function($query) {
$query->select('patient_id', 'salutation', 'first_name', 'last_name');
},
'conversation' => function($query) {
$query->latest();
}
])
->groupBy('patient_id')
->get(['patient_id', 'upcoming', 'patient', 'conversation']);
Thank you all
I solved it my way..
PHP
$user = $request->user();
$appointment = Appointment::with(
[
'upcoming.consultant' => function($query) use ($user){
$query->where('consultant_id', $user->consultant_id);
},
'patient','conversation'
])
->has('conversation')
->get();
$patientList = Appointment::with(
[
'upcoming.consultant' => function($query) use ($user){
$query->where('consultant_id', $user->consultant_id);
},
'patient','conversation' => function($query){
$query->latest();
}
])
->groupBy('patient_id')
->get('patient_id');
$list = array();
foreach ($patientList as $key1 => $patient) {
foreach ($appointment as $key2 => $row) {
if($patient->patient_id == $row->patient_id){
$keyList = $this->searchForId($row->patient_id,$list);
if(is_null($keyList)){
array_push($list,[
'patient'=>$row->patient,
'conversation' => $row->conversation
]);
}else{
$currentDate = Carbon::parse($list[$keyList]['conversation']['created_at']);
$newDate = Carbon::parse($row->conversation->created_at);
// dd($newDate->gt($currentDate));
if ($newDate->gt($currentDate)) {
$list[$keyList] = [
'patient'=>$row->patient,
'conversation' => $row->conversation
];
}
}
}
}
}
foreach ($list as $key => $part) {
$sort[$key] = strtotime($part['conversation']['created_at']);
}
array_multisort($sort, SORT_DESC, $list);
return view('consultant.chat', [
'patients' => $list
]);
JSON
[
{
"patient": {
"patient_id": 5,
"salutation": "MR",
"first_name": "Apis Technologies",
"last_name": "#NutriInfo",
"email": "apislk.nutriinfo#gmail.com",
"email_verified_at": "2023-02-08 14:28:33",
"dob": "2023-02-08 00:00:00",
"image": null,
"tp": "+1 (935) 591-6866",
"tp_verified_at": null,
"gender": "Male",
"country": "Afghanistan",
"language": "si",
"address": "Exercitation volupta",
"city": "Matale",
"state": null,
"zipcode": null,
"created_at": "2023-02-08 14:28:33",
"updated_at": "2023-02-10 00:56:02",
"deleted_at": null
},
"conversation": {
"id": 153,
"appointment_id": 16,
"sender": 5,
"receiver": 1,
"massege": "a",
"is_read": 0,
"is_document": 0,
"who_inserted": "patient",
"document_link": null,
"created_at": "2023-02-18 16:07:55",
"updated_at": "2023-02-18 16:07:55",
"deleted_at": null
}
},
{
"patient": {
"patient_id": 4,
"salutation": "MR",
"first_name": "Alexa",
"last_name": "PAKAYA",
"email": "sajith#apis.lk",
"email_verified_at": null,
"dob": "2013-07-24 00:00:00",
"image": null,
"tp": "+94772193832",
"tp_verified_at": null,
"gender": "Male",
"country": "Nigeria",
"language": "si",
"address": "Sunt corporis offic",
"city": null,
"state": null,
"zipcode": null,
"created_at": "2023-01-04 01:13:07",
"updated_at": "2023-02-16 09:24:37",
"deleted_at": null
},
"conversation": {
"id": 152,
"appointment_id": 24,
"sender": 3,
"receiver": 4,
"massege": "asd",
"is_read": 0,
"is_document": 0,
"who_inserted": "consultant",
"document_link": null,
"created_at": "2023-02-18 15:18:20",
"updated_at": "2023-02-18 15:18:20",
"deleted_at": null
}
}
]

Why my web services response return me data with first letter in lowercase?

I have a problem with my web service response and i'm not able to fix this problem.
So i want to get a result with letter data in Uppercase, cause after that I don't able to see my informations.
Here this my code on web service :
/**
* #Route("/contact/getContactFilter/{tdlinx}/{soc}", name="contact_getContactFilter")
*/
public function getContactFilter($tdlinx, $soc){
$em = $this->getDoctrine()->getManager("APP_REFERENTIEL");
$contactFilter = $em -> getRepository(CONTACT::class)->findBy(["TDLINX" => $tdlinx,"SOCIETE" => $soc,"ACTIF" => 1]);
$encoders = [new JsonEncoder()]; // If no need for XmlEncoder
$normalizer = new ObjectNormalizer();
$normalizers = [new \App\Utils\DateTimeNormalizer(), $normalizer];
$serializer = new Serializer($normalizers, $encoders);
$jsonObject = $serializer->serialize($arrayUpper, 'json', [
'circular_reference_handler' => function ($object) {
return $object->getId();
}]);
if(!$contactFilter) return new Response(null,204);
else return new Response($jsonObject,200, ['Content-Type' => 'application/json']);
}
And this is my response on Postman and the problem is visible here at third part :
{
"id": 63,
"TDLINX": 257242,
"TYPE": "physique",
"SOCIETE": "B",
"NOM": "Post",
"PRENOM": "Strike",
"COMMENTAIRE": "Test",
"ACTIF": true,
"INFOS": [
{
"id": 52,
"VALUE": "006516451",
"CONTACTID": 63,
"TYPEID": {
"id": 15,
"lIBELLE": "Phone fixe",
"pATTERN": "phone",
"sOCIETE": "B",
"iCON": "local_phone",
"lIST": [],
"iNFOS": [
{
"id": 51,
"VALUE": "034455258",
"CONTACTID": {
"id": 169,
"tDLINX": 257242,
"tYPE": "physique",
"sOCIETE": "B",
"nOM": "Norris",
"pRENOM": "Chuck",
"cOMMENTAIRE": "Test",
"aCTIF": false,
"iNFOS": [
{
"id": 50,
"VALUE": "Directeur adjoint",
"CONTACTID": 169,
"TYPEID": {
"id": 17,
"lIBELLE": "Poste",
"pATTERN": "liste",
"sOCIETE": "B",
"iCON": "business_center",
"lIST": [
{
"id": 12,
"VALUE": "Directeur",
"TYPEID": 17
},
{
"id": 13,
"VALUE": "Directeur adjoint",
"TYPEID": 17
},
{
"id": 14,
"VALUE": "Chef de rayon",
"TYPEID": 17
}
],
"iNFOS": [
50,
{
"id": 53,
"VALUE": "Directeur adjoint",
"CONTACTID": 63,
"TYPEID": 17
}
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
}
},
51
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"TYPEID": 15
},
52
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
}
}
}```
How to fix this problem ?
Please check your database probably you defined id as "id"(first letter in small letter)

How to manually map collection using laravel/php and get total amount

I currently have the below json response that the API is returning. I am able to return it using Laravel Eloquent. There are several users and each user has a several receipts. A receipt has types and status. I want to try to get the total sum amount for each receipt that is related to its type and status. I was able to return the below json response using
$this->user->with('receipts')->has('receipts')->get(['id', 'name']);
I have tried using multiple laravel collections methods https://laravel.com/docs/5.8/collections#available-methods But I am still unable to get the desired response.
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"id": 1,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 2,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 3,
"user_id": 1,
"type_id": 2,
"status": 1,
"amount": 50
},
{
"id": 4,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 5,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 6,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 20
},
{
"id": 7,
"user_id": 1,
"type_id": 1,
"status": 1,
"amount": 10
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"id": 9,
"user_id": 2,
"type_id": 1,
"status": 0,
"amount": 20
}
]
}
]
I expect to get this:
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"performance and deleted": 220,
"performance and not deleted": 10,
"project and deleted": 60,
"project and deleted": 50
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"performance and deleted": 20,
"performance and not deleted": 0,
"project and deleted": 0,
"project and not deleted": 0
}
]
}
]
My main concern is to use laravel collection methods and easy to read code to get my expected result
In this way, I believe you get your expected result with nice readable code.
I'll assume that you have $users variable which contains a list of users in collection (And probably the receipts are already loaded).
// You need to name the keys as you desire. (I can't figure out the labels by the type_id and status numbers).
$statusPair = collect([
'performance and deleted' => [
'type_id' => 1,
'status' => 0,
],
'something' => [
'type_id' => 1,
'status' => 1,
],
'something 2' => [
'type_id' => 2,
'status' => 0,
],
'something 3' => [
'type_id' => 2,
'status' => 1,
],
]);
$data = $users->map(function ($user) use ($statusPair) {
$receipts = $user->receipts;
$sums = $statusPair->mapWithKeys(function ($pair, $statusLabel) use ($receipts) {
$filtered = $receipts;
foreach ($pair as $key => $value) {
$filtered = $filtered->where($key, $value);
}
$sum = $filtered->sum('amount');
return [
$statusLabel => $sum,
];
});
return [
'id' => $user->id,
'name' => $user->name,
'receipts' => $sums->toArray(),
];
});
i think this will help
$user->receipts->sum('amount');

How to join Table into Table in Laravel Eloquent

I Have one Table That is tbl_service
table_service has relation with 4 other table as below
tbl_service_review
tbl_service_images
tbl_service_packages
tbl_service_step
tbl_user
I Have Joined This Four Table With Tbl_service Model Relationship. Now, I want To Subjoin table_user into tbl_service_review.......basically i want reviewer profile_pic And His Name from database......i have already joined tbl_user for who added service......
please help me with this......
Thank You In Advance.
function get_service_detail_by_id(Request $request) {
$rule = [
'service_id' => 'required',
];
$validate = Validator::make(request()->all(), $rule);
if ($validate->fails()) {
return response()->json(['data' => ['errors' => $validate->errors()->all()], 'message' => 'validation fail', 'status' => '0'], 406);
}
$userId = Auth::id();
$service_id = $request->input('service_id');
$package = Tbl_service::select(array('tbl_service.*',
DB::raw("IFNULL((select IFNULL(avg(rate),0) from tbl_rating where service_id = tbl_service.service_id group by service_id),0) as avg_rating"),
DB::raw("IFNULL((select COALESCE(count(rate),0) from tbl_rating where service_id = tbl_service.service_id group by service_id),0) as total_rating"),
DB::raw("IFNULL((select COALESCE(count(like_to),0) from tbl_service_favorite where like_to = tbl_service.service_id group by service_id),0) as total_like"),
DB::raw("IFNULL((select CASE WHEN id THEN 1 END from tbl_service_favorite where like_to = tbl_service.service_id and like_by = $userId group by tbl_service.service_id),0) as is_like_by_me"),
))
->with('Images', 'Packages', 'User_data', 'Steps')
->where('service_id', $service_id)
->get();
return response()->json(['data' => $package, 'message' => 'Get List Service Detail Successfully', 'status' => 1], 200);
}
Table_service Model
public $timestamps = false;
protected $table = 'tbl_service';
public function Images() {
return $this->hasMany('App\Models\Tbl_service_image', 'service_id', 'service_id');
}
public function Packages() {
return $this->hasMany('App\Models\Tbl_service_package', 'service_id', 'service_id');
}
public function User_data() {
return $this->hasMany('App\User', 'id', 'seller_id');
}
public function Steps() {
return $this->hasMany('App\Models\Tbl_service_step', 'service_id', 'service_id');
}
public function Review() {
return $this->hasMany('App\Models\Tbl_rating', 'service_id', 'service_id');
}
}
My Current Response is
"data": [
{
"service_id": 2,
"category_id": 2,
"seller_id": 1,
"service_title": "text",
"service_package": 3,
"created_at": "2019-08-06 09:20:45",
"avg_rating": "5.0000",
"total_rating": 2,
"total_like": 0,
"is_like_by_me": 0,
"Review": [
{
"rating_by": 2,
"rate": 5,
"rating_text": "Good",
"created_at": "2019-08-06 10:09:33",
},
{
"rating_by": 2,
"rate": 5,
"rating_text": "Good",
"created_at": "2019-08-06 10:09:33",
}
],
"user_data": [
{
"id": 1,
"role": 0,
"thirdparty_id": null,
"login_by": 0,
"name": "Test User",
"email": "test_user#gmail.com",
"country": "India",
"languages": "English",
"profile_pic": "https://images.unsplash.com/photo-1497316730643-415fac54a2af?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
"is_online": 0,
"last_seen": null,
"description": "User Details",
"password": "$2y$10$qf1ohDCSb0x7HrFDvF6cWe.B1V41r4gjuAhMm0DQFyhM1fy7ieKR2",
"temp_pass": null,
"is_active": 1,
"is_blocked": 0,
"user_lat": "21.12345",
"user_long": "72.12345",
"created_at": "2019-08-02 08:49:48"
}
],
}
],
"message": "Get List Service Detail Successfully",
"status": 1
My Expected Response Is
"data": [
{
"service_id": 2,
"category_id": 2,
"seller_id": 1,
"service_title": "Text",
"service_package": 3,
"created_at": "2019-08-06 09:20:45",
"avg_rating": "5.0000",
"total_rating": 2,
"total_like": 0,
"is_like_by_me": 0,
"Review": [
{
"rating_by": 2,
"rate": 5,
"rating_text": "Good",
"created_at": "2019-08-06 10:09:33",
"name": "trst",
"profile_pic": "https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg"
},
{
"rating_by": 2,
"rate": 5,
"rating_text": "Good",
"created_at": "2019-08-06 10:09:33",
"name": "trst",
"profile_pic": "https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg"
}
],
"user_data": [
{
"id": 1,
"role": 0,
"thirdparty_id": null,
"login_by": 0,
"name": "Test User",
"email": "test_user#gmail.com",
"country": "India",
"languages": "English",
"profile_pic": "https://images.unsplash.com/photo-1497316730643-415fac54a2af?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
"is_online": 0,
"last_seen": null,
"description": "User Details",
"password": "$2y$10$qf1ohDCSb0x7HrFDvF6cWe.B1V41r4gjuAhMm0DQFyhM1fy7ieKR2",
"temp_pass": null,
"is_active": 1,
"is_blocked": 0,
"user_lat": "21.12345",
"user_long": "72.12345",
"created_at": "2019-08-02 08:49:48"
}
],
}
],
"message": "Get List Service Detail Successfully",
"status": 1
What your are looking forward to is merging relationship
Here is the link
Just merge Review relationship merge useredata->pluck('profile_pic') and review object

building an array from looping an object

I am working on a laravel application at the moment, and I am trying to create an array from an object that is returned from the database by eloquent. The object looks like this,
[
{
"id": 3,
"body": "Fake User created the project Fake Project 2",
"uri": "8jss90xk",
"object_id": 422,
"user": [
{
"id": 25,
"email": "xxxxxxxxxx#gmail.com",
"first_name": "xxx1",
"last_name": "xxxx1",
"display_name": "xxxxxxxxxxx",
"initials": "XX",
"remember_me": null,
"active": "1",
"invite_code": null,
"forgotten_code": null,
"cost_visible": 0,
"login_type": "normal",
"api_token": null,
"created_at": "2015-02-13 11:47:24",
"updated_at": "2015-05-06 22:43:23",
"deleted_at": null,
"pivot": {
"notification_id": 3,
"user_id": 25,
"is_read": 0
}
}
],
"project": {
"id": 422,
"name": "Project Number 1",
"slug": "Tdc3de97",
"uri_hash": "project-number-1",
"description": null,
"total_cost": "1000.00",
"start_date": "2015-07-21",
"finish_date": "2015-10-22",
"status": 2,
"sales_person": null,
"client_id": 0,
"organisation_id": 97,
"owner_id": 97,
"user_id": 25,
"locked_by": null,
"created_at": "2015-07-21 13:39:21",
"updated_at": "2015-07-24 10:07:38",
"deleted_at": null,
"archived_at": "0000-00-00 00:00:00",
"invoiced_at": null,
"is_internal": 0
}
},
{
"id": 4,
"body": "Fake User created the project Fake Project 3",
"uri": "8jss90xk",
"object_id": 422,
"user": [
{
"id": 25,
"email": "XXXXXX#gmail.com",
"first_name": "XXXXX",
"last_name": "XXXXXXXX",
"display_name": "XXX",
"initials": "XX",
"remember_me": null,
"active": "1",
"invite_code": null,
"forgotten_code": null,
"cost_visible": 0,
"login_type": "normal",
"api_token": null,
"created_at": "2015-02-13 11:47:24",
"updated_at": "2015-05-06 22:43:23",
"deleted_at": null,
"pivot": {
"notification_id": 4,
"user_id": 25,
"is_read": 0
}
}
],
"project": {
"id": 422,
"name": "Project Number 1",
"slug": "Tdc3de97",
"uri_hash": "project-number-1",
"description": null,
"total_cost": "1000.00",
"start_date": "2015-07-21",
"finish_date": "2015-10-22",
"status": 2,
"sales_person": null,
"client_id": 0,
"organisation_id": 97,
"owner_id": 97,
"user_id": 25,
"locked_by": null,
"created_at": "2015-07-21 13:39:21",
"updated_at": "2015-07-24 10:07:38",
"deleted_at": null,
"archived_at": "0000-00-00 00:00:00",
"invoiced_at": null,
"is_internal": 0
}
},
{
"id": 5,
"body": "Fake User created the project Fake Project 4",
"uri": "8jss90xk",
"object_id": 422,
"user": [
{
"id": 25,
"email": "XXXXXXX#gmail.com",
"first_name": "XXXXXX",
"last_name": "XXXXXXX",
"display_name": "XXXXXXX",
"initials": "XX",
"remember_me": null,
"active": "1",
"invite_code": null,
"forgotten_code": null,
"cost_visible": 0,
"login_type": "normal",
"api_token": null,
"created_at": "2015-02-13 11:47:24",
"updated_at": "2015-05-06 22:43:23",
"deleted_at": null,
"pivot": {
"notification_id": 5,
"user_id": 25,
"is_read": 0
}
}
],
"project": {
"id": 422,
"name": "Project Number 1",
"slug": "Tdc3de97",
"uri_hash": "project-number-1",
"description": null,
"total_cost": "1000.00",
"start_date": "2015-07-21",
"finish_date": "2015-10-22",
"status": 2,
"sales_person": null,
"client_id": 0,
"organisation_id": 97,
"owner_id": 97,
"user_id": 25,
"locked_by": null,
"created_at": "2015-07-21 13:39:21",
"updated_at": "2015-07-24 10:07:38",
"deleted_at": null,
"archived_at": "0000-00-00 00:00:00",
"invoiced_at": null,
"is_internal": 0
}
}
}]
Basically the query returns all the users with unread notifications, and I want to build that into array along with any notifications and send an email but the array needs to be quite specific with the details it contains.
I imagine sending something like this to mail function that will send the reminders,
'user#emailaddress.com' => array(
'first_name' => 'User',
'last_name' => 'Lastname',
'projects' => array(
'Project Title 1' => array(
'notifications' => array(
[0] => 'Notification 1',
[1] => 'Notification 2',
[2] => 'Notification 3'
)
)
)
)
I cannot for the live of me work out how to build this array from my object, I currently have this in my code,
foreach($unread as $object) {
$emails_to_send = array(
'user' => $object->user[0],
'uri' => $object->uri,
'body' => $object->body,
'project' => $object->project
);
}
This however builds the wrong structure and overwrites the last loop.
The reason why you get the data overwritten in the last loop is because you assing newly created array to $emails_to_send variable instead of appending to the array. Try the following:
$emails_to_send = array();
foreach($unread as $object) {
$emails_to_send[] = array(
'user' => $object->user[0],
'uri' => $object->uri,
'body' => $object->body,
'project' => $object->project
);
}
var_dump($emails_to_send);
This should give you a list containing one entry for each email that needs to be sent.
You are wright you have to iterate through your resulting array but like this:
// First create the final array
$emails_to_send = array();
foreach($unread as $object) {
// Add new array element with the email key
$emails_to_send[$object->user[0]->email] = array(
'first_name' => $object->user[0]->first_name,
'last_name' => $object->user[0]->last_name,
'project' => $object->project
);
}
var_export($emails_to_send);
As a result you will see something like:
array(
'user#emailaddress.com' => array(
'first_name' => 'User',
'last_name' => 'Lastname',
'project' => array(
"id" => 422,
"name" => "Project Number 1",
"slug" => "Tdc3de97",
"uri_hash" => "project-number-1",
...
)
),
...
)

Categories