I'm trying to show the last reply that was left on a post. But only the name and date of it. I tried the following things
What I think this one should do is look at the replies to the post. Sort them by ID and then display the first one's username. But it doesn't work.
$topic->replies->sortBydesc('id')->first()->user->username }}
I also tried this one where I requested all the replies in the entire forum and displayed the last one. It worked but I wasn't the one related to the post.
{{ $allposts->sortBydesc('id')->first()->user->username }}
Does anyone know how I can make this work?
Currently, i'm passing these two into the view (There is nothing wrong with these, they work but I think there should be something added)
public function show($id)
{
$topics = Topic::with('theme')->find($id);
$theme = Theme::with('topics')->find($id);
return view('themes.theme')->with('topics', $topics)->with('theme', $theme);
}
Thanks in advance
If you are trying to get topic's replies you need to eager load. Also if you have relation with user who replied eager load it as well.
Use latest() method for getting latest replies.
For only name and date we have select() .
public function show($id)
{
$topics = $topic->with('replies' => function($query) {
$query->with('user')->select('name', 'created_at')->latest();
});
$theme = Theme::with('topics')->find($id);
return view('themes.theme', compact('topics', 'theme'));
}
Related
I have user and news table and then a middle table called news_user, the middle table determines which news has been seen by the user. I can easily get objects that have been seen but, but now I need to show the user objects that have not been seen.
I did a workaround with putting all the seen news id in an array and look for news where id differs from the array. but I don't consider it as the healthiest solution.
This is what I did:
$seenNewses = DB::table('news_user')->where('user_id', Auth::id())
->pluck('news_id')->toArray();
$notSeenNewses = News::whereNotIn('id', $seenKeepers)
->orderBy('id', 'asc')->first();
Is there a way I can do this with a single query?
P.S: I have seen similar questions but they got little confused. Any answer is appreciated.
First in your News Model you need to make relationship like this
public function users()
{
return $this->belongsToMany(News::class,'news_user','news_id','user_id');
}
Below command will give you all the news which are not seen by any users yet
$notSeenNewses = News::doesntHave('users')->get();
If you want to put any condition then also check for
$notSeenNewses = News::whereDoesntHave('users', function ($query) {
$query->where('YOUR CONDITION');
})->get();
It's not tested but you can modify as per your need.
how to display data one too many relationships with conditions into view.
I have a blog post that has a comment, but this comment has a condition that published or not.
here my Post Model
...
public function comments()
{
return $this->hasMany(Comment::class);
}
...
on my code above I can simply use $post->comments to show all the comments.
like I said before, I need only show comments with published is true
but how to add conditions?...
You can achieve this by getting the post with it's published comments;
$post = Post::where('id', $id)->with('comments', function ($q) {
$q->where('published', true);
})->first();
Then when in the view you call $post->comments, you will only get the published one.
Alternatively, if you really want to you can update your Model to have a published comments relationship, but this is less advised.
public function publishedComments()
{
return $this->hasMany(Comment::class)->where('published', true);
}
You can get only published comments by using
$this->post->comments()->where('published', true)->get()
Check the Documentation
Of course, since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments method and continuing to chain conditions onto the query: $comment = App\Post::find(1)->comments()->where('title', 'foo')->first();
i have the next structure:
model call content
public function credits(){
return $this->belongsToMany('App\models\Credit');
}
model call Credit
public function content()
{
return $this->belongsToMany('App\models\Content');
}
What i am triying to do is extract all the credits of one content, but selecting only the columns that i want, with the below code:
$credits2=$this->content::with(array('credits'=>function($query){
$query->select('id','department','job');
}))->where('id',$id_content)->get();
The problem that i have is that when i execute all the code the result is:
[]
but if i do a normal query in mysql i can figure out that for the movie exists credits.
I have extracted this code, from other forums, and stackoverflow post.
There is another easy way to specify columns without using closure:
$credits2 = $this->content::with('credits:credits.id,department,job')
->find($id_content->id);
The problem was that $id_content was a result from a previous query, so if i put $id_content didn't work, for that i have to access to the column.
And the solution is:
$credits2=$this->content::with(array('credits'=>function($query){
$query->select('id','department','job');
}))->where('id',$id_content)->get();
What I'm trying to do is to show the posts that have been saved by the user in the profile. I will try to explain it as good as possible refering to my code. So:
public function userProfil($id)
I have the profile function which get the data from userprofile table. and inside I have the following code for saved data:
$authed = User::find($id);
$savedarticles = $authed->mysaves;
$allsavings = DB::select("Select * from article where id=$savedarticles->id");
But this code does not work like this anyway. I can do this instead:
$authed = User::find($id);
$savedarticles = $authed->mysaves;
But when I try to get articles from article table with the article_id of mysaves, it does not work such as this:
$allsaved= DB::table('article')->where('id', $savedarticles->article_id);
the error it gives is like:
Property [article_id] does not exist on this collection instance.
although savearticle table has article_id I can output it without the line above and in view I get them as:
#foreach($savedarticles as $savedarticle)
<p>{{$savedarticle}}</p>
#endforeach
it gives me everything that is in the savearticle table and I can get do savedarticle->article_id and get article_id but can't get it in controller.
I am using Laravel 5.4.
The error message Property [article_id] does not exist on this collection instance. means you are trying to get an attribute of a single instance but from a collection.
For example the collection could be like
[$article1, $article2, $article3]
therefore what you tried to do is something similar to
[$article1, $article2, $article3]->article_id
You are trying to get an attribute from a collection instead of a single instance.
As for your query, you can use where in sql statement to search for rows that match any item in an array
$allsaved= DB::table('article')->whereIn('id', $savedarticles->pluck('article_id')->all());
What I have understood is that A USER has many POSTS and a POST belong to an article.
If this is true then you have to do following.
1: In USER model define a relation to get all posts. like below.
public function posts() {
// Foreign key will be a key that is stored in posts table and represent the user MAY BE: user_id
$this->hasMany(Posts::class, 'foreign_key', 'local_key')
}
This will allow you to get all posts belong to a user.
2: In posts, model defines a user relation like below.
public function user() {
$this->belongsTo(User::class, 'foreign_key', 'local_key');
}
This will allow you to get a post User;
3: Now in your controller you will have something like this.
public function show($user_id) {
// find a user with posts as eager loading(to avoid query again)
$user = User::with(['posts'])->where('id', $user_id)->first();
// get all posts that belong to this user
$posts = $user->posts;
}
In controller show($user_id) method you will have a user data as well as user posts data. Now if you want to get a post relations then simply define as below. let say a post belongs to an article as well.
4: In posts, model defines a relation to get an article.
public function article() {
// This will allow you to get a post artcle
$this->belongsTo(Article::class, 'foreign_key', 'local_key');
}
Now you can get the article as well while finding a user. please see below. I am rewriting controller show action to give you a better understanding.
5: Get a user with user_id
public function show($user_id) {
// find a user with posts as eager loading(to avoid query again)
// eager loading for posts & post child, this will give you NOSQL at runtime and all data will come from one query.
$user = User::with(['posts', 'posts.article'])->where('id', $user_id)->first();
// get all posts that belong to this user
$posts = $user->posts;
foreach($posts as $post) {
$article = $post->article; // Child relation of post.
}
}
Hope you will understand the flow, you have to make sure models relation to work it perfectly. If you need further help please let me know.
So I have the tables tags, posts and a link table for these
Now I want to get all the tags from the current post.
Now I want to get all the tags related to this post.
I made a model "Tag" (with no functions yet, just extending Eloquent)
How can I use this model to get all the tag names/titles based on the current post id, or do I need a seperate model for the Linking table(Which seems incorrect to me)?
I'm kinda lost in it right now, probably due to too much searching.
Anyone can help me out here?
SOLVED
$post = Post::where('id', $id)->first();
$tags= $post->tags;
Tags function in the Post model:
public function tags()
{
return $this->belongsToMany('Tag');
}
Add the following function to your Post model
public function tags()
{
return $this->belongsToMany('Tag');
}
Now you can call $post->tags()->getResults() to get all tags of a post.
Corresponding docs: http://laravel.com/docs/4.2/eloquent#many-to-many