Laravel - Argument 2 passed to Symfony\\Component\\HttpFoundation\\JsonResponse - php

I want to return the data in $users as an array as well as the data in $this->guard()->user() as not inside an array. I've tried as giveb below. But it generates the error - Argument 2 passed to Symfony\\Component\\HttpFoundation\\JsonResponse::__construct() must be of the type int, object given, called in C:\\wamp64\\www\\Laravel\\projects\\Content-Que-Laravel-API\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\JsonResponse.php on line 32. Am using Laravel-8 & pgsql -13.
How to solve this? Any suggestions..
$users = DB::table('users')
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
return response()->json(['data' => $users],$this->guard()->user());
Expected output:
{
"id": 2,
"name": "mrt",
"email": "ba#f.com",
"phone": 1112223333,
"email_verified_at": null,
"OTP": null,
"ph_OTP": 6033,
"email_OTP": 1090,
"user_access_token": null,
"created_at": "2021-07-20T06:49:29.000000Z",
"updated_at": "2021-07-20T06:49:29.000000Z"
}

You can pass like below result, because second arugment in jsonresponse is http status(200, 401).
return response()->json([
'data' => [
'users' => $users,
'guard' => $this->guard()->user()
]
]);

Related

Laravel get sums from models with two and more joins

I want to get the sum of prices from contract table and sum of transactions together connected to user id. And how can i use where in this.
Table Contracts:
[
{
"id": 1,
"user_id":97,
"price":"100"
},
{
"id": 2,
"user_id":97,
"price":"200"
},
{
"id": 3,
"user_id":97,
"price":"300"
}
]
Table Transactions:
[
{
"id": 1,
"user_id":97,
"sum":"100"
},
{
"id": 2,
"user_id":97,
"sum":"200"
},
{
"id": 3,
"user_id":97,
"sum":"300"
}
]
My query:
$query = User::where([
['contracts_sum', '<', 'transactions_sum'],
])
->join('contracts', 'contracts.user_id', '=','users.id')
->join('transactions', 'users.id', '=','transactions.user_id')
->groupBy(['users.id'])
->select(
'users.id', 'users.name',
DB::raw('SUM(contracts.price) AS contracts_sum'),
DB::raw('SUM(transactions.sum) AS transactions_sum'),
)
->get();
But this variant returns sum multiplied to count of transactions table rows like this:
[
{
"id":97,
"name":"JOHN",
"contracts_sum":"1800",
"transactions_sum":"1800"
}
]
But i would like to get the data in this kind of form:
[
{
"id":97,
"name":"JOHN",
"contracts_sum":"600",
"transactions_sum":"600"
}
]
My advice would be to make use of laravel's relation feature, as it would make it a lot easier.
class User
{
public function transactions()
{
return $this->hasMany(Transaction::class, 'user_id', 'id');
}
public function contracts()
{
return $this->hasMany(Contract::class, 'user_id', 'id');
}
}
Then, in your controller, you could do the following:
$user = User::where('id', 97)
->withSum('contracts', 'price')
->withSum('transactions', 'sum')
->get();
return [
'id' => $user->id,
'name' => $user->name,
'contracts_sum' => $user->transactions_sum_sum,
'transactions_sum' => $user->contracts_sum_price
];
Not only does this look a lot cleaner, the query will be more efficient as well. More information on the aggregate functions can be found in the laravel documentation.

How to merge two objects into one object using laravel

I am getting objects response like this:
"facilities": [
[
{
"facility_id": 1,
"speciality_id": null,
"is_facility_supervisor": 0,
"priv_key": "can_add_doctor,can_view_doctor"
}
],
{
"name": "Patient",
"role_id": 7
}
]
I want name and role_id into facilities and i want expected output like this
"facilities": [
[
{
"facility_id": 1,
"speciality_id": null,
"is_facility_supervisor": 0,
"priv_key": "can_add_doctor,can_view_doctor",
"name": "Patient",
"role_id": 7
}
],
]
How i can achieve this output name and role_id is in separate object but i want in one object like i shared.
My Code:
$specialities = DB::table('user_facility')
->select('user_facility.facility_id','user_facility.speciality_id','user_facility.is_facility_supervisor','user_facility.priv_key')
->where('user_id',$currentUser->id)->get();
$roles = DB::table('roles')
->join('user_facility', 'roles.id', 'user_facility.role_id')
->where('user_facility.user_id', Auth::user()->id)
->select('roles.name','user_facility.role_id')->first();
$superadmin = $is_super_admin->is_super_admin;
$specialities = (object) $speciality_id;
$response = ['is_super_admin' => $superadmin, 'facilities' => array_merge([$specialities,$roles])];
Your help will be highly appreciated?
How about:
$specialitiesAndRoles = DB::table('roles')
->join('user_facility', 'roles.id', 'user_facility.role_id')
->where('user_facility.user_id', Auth::user()->id)
->select('user_facility.facility_id','user_facility.speciality_id','user_facility.is_facility_supervisor','user_facility.priv_key','roles.name','user_facility.role_id')
->get();
When you are anyway joining both tables. Just select everything from the joined table. Please check/add if you have any more where clauses.

