Instead of belongsTo, use hasMany

For belongsTo relationship, instead of passing parent's ID when creating child record, use hasMany relationship to make a shorter sentence.

1// if Post -> belongsTo(User), and User -> hasMany(Post)...
2// Then instead of passing user_id...
3Post::create([
4 'user_id' => auth()->id(),
5 'title' => request()->input('title'),
6 'post_text' => request()->input('post_text'),
7]);
8 
9// Do this
10auth()->user()->posts()->create([
11 'title' => request()->input('title'),
12 'post_text' => request()->input('post_text'),
13]);

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord