Laravel 10 One to Many Relationship Example

Laravel 10 One to Many Relationship Example

Laravel one to many relationship example; In this tutorial, you will learn one to many relationship with examples in laravel.

Using one to many relationship, you can perform crud (create, read, update, delete) operation with the eloquent model from the database table in laravel.

Laravel Eloquent One to Many Relationship Example

Let you have two tables name posts and authors. Using laravel migration, you can create both tables with the following fields:

Author table migration:

Schema::create('authors', function (Blueprint $table) {

    $table->increments('id');

    $table->string('name');

    $table->timestamps();

});

Post table migration:

Schema::create('posts', function (Blueprint $table) {

    $table->increments('id');

    $table->string('title');

    $table->text('description');

    $table->integer('author_id')->unsigned();

    $table->timestamps();


    $table->foreign('author_id')->references('id')->on('authors')

        ->onDelete('cascade');

});

Define One To Many Relationship

One to many relationships determines a relationship where one single model owns the number of the other model. For example, a blog author may have many posts.

A single author can have written many post articles. Let’s take an example of one to many relationships.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    ...
    public function post()
    {
        return $this->hasMany('App\Post');
    }
}

We can then access the collection of post articles by using the post() method as.

Using this, we get all the posts of a single author. Here we need to get the author details of a single post, for each post there a single author, within the Post model includes belongsTo relation.

$posts = App\Author::find(10)->post()->get();

 foreach ($posts as $post) {
     //do something
 }

Defining Inverse One To Many Relationship in Laravel

Since we can now access all the post articles of an author, it is time to allow a post article to access its parent model (Author model) or access author details by using the post model. The inverse relationship of both One to One and One to Many works the same way. Both use the belongsTo method to define the inverse relation. Thus we can define one as:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}

Using this, Here we need to get the author details by using posts, for each post there a single author, within the Post model includes belongsTo relation.

$post->author->name;

Retrieving Data

Once you have defined the relationship on models, you can retrieve data from the DB table using the eloquent model.

In this example, you can get all posts of a particular author: 

 $posts = Author::find(10)->post()->get();

 foreach ($posts as $post) {
     //do something
 } 

Similarly, you can retrieve the inverse related model.

 $posts = Post::find(10)->author()->get();

 foreach ($posts as $post) {
     //do something
 } 

Inserting Data

To create a relationship between two models or associating them, we can first create a child object and then save it using the parent object.

$author = Author::find(1);

$post= new Post();
$post->title = 'iPhone X';
$post->description = 'Some description';

// Saving related model
$author->post()->save($post);

You can also use the saveMany() method instead of save() to associate multiple records.

Filtering Data

You might want to filter the related records and want them to sort when retrieving. You can chain the methods on your retrieving query.

$author = Author::find(1); 
$post = $author->post() 
 ->orderBy('name', 'asc') 
 ->get(); 

Deleting Data

Deleting one to many relationship is the same as we have created them. Firstly we get the parent object which is brand and then use the post() method to delete all post. To delete all posts for a particular author use below code example.

$author = Author::find(1);
$author->post()->delete();

Conclusion

In this tutorial, you have learned how to define one to many relationship and using this relationship how to perform crud operation with an eloquent model from database tables.

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *