I'm currently building a small app to learn Laravel. I'm new to the whole framework and I've been struggling with creating a timeline...
In the app you can ask a user a question, and that user can answer the question. You can also follow users and on the homepage/timeline, you can view everyone's questions/answers.
I have all this setup and working.
However, there are a few issues:
- On the timeline, I'd like to show everyone's questions/answers of user I'm following plus my own.
- Make sure only answered questions are shown
- And then sort the posts in order by the answer's created_at.
On the timeline I have this:
$id = Auth::id();
$replies = Questions::has('answer')->with('user')
->join('followers', 'followers.user_id', '=', 'questions.user_id')
->where('followers.follower_user_id', '=', $id)
->orderBy('followers.created_at', 'desc')->get();
Here are my Models:
Answer.php
public function question()
{
return $this->belongsTo('App\Questions', 'question_id');
}
Questions.php
// returns the answer instance for the questions
public function answer()
{
return $this->hasOne('App\Answer', 'question_id');
}
// returns the user who was asked the question
// i.e billy asked Fred 'who is your crush', Fred is returned
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
// returns the user who asked the question
// i.e billy asked Fred 'who is your crush', Billy is returned
public function author()
{
return $this->belongsTo('App\User', 'author_id');
}
User.php
public function questions()
{
return $this->hasMany('App\Questions');
}
/**
* The following that belong to the user.
*/
public function following()
{
return $this->belongsToMany('App\User', 'followers', 'follower_user_id', 'user_id')->withTimestamps();
}
public function isFollowing(User $user)
{
return ! is_null($this->following()->where('user_id', $user->id)->first());
}
I have 3 tables:
The Tables look like this:
- Users:
id
- Followers:
user_id, follower_user_id (user_id is the logged in user, follower_user_id is the user the logged in user is following)
- Posts:
user_id
Is there a way to acomplish this with the way I'm currently doing it, or is this not going to work? I was going to make a bunch of foreach loops and add all the data to an array and pass the array to my view but figured that would be a terrible idea.
Thanks for all the help, really appreciate it!