AppDividend
Latest Code Tutorials

Laravel Model Relationships Example From Scratch

Laravel 5.6 One To Many Relationships Tutorial

638

Get real time updates directly on you device, subscribe now.

Laravel Model Relationships Example is the today’s main topic. In this tutorial, I will define two tables and establish the relationships between the tables. We will explore hasMany() relationship in this example from scratch. Eloquent Relationships are very compelling and save your lots of time. So let us get started this tutorial of Laravel Model Relationships Example.

Laravel Model Relationships Example

Let us install Laravel 5.6.

Step 1: Install Laravel 5.6.

I am using Laravel Valet.

laravel new relationships

If you are not using Laravel Valet, then install using the following command.

composer create-project laravel/laravel relationships --prefer-dist

After that, go into the project folder.

cd relationships

Setup the database in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name
DB_USERNAME=your username
DB_PASSWORD=your password

Now, go to the terminal and migrate the two default tables using the following command.

php artisan migrate

Laravel Auth

Laravel provides us the Authentication Scaffold. So, let us use that. Type the following command.

php artisan make:auth

We need to create a user because we will save the user_id for the upcoming new table’s data.

Now, register the user by going to this URL: http://relationships.test/register. Of course, if you are not using Laravel Valet, then you need to start the Laravel development server by the following command.

php artisan serve

Go to this URL: http://localhost:8000/register.

Step 2: Create Category and Post models.

Now, we will create the following models.

  1. Category.php

Go to your terminal and type the following command.

php artisan make:model Category -m

It will also create the migrations. Now all the migration files are inside database >> migrations folder.

Now, write the schema for the create_categories_table.

// create_categories_table

/**
  * Run the migrations.
  *
  * @return void
  */
   public function up()
   {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->timestamps();
        });
   }

Run the migrations using the following command.

php artisan migrate

Step 3: Create a category form.

Now, we do need an ID of registered User. So first register in the Laravel application. You will redirect to the ‘/home’ route. Next step is to create a CategoryController. So, generate using the following command.

php artisan make:controller CategoryController

Next, go to the web.php file and create the route to add the categories.

// web.php

Route::get('/category/create', 'CategoryController@create')->name('category.create');

Also, we need to define this route in the navigation bar. So inside views >> layouts >> app.blade.php file, add the right side the navigation link.

<li>
    <a class="nav-link" href="{{ route('category.create') }}">
         Create Category
    </a>
</li>

Inside CategoryController.php file, add the create() function.

Related Posts
1 of 37
// CategoryController.php

public function create()
{
    return view('category.create');
}

Inside views folder, create one folder called category and inside that folder, make one file called create.blade.php.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Create Category</div>
                <form action="{{ route('category.store') }}" method="post">
                    <div class="card-body">
                        @csrf
                        <label>Title</label>
                        <input type="text" class="form-control" name="title" />
                    </div>
                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary">Add</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

 

Laravel Many To Many Relationships

Now, define the store route inside a web.php file.

Route::post('category/store', 'CategoryController@store')->name('category.store');

But before, code the store function, we need to define the relationship between Category and User model.

Step 4: Define User and Category Relationship.

Now, the One User can create multiple Categories, and each Category belongs to a User.

So write the following function inside User.php file.

// User.php

public function categories()
{
    return $this->hasMany(Category::class);
}

Also, we need to define the inverse relationship inside Category.php file.

// Category.php

public function user()
{
    return $this->belongsTo(User::class);
}

Step 5: Save the categories in the database.

As we have defined the relationship between User and Category, we now can associate the Category with a particular User.  We can write the following code inside store() function.

// CategoryController.php

public function store(Request $request)
{
    $category = new Category;
    $category->title = $request->get('title');
    $category->user()->associate($request->user());

    $category->save();

    return 'Success';
}

Now, we can save the data into the database.

Whole CategoryController.php file looks like this.

// CategoryController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;

class CategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function create()
    {
        return view('category.create');
    }

    public function store(Request $request)
    {
        $category = new Category;
        $category->title = $request->get('title');
        $category->user()->associate($request->user());

        $category->save();

        return 'Success';
    }
}

Step 6: Display the Categories with User’s name.

Now, we need to display the posts with their username. Let us log out the session and try to register with another user and create two-three categories as well. I have created the second user.

Laravel 5.6 Authentication

 

Now, create the categories with this second user.

Laravel 5.6 CRUD

 

 

 

From an Image, you can see that, I have created three-three categories from two users.

Now, display the categories with respective users.

First, create a route to display the categories.

// web.php

Route::get('categories', 'CategoryController@index')->name('category.index');

Code the index function inside CategoryController.php file.

// CategoryController.php

public function index()
{
    $categories = Category::get();

    return view('category.index', compact('categories'));
}

Now, inside views >> category folder, create one file called index.blade.php and write the following code inside it.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
    @foreach($categories as $category)
    <div class="card" style="width: 18rem;">
        <div class="card-body">
            <div class="card-title"><h3>{{ $category->title }}</h3></div>
            <div class="card-text">
                Created By: <b>{{ $category->user->name }}</b><br />
                Created At: {{ $category->created_at->diffForHumans() }}
            </div>
        </div>
    </div>
    @endforeach
    </div>
</div>
@endsection

Now, for display the user’s name, I have used Eager loading, which is very important definition.

Eager Loading in Laravel

At a basic level, Eloquent ORMs “lazy” load related model data. After all, how’s the ORM supposed to know your intention? Perhaps you will never actually use the related model’s data after querying the model. Not optimizing the query is known as a “N+1” issue. When you use objects to represent queries, you might be making queries without even knowing it.

Laravel’s ORM, called Eloquent, makes it trivial to eager load models, and even eagerly loading nested relationships. Eager loading optimizes the database queries related to ORM, in our case, it is Eloquent ORM.

So, the output will display like below image.

Laravel Eager Loading

 

So, we have successfully use the Laravel hasMany and Inverse relationships.

Although In Eloquent Relationships, there are more relationships than this, we will cover in the future for sure.

Finally, our Laravel Model Relationships Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.