0
votes

I want to make a relation between post and user to be able to get all posts by this way $user->posts() and to get user by this way $post->user()

I made belongsTo function but i need a way so when i get the user i can find all his posts somehow also when i get the post i used \App\Post::find(1)->user()->name it return nothing

Post Model

class Post extends Model
{
    public function user() {
        return $this->belongsTo('App\User',null,'userid');
    }
}

Post DB Structure

Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->longText('body');
            $table->string('thumbnail');
            $table->integer('views');
            $table->integer('likes');
            $table->bigInteger('userid');
            $table->integer('categoryid');
            $table->timestamps();
        });

User Model has nothing in it rather than laravel defaults because user has no columns that refer to posts

User DB Structure is Laravel Default

Foreach code:

@foreach(\App\Post::find(4)->user() as $user)
            <p>{{$user->name}}</p>
@endforeach

i expected it to get the user name but it didn't..

2

2 Answers

1
votes

Use the hasMany relationship.

Within user model:

public function posts()
{
    return $this->hasMany(Post::class, 'userid', 'id');
}

Now, you are able to get all user posts:

$posts = User::find($someId)->posts()->get();
//or
$posts = User::find($someId)->posts;

Docs about has many relationship

Hope it helps.

0
votes

In User model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

In User model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Post;

class User extends Model
{
    /**
     * Get the posts for the user.
     */
    public function comments()
    {
        return $this->hasMany('App\Post');
    }
}

Now you can access posts of user as App\User::find(id)->posts