Laravel Model Relationships is the today’s primary subject. In this post, we will create two tables and build up the relationship between these tables. We will use hasMany() relationship in this example. Eloquent Relationships are very compelling and save a lots of your time. So let start today tutorial.

Install laravel

Run windows terminal and navigate it to the folder where you want to install the laravel project. To install the project run the below command.

laravel new laravelmodel

After installation is complete then go the the project folder. To go to the project folder type below command on your terminal

cd laravelmodel

Then re-generate the new key for the project

php artisan key:generate

Now setup the database credentials in your .env file

DB_DATABASE=Your Database Name
DB_USERNAME=Your User Name
DB_PASSWORD=Your Password

Go to the App/Providers/AppServiceProvider.php and modify the boot method

use Illuminate\Support\Facades\Schema;
    
public function boot(){
    Schema::defaultStringLength(200);
}

Laravel provides us the Authentication Scaffold which is used for creating the registration system. Let’s use that for login

php artisan make:auth 

Now go to the terminal and migrate the user table to database using the following command.

php artisan migrate

Let’s start the laravel server by using the following command.

php artisan serve

Now open the url http://127.0.0.1:8000/ and register the user by clicking on the register button.

Welcome Page

Category

Model & Migration

Now we will create the category model. To create the category model, go to the terminal and run the following command

php artisan make:model Category

Now create the migration by running the following command on terminal.

php artisan make:migration create_categories_table

All the migration file are stored on database/migrations folder. Go to the migration folder and write the schema for the 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();
        });
    }

Now, let’s go to the Category model. All the models files are on the app folder. Go to the Category model and add the following code on the model.

protected $table = 'categories';

    protected $fillable = [
        'user_id', 'title',
    ];

Controller & Routes

Now we need the id of the register users. If you haven’t already register then register now. Next step is to create the CategoryController. Run the following command on your terminal for category controller.

php artisan make:controller CategoryController -r

At first, let’s create route before making any changes on CategoryController. To create route go to routes/web.php

Route::resource('category', 'CategoryController');

Now let us make change on CataegoryController. Inside CategoryController.php create function add the following code

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('category.create');
    }

In create function we can see that we had make return view to ‘category.create’. So we need to make the create view inside the category directory. For that case, go to the resources/views folder. Inside views folder create a new folder named category. Then create the view create.blade.php inside the category folder. Write the below code on 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" role="form">
                            @csrf
                            <div class="card-body">
                                <label for="title">Title</label>
                                <input type="text" class="form-control" name="title" id="title">
                            </div>
                            <div class="card-footer">
                                <button type="submit" class="btn btn-primary">Save</button>
                            </div>
                        </form>
                </div>
            </div>
        </div>
    </div>
@endsection

This code will make a form for inserting the category title in our database. You can get the create category form on the url 127.0.0.1:8000/category/create. The form will look like as shown in the figure below

Category Title

Model relationship

Till now we have only created the form for adding title of category. We also need to save the title of the category in the database. But before saving the data to the database, we will see the users and the categories table relationship.

A relationship, in the context to the database, is connection or link between two tables through a primary key and a reference key. One table has a foreign key that references the primary key of the another table. Relationship allow relational databases to split and store the data in various tables.

Database table are often related to one other. For example, we can take our current situation. Here we have an user and a category table. Users can create or can have many category but one category can have only one users. Here the relationship between the user and the category table is one to many relationship. We will discuss more about the database relationship later.

Now we will be writing the relationship for the users and the category. Go to the User model and define the relationship with Category

/**
     * User can have many categories
    */
    public function categories(){
        return $this->hasMany(Category::class);
    }

Now go to the Category model and define the relationship with User

/**
     * Category can have one user
    */
    public function user(){
        return $this->belongsTo(User::class);
    }

Saving Category Data on Database

To save the category data, go to the CategoryController.php and add the following code on the store function.

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $category = new Category;
        $category->title = $request->title;
        $category->user_id = Auth::user()->id;
        $category->save();
        return redirect(route('category.create'))->with('status', 'Category saved successfully');
    }

In the store method I have used ‘Auth::user()->id’ to get the id of the current user. Because of that if we try to save the category title without logging in in the system we will get error message. We may want to redirect the user to login page, when the user tries to go to the 127.0.0.1:8000/category/create page. For that case, we will define the __construct method on controller. Add the __construct() method at the top inside the class as shown below

...

class CategoryController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

...

After adding the __construct() if you try to access the 127.0.0.1:8000/category/create page without logging then you will be automatically redirected to the login page.

Fetching Data

We also need to fetch the data from the database and show it in our site. In CategoryController.php add below given code on index method.

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = Category::all();

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

Create the index views inside the resources/views/category folder and add the below given code.

@extends('layouts.app')

@section('content')

    <div class="container">
        <div class="row justify-content-center">

                @foreach( $categories as $category)
                    <div class="card">
                        <div class="card-header">{{ $category->title }}</div>

                        <div class="card-body">
                            <div class="card-text">
                                Created By: {{ $category->user->name }}
                            </div>
                        </div>
                    </div>
                @endforeach

        </div>
    </div>

@endsection

The data that are store will be seen by the users in the following format.

View image

CONCLUSION

In this article, we learn about the Laravel Model Relationship . This is a simple example you can add your own design and logic as per your requirement. If you wish to add to the discussion or would like to ask a question, leave a comment below.

Download Source Code from below

Download Code

Comments

Leave a Reply

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