Laravel 5.8 CRUD Tutorial With Example Step By Step

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

Laravel 5.8 CRUD Tutorial With Example Step By Step is explained today.

We will implement create, read, update and delete functionalities of data records using MySQL database.

Laravel is powerful PHP framework which provides healthy built-in features which simplifies the process of interacting with the database.

We will create and update sports players and will also learn how to fetch and delete records from MySQL database using Laravel 5.8.

Watch the following video which is outcome of this Laravel 5.8 CRUD Tutorial.

Step 1. Create Laravel 5.8 Project

Use the below command to create laravel 5.8 project.

composer create-project laravel/laravel=5.8 lara5.8Crud --prefer-dist

Above command will make laravel 5.8 project and name of the project will be lara5.8Crud

Don’t worry if your current version of laravel is lower than 5.8, this command will still create project which uses laravel 5.8 version.

Step 2. Making MySQL Database

Now we need to make a new MySQL database named “crud58players”

I am using sequel pro to manage MySQL database. If you are using phpMyAdmin with XAMPP or WAMP or MAMP then it is all ok. Process is same.

Just create a new database and name it as “crud58players”

Now in your laravel project, open up your .env file.

In this file, you need to change below lines

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

My username is “root” and password is empty. Similarly, update all the information as per your system configurations.

These lines will connect our laravel project with the database.

Step 3. Creating New Table in Database

Time to create new table in our database.

Trigger the below command in terminal

php artisan make:migration create_players_table

Using above command, system will create a new migration file in laravel project.

Browse in app->database->migrations folder. Inside migrations folder, you will find a new file which may have name like timestamp_create_player_table.php file.

Source code for this timestamp_create_player_table.php file is as the below

<?php

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

class CreatePlayersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('players', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('sport');
            $table->string('country');
            $table->timestamps();
        });
    }

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

Look at the up() function. This function includes the name of the various fields (column names) of the players table.

After this, run the following command

php artisan migrate

Above command will make a new table and the name of the table will be “players”

Step 4. Making Model and Controller files

Now we need to create model and controller classes.

Make a new command like below

php artisan make:controller PlayersController -r -m Player

Above command will try to create an controller class named “PlayersController.php” and a model called “Player.php”

But because model class is not there, it will ask you if you want to create model ? say yes.

See the below snippet

➜  lara5.8Crud php artisan make:controller PlayersController -r -m Player


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

Model created successfully.
Controller created successfully.

When you hit “Enter” after writing yes, system will create two files : controller class named “PlayersController.php” and a model called “Player.php”

Now, go to app->Player.php class.

Source code for this file is as the follow

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Player extends Model
{
    //
    public $table = "players";
}

I have added just one line in this model class.

Now go to app->Http->Controllers->PlayersController.php

Source lines for “PlayersController.php is as the below

<?php

namespace App\Http\Controllers;

use App\Player;
use Illuminate\Http\Request;

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

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

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

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

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Player  $player
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        //dd('grttt');
       
        $player = Player::findOrFail($id);
 
        $player->name = request('name');
        $player->sport = request('sport');
        $player->country = request('country');
 
        $player->save();
 
        return redirect('/players');
    }

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

This controller class is like the heart of the tutorial. It contains the functions which will implement CRUD operations.

I will explain these functions in detail later.

Step 5. Defining Routes

Navigate to app->routes->web.php file

Code snippet for this file is as the below

<?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('players','PlayersController');

Last line is defining the routes for all CRUD operations.

To see the routes in detail, trigger the below command

php artisan route:list

You will find the output like below

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

So as you can see that various routes are there with GET or POST requests.

Step 6. Creating Blade View files

Now, we need to code some view files to create look and feel of our project.

Fetching all the records

Let us get all the records from the database.

For this, run your project in browser using below command

php artisan serve

In your browser hit the url like “http://127.0.0.1:8000/players”

This URL will call the index() function from the PlayersController.php file, which is as below

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

First line will fetch all the records from the Players table.

Then system will call the index.blade.php file and will also pass all the fetched records using compact.

We do not have created index.blade.php file till now. So, let’s do that first.

First of all, go to app->resources->views directory. Make a new folder named “players” inside views folder.

Inside players folder, make a new file and give it a name index.blade.php

Write down the below lines in this file

@extends('layout')
 
@section('content')
 
</<!DOCTYPE html>
<html>
<head>
   
</head>
<style>


</style>
<body>
 <br>
<h1 class="title">Players Table</h1>

<form action="/players/create">
    <div class="field">
        <div class="control">
           <button type="submit" class="button is-link" >Create New Player</button>
      </div>
   </div>
</form>

 
@foreach ($players as $player)
<li> 
    <a href="/players/{{ $player->id }}">
 
    {{ $player->name}}  
 
    </a>
 
</li>
@endforeach
 
 
</body>
</html>
 
 
@endsection

Look at the very first line. It is extending the “layouts” file. We have not create this file also.

So inside views folder, make a new file and name it like “layout.blade.php” and add the blow code in it

</<!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>

