Laravel 9 CRUD Example Tutorial for Beginners - TechvBlogs

Laravel 9 CRUD Example Tutorial for Beginners

Today we will be learning how to create a Laravel CRUD (Create, Read, Update, Delete) web application step by step from scratch.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

1 year ago

TechvBlogs - Google News

Throughout this Laravel 9 CRUD operation with an example for beginners tutorial, you will learn step-by-step guide on how to build a simple crud operation app in laravel 9 and how to validate with store & update form data to the database in laravel crud app with bootstrap.

CRUD Meaning: CRUD is an acronym that comes from the world of computer programming and refers to the four functions that are considered necessary to implement a persistent storage application: create, read, update and delete.

This laravel 9 crud operation step-by-step tutorial from scratch will implement a simple post crud operation app in laravel app with validation and image upload. Using this crud app, you can learn how to insert, read, update and delete data from the database in laravel 9 project.

Laravel 9 CRUD Example Tutorial for Beginners

Use the following steps to create a crud operation app in laravel 9 as follows:

  • Step 1 – Download Laravel 9 App
  • Step 2 – Setup Database with App
  • Step 3 – Create Company Model & Migration For CRUD App
  • Step 4 – Create Company Controller By Artisan Command
  • Step 5 – Create Routes
  • Step 6 – Create Blade Views File
    • Make Directory Name Companies
    • index.blade.php
    • create.blade.php
    • edit.blade.php
  • Step 7 – Run Laravel CRUD App on Development Server

Step 1 – Download Laravel 9 App

First of all, download or install laravel 9 new setup. So, open the terminal and type the following command to install the new laravel 9 app into your machine:

composer create-project --prefer-dist laravel/laravel:^9.0 laravel-9-crud

Step 2 – Setup Database with App

Setup database with your downloaded/installed laravel app. So, you need to find the .env file and setup database details as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 – Create Company Model & Migration For CRUD App

Open again your command prompt. And run the following command on it. To create model and migration file for form:

php artisan make:model Company -m

After that, open company migration  file inside laravel-9-crud/database/migrations/ directory. And then update the function up() with the following code:

public function up()
{
    Schema::create('companies', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email');
        $table->string('address');
        $table->timestamps();
    });
}

app/Models/Company.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'email', 'address'];
}

Then, open again command prompt and run the following command to create tables in the database:

php artisan migrate

Read Also: How to set up Free self-hosted Email marketing with Mautic (60k Emails per month!)

Step 4 – Create Company Controller By Artisan Command

Create a controller by using the following command on the command prompt to create a controller file:

php artisan make:controller CompanyController

After that, visit app/Http/controllers and open the CompanyController.php file. And update the following code into it:

<?php

namespace App\Http\Controllers;
use App\Models\Company;
use Illuminate\Http\Request;

class CompanyController extends Controller
{
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
        $companies = Company::orderBy('id','desc')->paginate(5);
        return view('companies.index', compact('companies'));
    }

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

    /**
    * 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',
            'email' => 'required',
            'address' => 'required',
        ]);
        
        Company::create($request->post());

        return redirect()->route('companies.index')->with('success','Company has been created successfully.');
    }

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

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

    /**
    * Update the specified resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \App\company  $company
    * @return \Illuminate\Http\Response
    */
    public function update(Request $request, Company $company)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
            'address' => 'required',
        ]);
        
        $company->fill($request->post())->save();

        return redirect()->route('companies.index')->with('success','Company Has Been updated successfully');
    }

    /**
    * Remove the specified resource from storage.
    *
    * @param  \App\Company  $company
    * @return \Illuminate\Http\Response
    */
    public function destroy(Company $company)
    {
        $company->delete();
        return redirect()->route('companies.index')->with('success','Company has been deleted successfully');
    }
}

Step 5 – Create Routes

Then create routes for laravel crud app. So, open the web.php file from the routes directory of laravel CRUD app. And update the following routes into the web.php file:

use App\Http\Controllers\CompanyController;
 
Route::resource('companies', CompanyController::class);

Step 6 – Create Blade Views File

Create the directory and some blade view, see the following:

  • Make Directory Name Companies
  • index.blade.php
  • create.blade.php
  • edit.blade.php

Create directory name companies inside the resources/views directory.

Note that, create index.blade.php, create.blade.php, and edit.blade.php inside the companies directory. And update the following code into the following files:

index.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 9 CRUD Tutorial Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
</head>
<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Laravel 9 CRUD Example Tutorial</h2>
                </div>
                <div class="pull-right mb-2">
                    <a class="btn btn-success" href="{{ route('companies.create') }}"> Create Company</a>
                </div>
            </div>
        </div>
        @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <p>{{ $message }}</p>
            </div>
        @endif
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>S.No</th>
                    <th>Company Name</th>
                    <th>Company Email</th>
                    <th>Company Address</th>
                    <th width="280px">Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($companies as $company)
                    <tr>
                        <td>{{ $company->id }}</td>
                        <td>{{ $company->name }}</td>
                        <td>{{ $company->email }}</td>
                        <td>{{ $company->address }}</td>
                        <td>
                            <form action="{{ route('companies.destroy',$company->id) }}" method="Post">
                                <a class="btn btn-primary" href="{{ route('companies.edit',$company->id) }}">Edit</a>
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-danger">Delete</button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
            </tbody>
        </table>
        {!! $companies->links() !!}
    </div>
</body>
</html>

create.blade.php:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Add Company Form - Laravel 9 CRUD</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left mb-2">
                    <h2>Add Company</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('companies.index') }}"> Back</a>
                </div>
            </div>
        </div>
        @if(session('status'))
        <div class="alert alert-success mb-1 mt-1">
            {{ session('status') }}
        </div>
        @endif
        <form action="{{ route('companies.store') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Name:</strong>
                        <input type="text" name="name" class="form-control" placeholder="Company Name">
                        @error('name')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Email:</strong>
                        <input type="email" name="email" class="form-control" placeholder="Company Email">
                        @error('email')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Address:</strong>
                        <input type="text" name="address" class="form-control" placeholder="Company Address">
                        @error('address')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <button type="submit" class="btn btn-primary ml-3">Submit</button>
            </div>
        </form>
    </div>
</body>

</html>

edit.blade.php:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Edit Company Form - Laravel 9 CRUD Tutorial</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Edit Company</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('companies.index') }}" enctype="multipart/form-data">
                        Back</a>
                </div>
            </div>
        </div>
        @if(session('status'))
        <div class="alert alert-success mb-1 mt-1">
            {{ session('status') }}
        </div>
        @endif
        <form action="{{ route('companies.update',$company->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Name:</strong>
                        <input type="text" name="name" value="{{ $company->name }}" class="form-control"
                            placeholder="Company name">
                        @error('name')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Email:</strong>
                        <input type="email" name="email" class="form-control" placeholder="Company Email"
                            value="{{ $company->email }}">
                        @error('email')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Address:</strong>
                        <input type="text" name="address" value="{{ $company->address }}" class="form-control"
                            placeholder="Company Address">
                        @error('address')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <button type="submit" class="btn btn-primary ml-3">Submit</button>
            </div>
        </form>
    </div>
</body>

</html>

If you submit the add or edit form blank. So the error message will be displayed with the help of the code given below:

@error('name')
    <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror

Step 7 – Run Development Server

In the last step, open a command prompt and run the following command to start the development server:

php artisan serve

Then open your browser and hit the following URL on it:

http://127.0.0.1:8000/companies

Thank you for reading this blog.

Read Also: How To Install Vue 3 in Laravel 9 From Scratch

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

Comments (26)

Asfa Asfa 4 months ago

Work fine, nice explain step by step

hammad hammad 6 months ago

View [companies.index] not found.

Sheran Harendra Sheran Harendra 7 months ago

Hi this example working fine but i got a problem when creating different one. The error occurred in the place i going to update a record. I face problem when retrieving data and bind them in to the text box no data received. Pls help me out

Prince Prince 7 months ago

great blog

Ibrahim Shuaib Ibrahim Shuaib 9 months ago

works just perfect thanks !

Priya Kannan Priya Kannan 10 months ago

how to passing form data to controller using jquery in laravel 9

YASODHA M YASODHA M 10 months ago

how to view a particular record

YASODHA M YASODHA M 10 months ago

when i create net company got

SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "email" of relation "departments" violates not-null constraint DETAIL: Failing row contains (3, ELectrical, eee, null, 2023-05-09 04:19:41, 2023-05-09 04:19:41).

this error give solition

mukul mukul 1 year ago

this is the best

laravel laravel 1 year ago

error msg --> View [companies.index] not found.

Anoy Anoy 1 year ago

Check if companies is a folder and the phps are in that folder

rajesh rajesh 1 year ago

Target class [CompanyController] does not exist.

Pai Joh Pai Joh 1 year ago

Great intro to Laravel 9. Thanks a lot.

Wanjaya Wanjaya 1 year ago

Missing required parameter for [Route: companies.update] [URI: companies/{company}] [Missing parameter: company].

Claudiu Claudiu 1 year ago

Where is the view file for .show ?

Amar Chand Amar Chand 1 year ago

Class "App\Http\Controllers\Company" not found

Amar Chand Amar Chand 1 year ago

$companies = Company::orderBy('id','desc')->paginate(5); return view('companies.index', compact('companies'));

Antonio Queiroz Antonio Queiroz 1 year ago

The edit part gave the following error: View [companies.edit] not found.

App \ Http \ Controllers \ CompanyController : 39 edit

public function edit(Company $company)

{

    return view('companies.edit',compact('company'));

}
Haider Haider 1 year ago

can we edit image and all input field with request->all()

Mahinder Mahinder 1 year ago

There is an error on /companies/create route upon creating a company, it says "Class App/Http/Controllers/Company" not found. Then CompantContoller's line:39 is referred as error.

Mahinder Mahinder 1 year ago

Sorry I forgot to add models.

Raza Mumtaz Raza Mumtaz 1 year ago

Undefined variable $companies in resources  /  views  /  index.blade .php   : 36

Gabriele Gabriele 1 year ago

I have one question, shouldn't be the model where we handle the database logic?

Instead here it seems we do the database logic in the Controller.

How to change that?

Suresh Ramani Suresh Ramani 1 year ago

You can add that Logic to the Model. You need to define different methods for CRUD.

Artur Artur 1 year ago

Step 5 is bugged. You use comapny instead company...

Suresh Ramani Suresh Ramani 1 year ago

Fixed!

Comment


Note: All Input Fields are required.