Two variable in one one variable

I have two queries.
$createdServer = Server::where('created_at', '>=', \Carbon\Carbon::now()->subMonth())
->selectRaw('COUNT(id) as createserver, DATE(created_at) as date,DAY(created_at) as day')
->groupBy('day', 'date')
->orderBy('date', 'ASC')
->orderBy('day', 'ASC')
->get();
$deletedServer = Server::where('deleted_at', '>=', \Carbon\Carbon::now()->subMonth())
->selectRaw('COUNT(id) as deleteserver, DATE(deleted_at) as date,DAY(deleted_at) as day')
->groupBy('day', 'date')
->orderBy('date', 'ASC')
->orderBy('day', 'ASC')
->onlyTrashed()
->get();
The output is:
"deletedServer": [
{
"deleteserver": 1,
"date": "2019-04-29",
"day": 29
}
],
"createdServer": [
{
"createserver": 2,
"date": "2019-04-29",
"day": 29
}
],
My requirement is:
"allServer": [
{
"deleteserver": 1,
"createserver": 2,
"date": "2019-04-29",
"day": 29
}
],
deleteServer and createServer count data in database.
You can retrieve with below code:
$allSevers = collect([
"deleteserver" => $deleteServer->count(), // retrieving the deleteServer count
"createserver" => $createServer->count(), // retrieving the createServer count
"date" => date('Y-m-d'), //date format in Year - Month - Date
"day" => date('j') // date format for mday
]);
merge function would solve the issue in your current case: link
$merged = $createdServer->merge($deletedServer);
$merged->all();
Edit:
$merged = $createdServer[0]->merge($deletedServer[0]);
$merged->all();

how to get inner array from Outer array

I want to pull a array from outer array.
My result
I want to remove circle symbol of array
{
"Success": "1",
"Message": "Subtopic Wise Questions...",
"Subtopic Questions": [
[
{
"id": "93",
"topic_id": "36",
"name": "Cell membrane and organelle",
"created_at": "2018-08-29 23:06:34",
"updated_at": "2018-08-29 23:06:34",
"q_count": "127"
}
],
]
}
Here is my output result of array. the
My Controller code
foreach($findid as $v)
{
$count[] = DB::table('questions')
->join('subtopics', 'subtopics.id', 'questions.subtopic_id')
->select('subtopics.*', DB::raw('count(questions.id) as q_count'))
->where('subtopic_id', $v)
->get();
}
return response([
'Success' => "1",
'Message' => "Subtopic Wise Questions...",
'Subtopic Questions' => $count
]);
use first() to obtain just an object as per your image you want to remove extra array quotes so
$count[] = DB::table('questions')
->join('subtopics', 'subtopics.id', 'questions.subtopic_id')
->select('subtopics.*', DB::raw('count(questions.id) as q_count'))
->where('subtopic_id', $v)
->first();
Hope it helps you!
use whereIn method instead of where method
note only store id in array then used whereIn method
$count = DB::table('questions')
->join('subtopics', 'subtopics.id', 'questions.subtopic_id')
->select('subtopics.*', DB::raw('count(questions.id) as q_count'))
->whereIn('subtopic_id', array_wrap($findid))
->get();
note if not working as u want restult then add toArray() method in
query like this
$count->toArray();
return response([
'Success' => "1",
'Message' => "Subtopic Wise Questions...",
'Subtopic Questions' => $count
]);
Your query is expensive. Since you are looping through array of ids, you are going to run queries count(findid) number of times. You can optimize and achieve the same as,
$count = DB::table('questions')
->join('subtopics', 'subtopics.id', 'questions.subtopic_id')
->select('subtopics.*', DB::raw('count(questions.id) as q_count'))
->whereIn('subtopic_id', $findid)
->get();
return response([
'Success' => "1",
'Message' => "Subtopic Wise Questions...",
'Subtopic Questions' => $count
]);

lumen with mongodb :getting error : Call to a member function prepare() on null

