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..