Laravel CRUD Example (Laravel 7)

0
3280

Laravel CRUD Example (Laravel 7) – In this tutorial, you will learn how to create CRUD (Create, Read, Update, and Delete) application using Laravel 7. This Laravel CRUD example is for those beginners who are looking to make their feet wet in the field on the PHP Laravel framework.

This is the very beginner laravel tutorial so you don’t need to have any prior knowledge to learn about this, however, we supposed that you have a working environment that fulfills all the basic needs to run a laravel application. In case if you don’t know, anything about those like set up of virtual host or installation of Laravel then please check to our old tutorial on how to install laravel 7 on windows.

After reading these articles you are all set to go, and without any delay let’s jump into the tutorial.

How to create a basic Laravel CRUD application? (Laravel 7 CRUD example)

Step 1: Create Laravel 7 Application 

First of all, we need to create a fresh laravel application using Composer or the command using the global laravel installer. If you haven’t installed global laravel installer run following command (inside wamp’s www or XAMPP’s htdocs folder):

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

Where laravel-crud is the project or application name. In case if you have already installed global laravel installer as mentioned on how to install laravel 7 on windows then you are free to run following command:

laravel new laravel-crud

Step 2: Database Configuration

After creating laravel-crud application, we need to configure the correct database credentials in the `.env` file. It is similar to every other PHP application where you need to enter the host, database name, database username, and database password.  To add this value open `.env` file and fill the correct credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel  //replace laravel with your database name
DB_USERNAME=root     //replace root with your database username
DB_PASSWORD=         //enter database password here

Make sure, you have already created the database with entered name on phpmyadmin.

Step 3: Create and Run Migration

If you had checked our previous article on laravel auth scaffolding, you should be familiar with laravel migration. But, if you are not familiar with it, you don’t need to worry, we will learn about it as well in this laravel crud example. For this laravel 7 crud example, we are going to create a “customers” table. So, let’s run the following command to create a migration for the “customers” table.

But before running the actual migration command, you need to change the directory to recently created “laravel-crud” directory as:

cd laravel-crud

then run the create migration command.

php artisan make:migration create_customers_table --create=customers

With the above commands, a migration will be created for sure, however, you might be confused what are these each part for? Let’s try to break it down.

php artisan make: migration this is the main migration command
create_customers_table this is as the name of the file, for this, the file name will be current_timestamps_create_customers_table, also the class name would be 
–create=customers this means to create a table with the name customers. If you are altering the table instead of creating a new one, you need to replace the create by the table.

After running the above-mentioned migration command, a new file will be created in the “database/migration” directory. Now, open that file and edit as follows:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCustomersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->strig('address');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customers');
    }
}

Once you edit this file, you need to migrate it so the new table created on the database with the added columns. 

php artisan migrate

While running php artisan migrate for the very first time, you might get an error like “specified key was too long“, if you receive anything like that because of the older version of MySQL or MariaDB, please, check this fix. After, running this command, you can check that either the “customers” table is created or not.

Step 4: Create Controller and Model

Because of laravel, it’s very easy to create the controller as well. You could create the controller as well just by running the command. For this specific purpose, i.e, to create a controller for our laravel crud example, you need to run following commands.

php artisan make:controller CustomerController --resource --model=Models/Customer

It might ask that a “Models/Customer” model does not exist, do you want to generate it? You can just hit “Enter” to create a Controller in “app/Http/Controllers” and a model in “Models/Customer“.

Before moving forward, let’s breakdown the above command.

php artisan make:controllermain make controller command
CustomerControllername of the controller
–resourcewith this parameter, the controller will be created with 7 resource options: index(), create(), store(), show(), edit(), update(), destroy().
–model=Models/Customerit’s another parameter that defines the name of the model. Here, in this laravel crud example, instead of defining “Models/Customer” you can just name “Customer“, however, its good to organize all of your models inside the “Models” directory. That’s why for organizing it nicely, we have created the Models folder.

Now, let’s update the Model in “app/Models/Customer.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
 	/*you can specify table name in this way, if the table name 
 	is in other than the "snake case", plural name of the class*/
    protected $table = 'customers'; 
    //you can ignore this line, if you have primary column as id
    protected $primaryKey = 'id'; 

    protected $guarded = ['id'];
    protected $dates = ['created_at','updated_at'];
}

After adding code to the model, let’s add code to our “CustomerController” located at “app/Http/Controllers/CustomerController” in our laravel crud example app.

app/Http/CustomerController.php

