Laravel CRUD Example Tutorial From Scratch For Beginners

install laravel, laravel install mysql, laravel get all data records, insert form data into database using laravel, laravel crud example, laravel custom 404, laravel registration and login, laravel 5.7 email verification, laravel 5.8 crud, laravel email verification, laravel facebook login, laravel google login, laravel file upload, laravel image upload, laravel image upload validation, laravel file upload validation, laravel form validation, laravel one to one relationship

Welcome to Laravel  CRUD Example Tutorial From Scratch For Beginners.

We will create a simple application in laravel which will have create, read, update and delete tasks for MySQL database.

We will make a list of super heroes in this laravel crud example.

See the CRUD Operations

First of all, check out the last output of this example in below video.

Step 1. Make a new project and database

First of all, create a new project using the below command

laravel new laraCrud

Above line will make a new project named “laraCrud

I am using sequal pro to handle MySQL database here. You can also use phpMyAdmin also for this.

Now make a new database using sequal pro or phpMyAdmin and name of database should be “superhero

So we have now a “superhero” database. Time to create a new table named “heros

Now in your .env file , you need to add this database name. So edit the below lines

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=superhero
DB_USERNAME=root
DB_PASSWORD=

Hit the below command

php artisan make:migration create_heros_table

Now we should have one new migration file inside database->migrations directory.

This file should have name like 2018_09_create_heros_table.php 

Do not change name of this migration file. Now a source code for this file is as the below

<?php

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

class CreateHerosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('heros', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('work');
            $table->timestamps();
        });
    }

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

Inside up() function, I have added two lines like the following

 $table->string('name');
 $table->text('work');

These lines will create two fields named “name” and “work” in the “heros” table.

Now fire the below command to finally create a heros” table.

php artisan migrate

Step 2. Making a model and Controller

Now we will create model and controller class. First of all, hit the below command

php artisan make:controller HerosController -r -m Hero

Now see that we are telling compiler to make a controller class named “HerosController” and a model named “Hero

We do not have model class right now, so it will ask us if we want to create model or not. say yes for this.

See the below lines to create controller and model successfully.

php artisan make:controller HerosController -r -m Hero

 A App\Hero model does not exist. Do you want to generate it? (yes/no) [yes]:
 > yes

Model created successfully.
Controller created successfully.

Now navigate to app->Hero.php file. It should have the below code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Hero extends Model
{
    //
    public $table = "heros";
}

You need to add a line ”   public $table = “heros”;    ” as per the above lines.

Now go to the app->http->controllers->HerosController.php file

You will see that this file already contains methods like index(), create(), show(), store(), update() etc.

You need to write some lines in these methods. So these lines are as the below

<?php

namespace App\Http\Controllers;

use App\Hero;
use Illuminate\Http\Request;

class HerosController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $heros = Hero::all();
 
        return view('heros.index',compact('heros'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $hero = new Hero();
 
        $hero->name = request('name');
        $hero->work = request('work');
 
        $hero->save();
 
        return redirect('/heros');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Hero  $hero
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $hero = Hero::findOrFail($id);
        return view('heros.show',compact('hero')); 
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Hero  $hero
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $heros = Hero::findOrFail($id);
         return view('heros.edit',compact('heros')); 
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Hero  $hero
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        //dd('grttt');
       
        $hero = Hero::findOrFail($id);

        $hero->name = request('name');
        $hero->work = request('work');

        $hero->save();

        return redirect('/heros');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Hero  $hero
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
       // dd('dele');
       Hero::findOrFail($id)->delete();
       return redirect('/heros');
    }
}

Above is the complete controller class which is able to make operations like create, update, fetch and delete from database.

I will explain this methods later.

Step 3. Making routes

A file called web.php (inside routes folder) has the below code structure.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});


Route::resource('heros','HerosController');

Look at the last line. You might wonder that only one route line??? Yes, because it has defined many routes indirectly.

To see all these routes, hit the below command in your terminal.

