get() + sum() in one line laravel - php

My data
invoice|amount|
0001 | 10000|
0001 | 10000|
Now my code on Controller;
$invoices = Invoice::where('user_id', 1)
->where('status', 'Paid')
->orderBy('datePaid', 'desc')
->groupBy('no_invoice')
->get()
->sum('amount'); return view('invoice', ['invoices' => $invoices]);
I want show all data with get() and sum only field amount like this on my foreach.
invoice|total amount|
0001 | 20000|

You can use selectRaw in your select in query and then use sum(amount) like this
$invoices = Invoice::selectRaw('*, sum(amount) as total')
->where('user_id', 1)
->where('status', 'Paid')
->orderBy('datePaid', 'desc')
->groupBy('no_invoice')
->get();
Now you can print
foreach($invoices as $invoice){
echo $invoice->total
}

Related

How to write below query in Laravel

I have a table and there are two columns.
user_id
to_user_id
101
102
102
101
101
105
In the above table, 1 and 2 rows of users are like each other I want to remove 2 rows.
Here is my code.
$query = \App\Models\MyMatch::query();
$query->whereHas('users')->whereHas('tousers')
->select('my_matches.*')->distinct()
->where('user_id', '!=', 'to_user_id');
$records = $query->get();
In the above code, I got total 3 rows
I want only a total of 2 rows 1 and 3
So, how can I write a query for it
$records = \App\Models\MyMatch::whereHas('users')->whereHas('tousers')
->where(function($query) {
$query->where('user_id', '!=', 'to_user_id')
->orWhere(function($query) {
$query->where('user_id', '<', 'to_user_id');
});
})
->distinct()
->get();
or use a subquery :
$subquery = DB::table('my_matches')
->select('user_id', 'to_user_id')
->whereColumn('user_id', '>', 'to_user_id')
->toSql();
$records = \App\Models\MyMatch::whereHas('users')->whereHas('tousers')
->whereNotExists(function($query) use ($subquery) {
$query->select(DB::raw(1))
->from(DB::raw("($subquery) as sub"))
->whereRaw('my_matches.user_id = sub.to_user_id and my_matches.to_user_id = sub.user_id');
})
->get();
You can use
$query = \App\Models\MyMatch::query();
$query->whereHas('users')->whereHas('tousers')
->select('my_matches.*')
->where('user_id', '!=', 'to_user_id')
->groupBy('to_user_id')
->havingRaw('COUNT(*) = 1');
$records = $query->get();

How to count where using DB::raw() in laravel?

I have this query, but it does not work
$order = Order::select('*', DB::raw('count(*) as num_product'),
DB::raw('count(status) where status = 1 as accepted')) // ERROR HERE
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))->get();
I want to show number of order that accepted, for example : 2 of 5
$order = Order::select(DB::raw('count(*) as num_product, status'))
->where('status', 1)
->groupBy('status')
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
->get();

Pagination eloquent

I want to paginate ordering by linkscount em ASC...
The table pages:
----------------------
id | name
----------------------
1 | Globo
----------------------
2 | Google
----------------------
3 | MC Donalds
----------------------
4 | Habibs
The query to FIRST PAGE RESULTS (order/query is OK):
$pages = Mypages::where('pages.author_id', auth()->user()->id)
->orderBy('linkscount', 'desc')
->leftJoin('links', 'links.page_id', '=', 'pages.id')
->selectRaw('pages.*, count(links.id) as linkscount')
->groupBy('pages.id')
->take(2)
->get();
The query TO PAGINATE (order/query is not ok):
$pages = Mypages::where('pages.author_id', auth()->user()->id)
->orderBy('linkscount', 'asc')
->leftJoin('links', 'links.page_id', '=', 'pages.id')
->selectRaw('pages.*, count(links.id) as linkscount')
->groupBy('pages.id')
->where('pages.id', '>', $id)
->take(2)
->get();
This query, don't return nothing, it was to return "MC Donalds"...
$id = LAST ID DISPLAYED.
Like Jacob H said in the comment, this isn't a real SQL, because the group by function need to have all the columns of the query that you have in the select except the functions like counts, sums, etc.
For this example you need to put the pages.name and pages.id in the group by
$pages = Mypages::where('pages.author_id', auth()->user()->id)
->orderBy('linkscount', 'asc')
->leftJoin('links', 'links.page_id', '=', 'pages.id')
->selectRaw('pages.id, pages.name, count(links.id) as linkscount')
->groupBy('pages.id', 'pages.name')
->where('pages.id', '>', $id)
->take(2)
->get();
And if you are sending the correct $id, everything seems ok.

How to do this in laravel, Subquery where count

I am trying to implement this query in Laravel
"SELECT * FROM jobs
WHERE status = 1 AND
taskerCount = (SELECT count(*) FROM jobRequests WHERE status = 1 AND job_id =
jobs.id)"
This is what i have tried;
Auth::user()->jobs
->where('status', 1)
->where('taskerCount', function ($q) {
$q->where('status', 1)
->where('job_id', $q->id)->count();
});
But I get the error:
Object of class Closure could not be converted to int.
Use a raw expression instead of -count().
You can view this documentation here
Example of a raw query from laravel:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
Make sure you define the count as a name.

Eloquent join table with two conditions

I have two tables:
A: id | user_id | phonenumber | status | ...
B: id | user_id | phonenumber | name | ...
I would like to list all elements in table A but I have to left join the elements to table B.
I can do it with DB:
DB::table('A')
->leftJoin('B', function ($join) {
$join->on('A.phonenumber', '=', 'B.phonenumber')
->on('A.user_id', '=', 'B.user_id');
})
->select(...)
->where('A.user_id', '=', $userId)
->get();
Is it possible to solve it with eloquent somehow?
You can use eloquent, one way is to change it to
A::leftJoin('B', function ($join) {
$join->on('A.phonenumber', '=', 'B.phonenumber')
->on('A.user_id', '=', 'B.user_id');
})
->select(...)
->where('A.user_id', '=', $userId)
->get();
And with using pure eloquent
You would have to do adjustment to your A model. We would define two model functions.
public function phoneNumber()
{
return $this->hasMany(B::class, "phonenumber", "phonenumber");
}
public function userId()
{
return $this->hasMany(B::class, "user_id", "user_id");
}
Now we will change our query to
A::with("phonenumber")->has("phonenumber")
->with("userId")->has("userId")
->where("user_id","=",$userId)
->get();
This should work for you.
** Updated ***
if you want all the record in A then simply do
A::with("phonenumber","userId")
->where("user_id","=",$userId)
->get();
modelname::where(condition)->leftjoin(tablename,fieldname,othertable.fieldname)->get()
This is format how we write join in laravel
$postdata = post::select('categories.id', 'posts.id', 'categories.categoryname', 'posts.title', 'posts.body', 'posts.image', 'posts.created_at', 'users.name')
->where('post_type', 'publish')
->where('status', 'active')
->where('categories.id', $id)
->leftJoin('users', 'users.id', '=', 'posts.user_id')
->leftJoin('categories', 'categories.id', '=', 'posts.category')
->orderBy('created_at', 'desc')
->paginate(5);
This query display blog with username and with category using join it's my proect convenient query you can also create for you in this manner

Categories