<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $customers = Customer::latest()->paginate(10);
        return view('customers.index',compact('customers'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $customer = new Customer();
        return view('customers.create',compact('customer'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:191',
            'address' => 'required|max:191'
        ]);

        Customer::create([
            'name'      => $request->name,
            'address'   => $request->address
        ]);

        return redirect()->route('customer.index')->with('success','Customer Created Successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function show(Customer $customer)
    {
         return view('customers.show',compact('customer'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function edit(Customer $customer)
    {
        return view('customers.edit',compact('customer'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Customer $customer)
    {
        $request->validate([
            'name' => 'required|max:191',
            'address' => 'required|max:191'
        ]);

        $customer->update([
            'name'=>$request->name,
            'address'=>$request->address,
        ]);
        return redirect()->route('customer.index')->with('success','Customer Updated Successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function destroy(Customer $customer)
    {
        $customer->delete();
        return redirect()->route('customer.index')
                        ->with('success','Customer Deleted Successfully');
    }
}

 

Step 5: Create view blade

Now, its time for creating view blade files. And, to make our view better we will integrate bootstrap on our laravel crud example and also, organize our view files as well. 

So to install bootstrap in our laravel crud example, first, we need to install the “laravel/ui” package.

composer require laravel/ui

After successfully installing the “laravel/ui” package. Let’s install bootstrap in our project.

php artisan ui bootstrap

After generating bootstrap frontend scaffolding, we need to compile SASS to CSS as:

npm install
npm run dev

After compilation, the “app.css” and “app.js” file will be generated inside the “public/css” and “public/js” folder respectively. Now, let’s move to our view files.

Step 5.1: Create Layout

At first, let’s create a layout for our laravel CRUD application. For this, you need to create a file in “resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel CRUD - NoobiTech Laravel 7 CRUD Example</title>

        <!-- CSS -->
        <link href="{{asset('/css/app.css')}}" rel="stylesheet">

    </head>
    <body>
        @yield('content')
        <script src="{{asset('js/app.js')}}"></script>
    </body>
</html>

Step 5.2: Create  partials (for organizing files)

Here, when we say partials it means something that can be shared across multiple files. Instead of writing the same code in multiple files, we are trying to organing it by writing it in a separate file, and including on every file wherever it is required. Although in our case, we have demonstrated only one model i.e, customer, however, in future, if you create some other models then on that case you don’t need to copy and paste that alert element to a different file. All you need to do is include this file.

resources/views/_partials/_messages.blade.php

@if(session('success'))
    <div class="alert alert-success alert-dismissable fade show disappear">
        <strong>Success!</strong>
        {{ session('success') }}
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
    </div>
@endif

@if(session('error'))
    <div class="alert alert-danger alert-dismissable fade show">
        <strong>Error</strong>
        {{ session('error') }}
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
    </div>
@endif

Step 5.3: Create views related to model

Now, let’s create the main view files that are directly linked to the models. Here, we are going to create the index, create, edit, show, and a separate file for the form. Create these files exactly in the following locations.

resources/views/customers/index.blade.php

@extends('layouts.app')

@section('content')

    <div class="container mt-5">
        <div class="card">
            <div class="card-header">
                Laravel CRUD Example - Customer Table
                <a href="{{ route('customer.create') }}" class="float-right btn btn-primary btn-sm">Create</a>
            </div>
            <div class="card-body">

                @include('_partials._messages')

                <div class="row">
                    <div class="col-md-12">
                        <table class="table table-striped no-top-border">
                            <thead>
                            <tr>
                                <th scope="col">Name</th>
                                <th scope="col">Address</th>
                                <th scope="col">Action</th>
                            </tr>
                            </thead>
                            <tbody>
                            @foreach($customers as $k => $v)
                                <tr>
                                    <td>{{ $v->name }}</td>
                                    <td>{{ $v->address }}</td>
                                    <td>
                                        <a href="{{ route('customer.show',$v->id) }}" class="btn btn-sm btn-info text-white mr-2">Show</a>
                                        <a href="{{ route('customer.edit',$v->id) }}" class="btn btn-sm btn-success mr-2">Edit</a>
                                        <form method="POST" action="{{ route('customer.destroy', $v->id) }}" class="form d-inline-block" title="Delete">
                                            @method('delete')
                                            @csrf
                                            <button type="submit" class="btn btn-sm btn-danger" title="{{ __('Delete') }}" onclick="return confirm('Are you sure want to delete?')" >Delete</button>
                                        </form>
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12 laravel-links">
                        {{ $customers->links() }}
                    </div>
                </div>
            </div>
        </div>
    </div>

@endsection

resources/views/customer/create.blade.php

@extends('layouts.app')
@section('content')

    <div class="container mt-5">
        <div class="card">
            <div class="card-header">
                Laravel CRUD Example - Create Customer
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        <form method="POST" action="{{ route('customer.store') }}">
                            @include('customers.form',['buttonText' => 'Save'])
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

@endsection

With the above code, the create view looks as:

laravel 7 crud example - create view screenshot

resources/views/customer/edit.blade.php

@extends('layouts.app')
@section('content')

    <div class="container mt-5">
        <div class="card">
            <div class="card-header">
                Laravel CRUD Example - Edit Customer
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        <form method="POST" action="{{ route('customer.update',$customer->id) }}">
                            {{ method_field('PUT') }}
                            @include('customers.form',['buttonText' => 'Update'])
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

@endsection

resources/views/customer/form.blade.php

@csrf

<div class="form-group row">
    <label for="name" class="col-sm-2 col-form-label required">{{ __('Name') }}</label>
    <div class="col-sm-10">
        <input type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name', $customer->name) }}" required autofocus>

        @error('name')
        <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

<div class="form-group row">
    <label for="value" class="col-sm-2 col-form-label required">{{ __('Address') }}</label>
    <div class="col-sm-10">
        <input type="text" class="form-control @error('address') is-invalid @enderror" name="address" value="{{ old('address', $customer->address) }}" required autofocus>

        @error('address')
        <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>


<div class="hr-line-dashed"></div>

<div class="form-group row">
    <div class="col-sm-4 col-sm-offset-2">
        <a href="{{ route('customer.index') }}" class="btn btn-secondary btn-sm">Cancel</a>
        <button class="btn btn-success btn-sm" type="submit">{{ $buttonText }}</button>
    </div>
</div>

resources/views/customer/show.blade.php

@extends('layouts.app')
@section('content')

<div class="container mt-5">
	<div class="card">
	  <div class="card-header">
	    Laravel CRUD Example - Customer Details
	    <a href="{{ route('customer.index') }}" class="float-right btn btn-dark btn-sm">Back</a>
	  </div>
	  <div class="card-body">
	     <p>
		<strong>Name:</strong> {{ $customer->name }}
	     </p>
             <p>
                <strong>Address:</strong> {{ $customer->address }}
             </p>
	  </div>
	</div>
</div>

@endsection

Step 6: Add Routes

Up to this point, we have already created all the necessary files such as Model, View, and Controller. But still, we have not routed the requests, so that, all the requests could be forwarded to the specific functions of a specific controller. So, to forward all the requests related to the customer model, add the following route to routes/web.php.

Route::resource('customer','CustomerController');

Here, we have added a resource route because our controller possesses every method that is included in a resource controller. Instead of writing a resource route, you could also have added an individual route for individual methods as something like:

Route::get('/customer', 'CustomerController@index');

For more details about the resource controllers, you can check here.  Or, you could also check all the available routes with the command as:

php artisan route:list

laravel CRUD example - route list

Step 7: Add additional codes to Laravel CRUD Example to make it better

Actually, you have already created the laravel CRUD example application. However, it might not have a very good interface and also you might need to navigate to the customer part by entering the URL directly into the browsers. So, we are just trying to add those links and some line of CSS to make it looks nicer.

resources/views/welcome.blade.php (replace the body part)

<body>
    <div class="flex-center position-ref full-height">
        @if (Route::has('login'))
            <div class="top-right links">
                @auth
                    <a href="{{ url('/home') }}">Home</a>
                @else
                    <a href="{{ route('login') }}">Login</a>

                    @if (Route::has('register'))
                        <a href="{{ route('register') }}">Register</a>
                    @endif
                @endauth
            </div>
        @endif

        <div class="content">
            <div class="title m-b-md">
                Laravel CRUD Example - (Laravel 7 )
            </div>

            <div class="links">
                <a href="{{ route('customer.index') }}">Customers</a>
            </div>
        </div>
    </div>
</body>

 

public/css/app.css (add this CSS at the end of the file)

/**added css*/
.laravel-links > nav{
  float: right;
}
.no-top-border th{
  border-top: 0px;
}

Now, you are all set to go. Just hit php artisan serve on the command prompt and visit “http://localhost:8000” on the browser. Then, click on the customers link provided on the landing page or enter “http://localhost:8000/customers” directly into the browser.

This is all for today, however, if you find any difficulties or find it confusing in any steps of our Laravel CRUD example tutorials, feel free to ask any question related to laravel CRUD in the comment section. We are always there to assist you from our side.

LEAVE A REPLY

Please enter your comment!
Please enter your name here