Hi I have two models Category,News, i want to retrieve categories with 3 latest news in each category, News models have created_at column for date when it created.
Can i achieve this in laravel
try this way,
$news = Category::whereHas('news',function($query){
$query->orderBy('created_at', 'desc')->take(3);
})->get();
Related
I have two model: Category and PostAd model.
They two have relation with each other.
In laravel view i have passed data through Category Model to display PostAd data.
I want to apply OrderBy condition in query but it doesn't work
Code
$data['category'] = Category::with(['postads'])->where('id',$id)->get();
I want to do this
$data['category'] = Category::with(['postads'])->where('id',$id)->orderBy('adtitle','DESC')->get();
But it doesn't work because it is Category Model.
How can i solve this.
if you want to get PostAd data with an order by then you can do an eager load Order by.
And here you're using get() method so it should be first(); because ->where('id',$id) always get one record.
$data['category'] = Category::with(['postads' => function($query) {
$query->orderBy('adtitle', 'DESC');
}])->where('id',$id)->first();
I'm creating an application where user can have one speciality.
User can in backend create posts assigned to his speciality, and has to associate it to one category.
I'm wondering how to manage categories when a doctor and an lawyer can use the same category, and not display all posts for all specialities where category is the same.
So actually:
user has one speciality
speciality has many categories
category belongs to many specialities
I think i have to create a pivot like category_speciality, as explained in Laravel doc for many to many relationships.
But then i can't figure how to use speciality an category to build dedicated queries and urls.
Any help will be great !
For URL's you could do something like:
web.php
Route::get('/articles/{category}/{specialty}', [
'uses' => 'PostController#index',
'as' => 'posts.index'
]);
where {category} and {specialty} are a unique slug field of their title. This would result in e.g. example.com/articles/deep-sea/fishing.
PostController
public function index($categorySlug, $specialtySlug)
{
$specialty = Specialty::where('slug', '=', '$specialtySlug')->first();
$posts = Posts::where('specialty_id', '=', $specialty->id)->get();
return view('posts.index', compact('posts'));
}
That is assuming you have specialty_id in Posts table and you have correct relationships set up.
This is just an example.
I have 3 tables in my database. users, books and book_user.
book_user is the pivot table that manages the many-to-many relationship between users and books.
I have the Laravel relationship correctly setup and i am able to display all the books associated to a user using the following in Laravel.
$user = Auth::user();
return response()->json($user->books()->get());
Now i am trying to display all the books that are NOT associated to a particular user. I have been struggling for quite some time and cant seem to find anything that works. Any tips would be greatly appreciated.
If the book is not related to the user then you should not try to retrieve it via the user. Instead use the book model:
Book::whereDoesntHave('users', function ($q) {
$q->where('id', \Auth::id());
})->get();
If you want all books not belonging to any user at all, instead of all books not belonging to a particular user, you could do something like :
$books = Book::whereDoesntExists(function($query) {
$query->select('book_user.id_book')
->from('book_user')
->where('book_user.id_book', '=', 'books.id');
// Assuming that the columns on the pivot table are 'id_book' and 'id_user' and the primary key is 'id' in the 'books' table.
});
Here you fetch all books that haven't their id in the book_user pivot table's id_book column. So basically, all books not belonging to any user.
How to Limit Related Model from Parent Model in Laravel,
I have Category and News Model, I want to fetch all categories and each category with 3 latest news.
Please try this. You will get all categories that as minimum one news model related
$news = Category::whereHas('news',function($query){
$query->orderBy('created_at', 'desc')->take(3);
})->get();
I am using laravel 5.1 for a CMS development. I have a simple structure of posts, users and users can like posts.
I want to list the trending posts (posts with most likes in last 1 week in desc order). Posts and Users have many-to many relationship and use a pivot table for relationship.
Posts Model has
public function likedby()
{
return $this->belongsToMany('App\Models\User','user_like_post')
->withTimestamps();
}
User Model has
public function likes(){
return $this->belongsToMany('App\Models\Post','user_like_post')
->withTimestamps();
}
How can I write eloquent query so I receive the trending post. I need to use the timestamp of the pivot table which I find difficult to use.
This is what I tried but it used 'created_at' of post table and not of pivot table.
$trending = Post::with('likedby')->get()
->sortByDesc(function ($post){
$one_week_ago = Carbon::now()->subWeeks(1);
return $post->likedby
->where('created_at','>=',$one_week_ago)
->count();
}
);
You can constrain an eager load within the with method, however this would still load all the posts but only eager load the likedby relationship when it is less than one week old. This is probably not the behaviour you want, but worth mentioning.
Post::with(['likedby' => function($query) {
$query->where('created_at', '>=', Carbon::now()->subWeeks(1));
}])->get();
To only load posts that have been liked within the last week, you would be best served by the whereHas method. This will provide you with a list of posts that have had likes placed on them within the last week.
Post::whereHas('likedby', function ($query) {
$query->where('created_at', '>=', Carbon::now()->subWeeks(1));
})->get();