Has Many Relationship( One to many )

One to many relationship is is most commonly used relationship, Where in this example I will show you a book has only one author, But author can have many books.

authors table columns : id, name, description, created_at, updated_at.

Author Model(App/Author.php)

In this Author model, there are books method which returns multiple matches rows in collection. We can handle it as an array.

<?php namespace App;
use Illuminate\Database\Eloquent\Model;

class Author extends Model {
	protected $table = 'authors';

    public function books(){
        //Returning multiple rows from books table 
        return $this->hasMany('App\Book');
    }
}

 

books table columns : id, title, description, author_id(foreign key), created_at, updated_at.

Book Model(App/Book.php)

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model {

    protected $table = 'books';
	
    public function author(){
        return $this->belongsTo('App\Author');
    }
}

 

App\Http\routes.php

This route section author/{name} where {name} which could be anything like:

http://localhost/author/john where word 'john' will check from database, If it matches from existed records then return results which will redirect to view page.

<?php
Route::get('author/{name}', function($name){
    $author =  Author::where('name', $name)->firstOrFail();
    return view('authors.author', compact('author'));
});

 

resources/view/authors/auhor.blade.php

Look at below code there are we getting some information by route. $author->books->title It has specific author's all books information in array or collection but we need here only title. 

<?php
@if($author->description == null )
    No description found
@endif
{!! $author->description !!}

<h3>Book published by {!! $author->name !!} </h3>
@foreach($author->books as $book)                  //books from Author model books() method
    {!! $book->title !!}<br>
@endforeach

 

Something to say? Tell us in comment section.