php artisan route:list

You should see the below output

+--------+----------+----------+------+---------+--------------+
| Domain | Method   | URI      | Name | Action  | Middleware   |
+--------+----------+----------+------+---------+--------------+
|        | GET|HEAD | /        |      | Closure | web          |
|        | GET|HEAD | api/user |      | Closure | api,auth:api |
+--------+----------+----------+------+---------+--------------+
➜  laraCrud php artisan route:list
+--------+-----------+-------------------+---------------+----------------------------------------------+--------------+
| Domain | Method    | URI               | Name          | Action                                       | Middleware   |
+--------+-----------+-------------------+---------------+----------------------------------------------+--------------+
|        | GET|HEAD  | /                 |               | Closure                                      | web          |
|        | GET|HEAD  | api/user          |               | Closure                                      | api,auth:api |
|        | GET|HEAD  | heros             | heros.index   | App\Http\Controllers\HerosController@index   | web          |
|        | POST      | heros             | heros.store   | App\Http\Controllers\HerosController@store   | web          |
|        | GET|HEAD  | heros/create      | heros.create  | App\Http\Controllers\HerosController@create  | web          |
|        | GET|HEAD  | heros/{hero}      | heros.show    | App\Http\Controllers\HerosController@show    | web          |
|        | PUT|PATCH | heros/{hero}      | heros.update  | App\Http\Controllers\HerosController@update  | web          |
|        | DELETE    | heros/{hero}      | heros.destroy | App\Http\Controllers\HerosController@destroy | web          |
|        | GET|HEAD  | heros/{hero}/edit | heros.edit    | App\Http\Controllers\HerosController@edit    | web          |
+--------+-----------+-------------------+---------------+----------------------------------------------+--------------+

So you can see that we have many routes there.

Now we will create blade files for every route step by step.

Step 4. Making Blade View files

We will start with index file.

Fetching all the heros

Our first task is to get all the names of the super heros from the database.

For this, we need to visit “http://127.0.0.1:8000/heros” in the browser. When you visit this URL, laravel will run the index() function from the controller class.

index() function from the controller class is as the below

 public function index()
    {
        $heros = Hero::all();
 
        return view('heros.index',compact('heros'));
    }

First line will fetch all the records from the table.

Second line will return the index.blade.php file. So we need to create this index.blade.php file file.

But first make a new folder named “heros” inside resources->views directory.

Now inside this heros folder, make a new file named index.blade.php and copy the below source code in it

@extends('layout')

@section('content')

</<!DOCTYPE html>
<html>
<head>
   
</head>
<body>
 
<h1 class="title">All Information About Super Hero</h1>

<p>

    <a href="/heros/create"> Create a new Hero </a>

</p>
 
@foreach ($heros as $hero)
<li> 

    <a href="/heros/{{ $hero->id }}">

        {{ $hero->name}}  

    </a>

</li>
@endforeach
 
 
</body>
</html>


@endsection

See the very first line. It is extending ‘layout’.  It is referring to the layout.blade.php file which we have not created yet.

So go on and make new file (layout.blade.php) in resources->views directory. Code snippet for this file is as the below

</<!DOCTYPE html>
<html>
<head>

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.css">
    

</head>

<body>

    <div class="container">
        @yield('content')
    </div>    

</html>

Creating a new Hero

Index file contains one link, when the user clicks this link, laravel will open a new screen. You will be able to add new hero from this screen.

Behind the seen, when the user hit the link, laravel will run the create() method from controller class.

Code for this create() method is as the below

public function create()
    {
        //dd('1');
        return view('heros.create');
    }

This function is telling the compiler to load create.blade.php file.

So make a new file named create.blade.php inside resources->views->heros directory and write down the below code in it

</<!DOCTYPE html>
<html>
<head>
 
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box;}
 
input[type=text], select, textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}
 