I am working with lumen and mongodb
I want to get (total unread) and total messages count based on folder
my mongodb query is like below,
$totalEmails = DB::connection('mongodb')
->select("sum(if(is_read==0,1,0)) as unread", "count(message_id) as total", "folder_id")
->collection('email_message')
->where('email_account_id', (int)$request->email_account_id)
->where('status', "Active")
->groupBy("folder_id")
->get();
it gives me error as below,
FatalErrorException in Connection.php line 333:
Call to a member function prepare() on null
please help me to resolve this issue.thank you.
I have resolve that error by change my query as below,
$totalEmails = DB::connection('mongodb')
->collection('email_message')
->select("sum(if(is_read==0,1,0)) as unread", "count(message_id) as total", "folder_id")
->where('email_account_id', (int)$request->email_account_id)
->where('status', "Active")
->groupBy("folder_id")
->get();
but it not gives me expected result,
it give me result as below,
[_id] => Array
(
[folder_id] => 5bee461e19f043020c001844
)
[folder_id] => 5bee461e19f043020c001844
[sum(if(is_read==0,1,0)) as unread] =>
[count(message_id) as total] =>
but my expectation is
[_id] => Array
(
[folder_id] => 5bee461e19f043020c001844
)
[folder_id] => 5bee461e19f043020c001844
[unread] => 2
[total] => 10
can you tell me where is wrong in query???
If I am using below query
$totalEmails = DB::connection('mongodb')
->selectRaw("sum(if(is_read==0,1,0)) as unread", "count(message_id) as total", "folder_id")
->collection('email_message')
->where('email_account_id', (int)$request->email_account_id)
->where('status', "Active")
->groupBy("folder_id")
->get();
it gives me error like,
ErrorException in Builder.php line 245:
Argument 2 passed to Illuminate\Database\Query\Builder::selectRaw() must be of the type array, string given,
If I am using below query,
$totalEmails = DB::connection('mongodb')
->collection('email_message')
->selectRaw("sum(if(is_read==0,1,0)) as unread,count(message_id) as total,folder_id")
->where('email_account_id', (int)$request->email_account_id)
->where('status', "Active")
->groupBy("folder_id")
->get();
it gives me result like,
[_id] => Array
(
[folder_id] => 5bee461e19f043020c001844
)
[folder_id] => 5bee461e19f043020c001844
[sum(if(is_read==0,1,0)) as unread,count(message_id) as total,folder_id] =>
please help me to get my expected result
This is quite a complex query to execute and very hard to produce with the laravel methods as far as I know, so I would recommend a raw query by using $aggregate like the following example:
$totalEmails = DB::connection("mongodb")
->collection("email_message")
->raw(function ($collection) {
return $collection->aggregate(
[
[
"\$match" => [
"email_account_id" => (int)$request->email_account_id,
"status" => "active"
]
],
[
"\$group" => [
"_id" => [
"folder_id" => "\$folder_id"
],
"unread" => [
"\$sum" => [
"\$switch" => [
"branches" => [
["case" => [
"\$eq" => [
"\$is_read", '0,1,0'
]
],
"then" => 1
]
],
"default" => 0
]
]
],
"total" => [
"\$sum" => 1
]
]
]
]
);
});
$collectedResult = array();
foreach ($result as $k => $v) {
$collectResult[] = $v->jsonSerialize();
}
return $collectedResult;
I have formatted it to be as readable as possible and I will try to explain every part of the query as well as possible so you know what it does.
By using the raw statement we can use the aggregate() function which simulates the mongo $aggregate.
First we want to filter on email_account_id which is done with the $match method, note that the $ is escaped because otherwise php will interpret it as a variable.
After that we need to perform the group by which is done with this part:
"_id" => [
"folder_id" => "\$folder_id"
]
This will create the _id column with in it an array with the key folder_id and will collect all unique values of the DB column 'folder_id' into the value.
Thus this part will produce an array of elements with unique folder_ids, then the unread and total messages will have to be counted for these folders.
The total is simple and is done with the $sum operator. The unread part is a bit more complex because this will need to filter on the is_read operator. Which is done with a switch statement and a default value of 0 (don't count when condition fails).
The raw query will return a MongoCursor so the last part is to collect these results
I hope this helps you and if anything is unclear please let me know.
I am not sure if this is what is causing your issue but you have an error in your code
It should be:
$totalEmails = DB::connection('mongodb')
->selectRaw("sum(if(is_read==0,1,0)) as unread, count(message_id) as total, folder_id")
->collection('email_message')
->where('email_account_id', (int)$request->email_account_id)
->where('status', "Active")
->groupBy("folder_id")
->get();
The selectRaw is needed to include raw code in the select. Here is the docs for more info
https://laravel.com/docs/5.5/queries#raw-expressions

Categories