DolDurma
DolDurma

Reputation: 17301

Laravel get user post with relationship

i have two table as user_blogs and users with this relationship structure

UserBlogs :

class UserBlogs extends Model
{
    protected $fillable = ['user_id', 'blog_content'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    ...
}

User:

class User extends Authenticatable
{
    ...

    public function blogs()
    {
        return $this->hasMany(UserBlogs::class);
    }
}

in controller i can get user blogs with this code:

$userBlogs = User::find($id)->blogs;

and i get can result on output, but why this code dont work and i get error:

$userBlogs = auth()->user()->blogs();

or

$userBlogs = auth()->user()->blogs;

migration:

public function up()
{
    Schema::create('user_blogs', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('blog_title');
        $table->longText('blog_content');
        $table->timestamps();
    });
}

Thanks in advance

Upvotes: 1

Views: 6811

Answers (2)

Sapna Bhayal
Sapna Bhayal

Reputation: 802

I also have same structure for user and their posts. Following code works for me :

$results = Post::with(['user'])->where('user_id',$user_id);
$posts = $results->get();

Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {

    public function user() {
        return $this->belongsTo(User::class, 'user_id');
    }

}

Upvotes: 5

Ben V.
Ben V.

Reputation: 231

Note: because of Eloquent's behavior for deducing table names, you should name your models not plural but singular.

UserBlogs should be called UserBlog instead.

Upvotes: 0

Related Questions