Osman Goni Nahid
Osman Goni Nahid

Reputation: 1279

How can i get all posts by a particular user in Laravel?

Try to get all post's by a user in application and show in a table with corresponding column , i tried with this way but showing exception : " Trying to get property of non-object " , how to solve it ?

public function usersPost(){
$uid = \Auth::user()->id;
$posts = DB::table('posts')->('user_id',$uid);
}

Here two table posts and users and user_id is foreign key of posts table .

Upvotes: 2

Views: 7759

Answers (3)

Curtis
Curtis

Reputation: 113

Laravel allows you to relate models to each other. For instance, you can relate your Post model to your User model like this.

class User extends Eloquent {

    public function posts() {
        return $this->hasMany('Post');
    }

}

After specifying that the User has many posts through a One-to-Many relationship, you can then simply call all of your user's posts.

$posts = User::find(user_id)->posts;

Upvotes: 6

mikegeorgeff
mikegeorgeff

Reputation: 36

You need a where clause like this:

$posts = DB::table('posts')->where('user_id', $uid)->get();

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 219930

public function usersPost() {
    $posts = DB::table('posts')->where('user_id', auth()->id())->get();
}

Upvotes: 4

Related Questions