Friday, November 29, 2019

Laravel 5.7 CRUD (Create Read Update Delete) Tutorial Example

In this Laravel 5.7 tutorial, I will let you know how to create basic CRUD functionality.
Laravel 5.7 has some other enhancement with awesome features.
In this example, You will get step by step guide that will help you to build a CRUD application easily.
This example will have following functionality :
  • How to install Laravel 5.7 application
  • How to configure MySQL database
  • How to work on migration file to create tables
  • How to use resource route
  • How to create Controller and Model
  • How to create Blade file
Step 1 : Install Laravel 5.7
In this first step, I will install the fresh Laravel 5.7 application by running following command :
composer create-project --prefer-dist laravel/laravel blog
Step 2 : Configure MySQl Database
In this step, I will create a database first in MySQL and connect database with Laravel application.
We will use environment variables for database credential. So let's open .env file :
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbName
DB_USERNAME=dbUsername
DB_PASSWORD=dbPassword
Step 3: Create migration file to generate table
In this step, I will create a migration file for "members" table so that we can work with CRUD functionality in Laravel 5.7
command:
php artisan make:migration create_members_table --create=members
It will create a migration file in "database/migrations" directory.
Now I will update the below schema inside the file timestamp_create_members_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMembersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('members', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('members');
    }
}
Now I will run the migration command to create table :
php artisan migrate
Step 4: Create model using artisan command
In this step, I will create Member model by running artisan command:
php artisan make:model Member
Now I will open the app/Member.php file that is generated by above command and specify the fillable attribute for mass assignment.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
    protected $fillable = [
        'name', 'email'
    ];
}
Step 5 : Add route
In this step, I will add resource route to display member list, view member details, display add member form, store member information, display edit member form, update member information and delete member information.
routes/web.php
Route::resource('members','MemberController');
Step 6: Create Controller
In this step, I will create a new resource controller by running artisan command :
php artisan make:controller MemberController --resource
Okay, now open MemberController.php file from the directory app/Http/Controllers/.
This MemberController has seven following methods to handle CRUD operation.
  1. index() - will list member data from the database.
  2. create() - will display the add member form.
  3. store() - will insert the member information into the members table.
  4. show() - will display the member information.
  5. edit() - will display the edit member form.
  6. update() - will update the member information.
  7. destroy() - will delete the member data from the database.
app/Http/Controllers/MemberController.php
<?php
  
namespace App\Http\Controllers;
  
use App\Member;
use Illuminate\Http\Request;
  
class MemberController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $members = Member::latest()->paginate(5);
  
        return view('members.index',compact('members'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }
   
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('members.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',
            'detail' => 'required',
        ]);
  
        Member::create($request->all());
   
        return redirect()->route('members.index')
                        ->with('success','Member created successfully.');
    }
   
    /**
     * Display the specified resource.
     *
     * @param  \App\Member  $member
     * @return \Illuminate\Http\Response
     */
    public function show(Member $member)
    {
        return view('members.show',compact('member'));
    }
   
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Member  $member
     * @return \Illuminate\Http\Response
     */
    public function edit(Member $member)
    {
        return view('members.edit',compact('member'));
    }
  
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Member  $member
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Member $member)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
  
        $member->update($request->all());
  
        return redirect()->route('members.index')
                        ->with('success','Member updated successfully');
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Member  $member
     * @return \Illuminate\Http\Response
     */
    public function destroy(Member $member)
    {
        $member->delete();
  
        return redirect()->route('members.index')
                        ->with('success','Member deleted successfully');
    }
}
Step 7: Create Blade Files
In this step, I will create master template and some blade file related to member management.
  1. layout.blade.php
  2. index.blade.php
  3. create.blade.php
  4. edit.blade.php
  5. show.blade.php
Okay, now I will create master template inside the views folder.
resources/views/layout.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Build CRUD Application in Laravel 5.7 - ExpertPHP.in </title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
  
<div class="container">
    @yield('content')
</div>
   
</body>
</html>
Now create members folder inside resources >> views and create all files inside that members folder.
resources/views/members/index.blade.php
@extends('layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Members CRUD</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('members.create') }}"> Create New Member</a>
            </div>
        </div>
    </div>
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Email</th>
            <th width="280px">Operation</th>
        </tr>
    @foreach ($members as $member)
    <tr>
        <td>{{ ++$i }}</td>
        <td>{{ $member->name}}</td>
        <td>{{ $member->email}}</td>
        <td>
            <a class="btn btn-info" href="{{ route('members.show',$member->id) }}">Show</a>
            <a class="btn btn-primary" href="{{ route('members.edit',$member->id) }}">Edit</a>
            {!! Form::open(['method' => 'DELETE','route' => ['members.destroy', $member->id],'style'=>'display:inline']) !!}
            {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
            {!! Form::close() !!}
        </td>
    </tr>
    @endforeach
    </table>
    {!! $members->render() !!}
@endsection
resources/views/members/form.blade.php
I will create a common form that will use in create and edit module.
<div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12">
        <div class="form-group">
            <strong>Name:</strong>
            {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
        </div>
    </div>
    <div class="col-xs-12 col-sm-12 col-md-12">
        <div class="form-group">
            <strong>Email:</strong>
            {!! Form::email('email', null, array('placeholder' => 'Email','class' => 'form-control')) !!}
        </div>
    </div>
    <div class="col-xs-12 col-sm-12 col-md-12 text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</div>
resources/views/members/create.blade.php
@extends('layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Add New Member</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('members.index') }}"> Back</a>
            </div>
        </div>
    </div>
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    {!! Form::open(array('route' => 'members.store','method'=>'POST')) !!}
         @include('members.form')
    {!! Form::close() !!}
@endsection
resources/views/members/edit.blade.php
@extends('layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit Member</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('members.index') }}"> Back</a>
            </div>
        </div>
    </div>
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    {!! Form::model($member, ['method' => 'PATCH','route' => ['members.update', $member->id]]) !!}
        @include('members.form')
    {!! Form::close() !!}
@endsection
resources/views/members/show.blade.php
@extends('layout')

@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Member</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('members.index') }}"> Back</a>
            </div>
        </div>
    </div>
   
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $member->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Email:</strong>
                {{ $member->email }}
            </div>
        </div>
    </div>
@endsection
Load disqus comments

0 comments