How to Save and Display One-to-Many Relationship in Laravel【hasMany】
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents of Laravel articles
I will write about how to save and display a one-to-many relationship in Laravel.
What is a Relationship?
It refers to data that is related between tables in a database.
In this example, by saving user_id, you can reference user data from the users table.
In Laravel, you can easily implement this with a few definitions.
The contents of this article are a summary of the official documentation
Verification Environment
Laravel 6
Table Design
In a relationship where the users table is 1 and the posts table is many, you save user_id on the many side.
The important thing to note here is,
"Save with singular_id
"
If you are going to relate to the users table's id, it is a naming convention to save it as user_id.
(Although this is the naming convention, there are other ways to set up relationships. However, it is good to know that there are other methods due to this being a special case.)
Saving user_id in Post
The following is the description in the Controller.
use App\Post;
use Auth;
~~~~~~~~~~~~~~
public function store(PostRequest $request)
{
$post = new Post;
// When posting, save the ID of the logged-in user.
$post->user_id = Auth::id();
$post->title = $request->title;
$post->content = $request->content;
$post->save();
return redirect()->route('post.create');
}
If you are unsure about the posting feature, please refer to this article.
Creating a Posting Feature in Laravel for Beginners (Something Like a Bulletin Board)
Validating Forms with Laravel Form Requests for Beginners
Retrieving Related Data
From the perspective of the user, post can have multiple possibilities.
Edit the User.php model.
public function posts()
{
return $this->hasMany('App\Post');
}
With this, the preparations are done.
Assume that you want to get a list of users.
Controller
use App\User;
~~~~~~~~
public function index()
{
$users = User::all();
return view('users/index',compact('users'));
}
Views
@foreach($users as $user)
{{ $user->posts }}
@endforeach
If data is present, there should be chaotic data in an array.
This is because in a one-to-many relationship, the many side assumes multiple instances, so they come out in an array form.
If you want to display them all,
@foreach($users as $user)
@foreach($user->posts as $post)
<h3>{{$post->title}}</h3>
<p>{{$post->content}}</p>
@endforeach
@endforeach
You need to loop through them again with foreach.
Eager Loading (Reduce Database Connection Time)
Actually, the previous foreach implementation is not very good in terms of writing code.
This is because for each user, a connection is made to the posts table to retrieve the data.
This is known as the N+1 problem and the like.
Therefore, in Laravel, a method to solve this problem is provided.
Controller
public function index()
{
$users = User::with('posts')->get();
return view('users/index',compact('users'));
}
Simply write with('function name defined in the model').
Therefore, remember that with is the happy set for relationships.
What Happens with a Join
Join is a method of retrieving data that is different from defining a relationship in the models as introduced earlier.
public function index()
{
//table to join, which column from where, which column from where is =
$users = User::join('posts','posts.user_id','=','users.id')
->get();
return view('users/index',compact('users'));
}
It will be like this.
In the first argument, specify the table to join and which columns from which table are equal.
Summary
How was it?
The above is an article that summarizes relationships in an easy-to-understand way from my perspective.
If you have any feedback or typos, please contact me via Twitter DM.
Popular Articles
Deploying PHP7.4 + Laravel6 Project to AWS EC2
Related Articles
How to Create a One-to-One Relationship in Laravel【hasOne】
How to Save and Display Many-to-Many Relationship in Laravel【belongsToMany】