Laravel One to Many relationships with CRUD example

Solomon Eseme
Backend Developers
Published in
7 min readDec 30, 2020

--

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.

one to many relationships

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

--

--

Solomon Eseme
Backend Developers

A Software Engineer who’s geared towards building high performing and innovative products. I help you become a great Backend Engineer @ masteringbackend.com