I have Post and User Model with relationship as follows:
user_id
is the foreign key in posts
table referenced to the id
of the users
table
Post Model
public function user () {
return $this->belongsTo(User::class,'user_id','id');
}
User Model
public function posts () {
return $this->hasMany(Posts::class, 'user_id', 'id');
}
And a PostController
with store method:
public function store(Request $request){
$this->validate($request, [
'title' => 'required|max:255',
'desc' => 'required|max:255'
]);
$image = null;
$files = $request->thumbnail;
$thumb = time().'.'.$files->getClientOriginalExtension();
$request->thumbnail->move(public_path('public'),$thumb);
$image = $thumb;
$post = Posts::create([
'title' => $request->title,
'thumbnail' => $image,
'user_id' => __________
'desc' => $request->desc
]);
return $post->toJson(); }
Considering that, I want to acheive a relationship as: a user can have many posts.
So, how can I get the id
of the user
with the help of relationship between users
and posts
table to insert in the posts table.
Edit: in above controller how can I get user_id value??