input[type=submit] {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
 
input[type=submit]:hover {
  background-color: #45a049;
}
 
.container {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
}
</style>
   
</head>
<body>
 
<h1>Create New Super Hero</h1>
 
<div class="container">
 
    <form method="POST" action="/heros">
 
        {{ csrf_field() }}
 
       <div>
          <label >Hero Name</label>
          <input type="text" name="name" placeholder="Hero Name" required>
 
      </div>
      <div>
            <label >Hero Work</label>
            <textarea name="work" placeholder="Hero Work" required></textarea>
 
      </div>
      <div>
 
            <input type="submit" value="Make Super Hero">
 
      </div>
 
    </form>  
 
 </div>   
 
</body>
</html>

Above file create one form which has two input fields. User can enter hero’s name and work in it.

When the user hit the “Make Super Hero” button, laravel will add one new hero into the database.

For this, compiler will execute the store() function from controller class.

 public function store(Request $request)
    {
        $hero = new Hero();
 
        $hero->name = request('name');
        $hero->work = request('work');
 
        $hero->save();
 
        return redirect('/heros');
    }

Above snippet will add the new hero into the table.

Edit and Delete Database Records

Now in the index view, you will see all the names of the heroes.

When the user clicks on any hero, compiler will open a new screen. For this it will run the show() function from controller file.

Below is it’s source lines

public function show($id)
    {
        $hero = Hero::findOrFail($id);
        return view('heros.show',compact('hero')); 
    }

This function will open the show.blade.php file. Make a new file (show.blade.php) under resources->views->heros directory and below lines in it

@extends('layout')

@section('content')

<h1 class="title" > Below is the name of super hero </h1>

<h1 class="title" > {{ $hero->name }} </h1>

<h1 class="title" > {{ $hero->work }} </h1>

<p>

    <a href="/heros/{{ $hero->id }}/edit"> Edit Hero </a>

</p>

@endsection

This code will print the name and work of the heroes first.

Below them, there is a link like “Edit Hero

Click on this link will open up a new page. It will run the edit() function from controller.

 public function edit($id)
    {
        //
        $heros = Hero::findOrFail($id);
         return view('heros.edit',compact('heros')); 
    }

Above function will open edit.blade.php file. Make a new file (edit.blade.php) under resources->views->heros directory and below lines in it

@extends('layout')

@section('content')

    <h1 class="title"> Edit Heros </h1>

    <form method="POST" action="/heros/{{ $heros->id }}">

    @method('PATCH')
    @csrf


        <div class="field">

            <label class="lable" for="name">Name </label>

            <div class="control">

                <input type="text" class="input" name="name" placeholder="Title" value="{{ $heros->name }}" required>
        
            </div>
       
        </div>

        <div class="field">

                <label class="lable" for="work">Work </label>

                <div class="control">

                      <textarea class="textarea" name="work" required>{{ $heros->work }} </textarea>

                </div>

        </div>

        <div class="field">

            <div class="control">

                <button type="submit" class="button is-link">Update Hero</button>

            </div>

        </div>

    </form>  

    <form method="POST" action="/heros/{{ $heros->id }}">

    @method('DELETE')
    @csrf


        <div class="field">

            <div class="control">

                <button type="submit" class="button is-link">Delete Hero</button>

            </div>

        </div>         

    </form>


 @endsection

This page will have two fields. User can change or edit hero information from here.

There are two buttons : Update Hero and Delete Hero

When the user clicks the Update Hero button, compiler will run the update() function which have below source code

 public function update($id)
    {
        //dd('grttt');
       
        $hero = Hero::findOrFail($id);

        $hero->name = request('name');
        $hero->work = request('work');

        $hero->save();

        return redirect('/heros');
    }

It will simply update the name and work of the hero.

When the user clicks the Delete Hero button, compiler will run destroy() function which have below code lines

public function destroy($id)
    {
       // dd('dele');
       Hero::findOrFail($id)->delete();
       return redirect('/heros');
    }

Above will delete the hero from the database.