get latest record of multiple groupby laravel - php

I want to group by an laravel eloquent with two classes come in with() I want to add column of these two with classes in group by
$query = CourseEnrolled::with('user', 'course')->latest()->groupBy('course_id','user_id')
Here course id come from course table and user id come from user table. it successfully group columns but does sort latest record. It display old record only
I have also tried but still same result
$query = CourseEnrolled::with('user', 'course')->orderBy('created_at')->groupBy('course_id','user_id')

u cant query them directly with the eloquent model of CourseEnrolled. if you want to add additional queries with other models, you have to use with() in this way :
CourseEnrolled::with('user' , function($user){
// now u can use any query with user fields
$user->where('user-name' , 'value');
})

This query solve my problem
$query = CourseEnrolled::with('user', 'course')->latest()->whereIn('id', function($q){
$q->select(DB::raw('MAX(id) FROM course_enrolleds GROUP BY user_id,course_id'));
});

Related

How to get 2 database tables and display only the 5 latest records? Laravel

I need to get the latest activity from the database and order them by created_at.
There is a database table of orders, which has a shop_id, and there is a database table of collected_birthdays, which also has a shop_id incommon.
How to get the latest orders and collected_birthdays which has the same shop_id and take 5 latest records?
The mission is to display to the user the latest records of the two database tables, in the future, there will be more tables which will I need to display and get the latest 5 records.
Currently I found it make it work this way:
$shop = Shop::FindOrFail(1);
$orders = $shop->orders()->orderBy('created_at', 'DESC')->limit(5)->get();
$collectedBirthdays = $shop->collectedBirthdays()->orderBy('created_at', 'DESC')->limit(5)->get();
$latestActivity = $orders->merge($collectedBirthdays)->sortByDesc('created_at')->take(5);
This is not the best solution, but made it work.
You can use DB::raw(). It will take the raw query and give you the reault.
$data = DB::raw(
'Select o.shop_id, o.created_at, cb.shop_id, cb.created_at
From orders as o
Inner Join collected_birthdays as cb on cb.shop_id = o.shop_id
Order By o.created_at DESC -- or use cb.created_at
Limit 5;'
)->get();
You can use take function in eloquent and do something like this:
Shop::join('orders', 'orders.shop_id', '=', 'shops.id')->orderBy('orders.created_at', 'DESC')->take(5)->get()
Or if you want to stop using join(table, onCondition..) I recommend you use Eloquent Power Joins package which will automatically generate joins for you based on relationship declared inside your model and use it like this:
Shop::joinRelationship('orders')->orderBy('orders.created_at', 'DESC')->take(5)->get();
Link to package: https://github.com/kirschbaum-development/eloquent-power-joins
This would also be possible by using paginate()

Laravel paginate belongsToMany relationship?

I would like to paginate my results I get from my relationship. I have a products table/controller, a users table/controller and a markedProducts table. However, I don't have a markedProducts table because I don't actually need it. I use this solution to get all marked products of one user in my user model:
public function markedProducts(){
return $this->belongsToMany('App\Product', 'products_marks');
}
My question now is how can I paginate my results and my second question is how can I get the created_at value of each row in my markedProducts table?
Because my solution is only returning the marked products. However, I would like to show the user when he has marked the product.
So far I had this idea:
$markedProducts = DB::table('products_marks')->where('user_id', Auth::id())->orderBy('created_at', 'desc')->paginate(2);
$products = Product::whereIn('id', $markedProducts->lists('product_id'));
However, ->lists() is not a method anymore and I actually don't want to bypass the Laravel methods and I don't want to loop through my pagination to get an array with all product_id's.
Do you guys have any good and performant solution?
Kind regards and thank you!
Auth::user() will return the authenticated user.
And use relationship method markedProducts() to get the query of products.
And then orderBy the column created_at of pivot table.
At last, apply paginate to this eloquent builder.
Auth::user()->markedProducts()->orderBy('products_marks.created_at', 'DESC')->paginate($limit);

laravel join with polymorphic pivot table using in on clause model names

I'm using eloquent polymorphic relationships that is awesome to manage pivot table between diferent models and other model called company.
I have a pivot table that contains the following structure:
I have to make a join query between vehicle table and pivot table using model_id and model_type using eloquent query builder. But when I do:
$builder->join('pivot_table', function($join){
$join->on('vehicle.id','=','pivot_table.model_id')
->on('pivot.model_type', Vehiculo::class );
})->select('vehicle.*',pivot_table.*)->get();
this code don't return any result. But if I change the second on clause to:
$builder->join('pivot_table', function($join){
$join->on('vehicle.id','=','pivot_table.model_id')
->on('pivot.model_type', 'like' , '%Vehiculo%');
})->select('vehicle.*',pivot_table.*)->get();
this code runs correctly and returns the results what I want, but I think that is the wrong way to obtain the results.
Somebody knows if there is a way make run the first code?
thanks for the responses.
Ok. I solved. The solution is changing the second on to where
$builder->join('pivot_table', function($join){
$join->on('vehicle.id','=','pivot_table.model_id')
->where('pivot.model_type' , Vehiculo::class);
})->select('vehicle.*',pivot_table.*)->get();

how to retrive custom data from database from specific column in laravel php

I have a table users in database
id, name, users_type
there are multiple types of users_type like Admin, Sub Admin, Unsigned, Normal User
I want to get All Types of users_type But Not Admin user.
If you are using eloquent Model then
$users = User::where('users_type', '!=', 'Admin')->get();
Using Query Builder
$users = DB::table('users')->where('users_type', '!=', 'Admin')->get();
check this for query builder https://laravel.com/docs/5.6/queries and for Eloquent you can look this https://laravel.com/docs/5.6/eloquent
$users = User::where('users_type','<>','Admin')->get();
You want to get result for equals to then no need add =
If you want to get only one user then use first() insted of get()

Multiple table data get using with()

Here, is my eloquent
$contacts = Contact::where('property_id',$commercial->id)->where('property_type','commercial_lease')
->with('contact_log')
->with('user_name')
->with('contact_log.contact_log_name')
->get();
->with('contact_log')
with this relationship...I got each and every data from that table using ->with('contact_log'). But i want last inserted data via with relationship.
Others will remains same. But need to get only last data via this relation.
You need to apply extra constraints on your contact_log relation in order to fetch only the last entry.
Replace
->with('contact_log')
with
->with('contact_log', function($query) {
// order latest entries first
$query->orderBy('created_at', 'DESC');
// take only the first entry
$query->take(1);
})

Categories