Laravel One to Many relationships with CRUD example
Laravel One to Many relationships is used to define situations where one entity in our database is related to many entities of the same type in our database.
In a voting system example, we can see that the political parties and candidates have a one to many relationships.
A political party can have many candidates — at least two candidates for each category of elections, for the running mates; and it could have several candidates if we make it extend to the presidential, governorship, and other levels of elections.
However, a candidate can only belong to one political party (at a time at least).
Another good example is categories and products — a simple system could exist where a category can have many products, but each product should belong to only one category.
If we were to define this relationship in plain English, we’d say:
“A political party has many candidates”.
Eloquent makes it easy to define such relationships:
Go ahead and take a guess at how Eloquent defines it?
Well, it’s done by using the hasMany method (I hope you got it right).
We use it like this:
<?php
namespace App\Models;
use…