This file will help us to use latest designs of buttons, text fields etc. UI widgets.

Making a new Player

Now it is time make a new player and insert its details into database.

index.blade.php file have one link like “Create new player“. When the user click on this, compiler will redirect him to a new page.

When user clicks the link, system will call create() method from PlayersController.php file and below is it’s source lines

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

This function will simply call the create.blade.php file.

Inside players folder, create a new file named create.blade.php

Coding lines for create.blade.php is as the below

</<!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 Player</h1>
 
<div class="container">
 
    <form method="POST" action="/players">
 
        {{ csrf_field() }}
 
       <div>
          <label >Player Name</label>
          <input type="text" name="name" placeholder="Player Name" required>
 
      </div>
      <div>
            <label >Player Sport</label>
            <textarea name="sport" placeholder="Player Sport" required></textarea>
 
      </div>
      <div>
            <label >Player Country</label>
            <textarea name="country" placeholder="Player Country" required></textarea>
 
      </div>
      <div>
 
            <input type="submit" value="Make Player">
 
      </div>
 
    </form>  
 
 </div>   
 
</body>
</html>

This page have fields like name, sport , country and a submit button. User can add new player from this page.

When the user clicks on submit button (Make Player) , system will call store() function from PlayersController.php file.

Below is the code for store() function

public function store(Request $request)
    {
        $player = new Player();
 
        $player->name = request('name');
        $player->sport = request('sport');
        $player->country = request('country');
 
        $player->save();
 
        return redirect('/players');
    }

First line will make a new object of Player model.

Then, second line will insert the name given by user into the object.

Similarly, third and fourth lines will insert sport and country in the object.

Fifth line will store the information into the database.

Last line will redirect the user to home page or index.blade.php

Edit and Delete Players Record

Home page makes a list of players name. This names are links.

When the user clicks on any name, system will call the show() function from controller class.

Below are the source lines for show() function

public function show($id)
    {
        $player = Player::findOrFail($id);
        return view('players.show',compact('player')); 
    }

This function will fetch the details of players from the id and then it will call show.blade.php file.

Make a new file (show.blade.php) under resources->views->players directory and below lines in it

@extends('layout')
 
@section('content')

<!DOCTYPE html>
<html>
<head>
<style>
a:link, a:visited {
  background-color: #05ba16;
  color: white;
  padding: 14px 25px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}

a:hover, a:active {
  background-color: red;
}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>
 
<br>

<h1 class="title" > Below is the details of player </h1>

<table>
  <tr>
    <td>Name: {{ $player->name }}</td>
  </tr>

  <tr>
     <td>Sport: {{ $player->sport }}</td>
  </tr>  
  <tr>
     <td>Country: {{ $player->country }}</td>
  </tr> 

 </table> 

<br>
<p>
 
    <a href="/players/{{ $player->id }}/edit"> Edit Player </a>
 
</p>
 
@endsection

Above file will display the information about player.

One button named “Edit Player” is there. When the user clicks it, system will run edit() function from controller class.

Below is the source for edit() function

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

This function will open edit.blade.php file. Create a new file in resources->views->players directory called edit.blade.php

Write the below lines in edit.blade.php

@extends('layout')
 
@section('content')
 
    <h1 class="title"> Edit Players </h1>
 
    <form method="POST" action="/players/{{ $players->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="{{ $players->name }}" required>
        
            </div>
       
        </div>
 
        <div class="field">
 
                <label class="lable" for="sport">Sport </label>
 
                <div class="control">
 
                      <textarea class="textarea" name="sport" required>{{ $players->sport }} </textarea>
 
                </div>
 
        </div>
        <div class="field">
 
             <label class="lable" for="country">Country </label>

            <div class="control">

                 <input type="text" class="input" name="country" placeholder="Title" value="{{ $players->country }}" required>

           </div>

        </div>
 
        <div class="field">
 
            <div class="control">
 
                <button type="submit" class="button is-link">Update Player</button>
 
            </div>
 
        </div>
 
    </form>  
 
    <form method="POST" action="/players/{{ $players->id }}">
 
    @method('DELETE')
    @csrf
 
 
        <div class="field">
 
            <div class="control">
 
                <button type="submit" class="button is-link">Delete Player</button>
 
            </div>
 
        </div>         
 
    </form>
 
 
 @endsection

In this file, user can change the information like name, sport and country.

There are two buttons in this file : UPDATE PLAYER and DELETE PLAYER

When the user clicks UPDATE PLAYER compiler will run update() function from controller.

public function update($id)
    {
        //dd('grttt');
       
        $player = Player::findOrFail($id);
 
        $player->name = request('name');
        $player->sport = request('sport');
        $player->country = request('country');
 
        $player->save();
 
        return redirect('/players');
    }

Above function will update the record in the database and then it will redirect to home page.

When the user clicks the DELETE PLAYER , compiler will run destroy() function.

Following is it’s coding lines

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

It will delete the record using id and then will redirect to the home page.

So, it was all for laravel 5.8 CRUD example.

Download Source Code

Click to download laravel 5.8 CRUD code