Laravel 5.5 CRUD (Create Read Update Delete) Example from scratch

Laravel 5.5 CRUD (Create Read Update Delete) Example from scratch

In this post we will give you information about Laravel 5.5 CRUD (Create Read Update Delete) Example from scratch. Hear we will give you detail about Laravel 5.5 CRUD (Create Read Update Delete) Example from scratchAnd how to use it also give you demo for it if it is necessary.

In this Laravel tutorial, You will learn the basic CRUD (Create Read Update Delete) functionality in Laravel 5.5.

Laravel is open-source web application framework with easy documentation.

If you are thinking to build an web application from scratch in Laravel then this example will help you out.

This example is basically designed for the beginners.

In this example, you will learn how to insert form data into a database, how can you modify the existing data, in short, you will learn the complete CRUD operation with the database.


Laravel 5.5 Installation

First, I need fresh Laravel 5.5 application to start from scratch.

Run the following command to install the upgraded version of Laravel :

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

With fresh Laravel 5.5 application, You will need to require Laravel Collective package for form builder : Laravel Collective.


Database Connection

To perform CRUD operation, You need to configure the MySQL database.

Once you have installed Laravel application then you should have .env file in the root directory which contains the various settings. So we will put database credentials in the .env file.


.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=xxxx


Create Member Table, Model and Controller

We will work on member table to perform all CRUD operation.

Run following command to have migration file for member table.

php artisan make:migration create_members_table

After this artisan command, You must have new migration file like “2017_09_06_071236_create_members_table.php” in following path database/migrations.

  1. <?php
  2. use IlluminateSupportFacadesSchema;
  3. use IlluminateDatabaseSchemaBlueprint;
  4. use IlluminateDatabaseMigrationsMigration;
  5. class CreateMembersTable extends Migration
  6. {
  7. /**
  8. * Run the migrations.
  9. *
  10. * @return void
  11. */
  12. public functionup()
  13. {
  14. Schema::create('members',function(Blueprint $table){
  15. $table->increments('id');
  16. $table->string('name');
  17. $table->string('email');
  18. $table->timestamps();
  19. });
  20. }
  21. /**
  22. * Reverse the migrations.
  23. *
  24. * @return void
  25. */
  26. public functiondown()
  27. {
  28. Schema::dropIfExists('members');
  29. }
  30. }
<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

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');
    }
}

Save the migration file with above code and run following command :

php artisan migrate

Now you have members table with id, name, email and timestamps fields.

Ok let’s create the model and controller in single command :

php artisan make:model Member -c

After above command, you will get the Member model and MemberController.



app/Member.php

  1. <?php
  2. namespace App;
  3. use IlluminateDatabaseEloquentModel;
  4. class Member extends Model
  5. {
  6. protected $fillable=[
  7. 'name','email'
  8. ];
  9. }
<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Member extends Model
{
    protected $fillable = [
        'name', 'email'
    ];
}


Resource Route

Laravel provides single resource route instead of creating different different routes for each operation.


routes/web.php

Route::resource('members','MemberController');


MemberController

You will notice that there will be some default method available with Member Controller after running artisan command.


app/Http/Controllers/MemberController.php

Put following code in Member Controller.

  1. <?php
  2. namespace AppHttpControllers;
  3. use IlluminateHttpRequest;
  4. use AppMember;
  5. class MemberController extends Controller
  6. {
  7. public functionindex()
  8. {
  9. $members= Member::latest()->paginate(10);
  10. returnview('members.index',compact('members'))
  11. ->with('i',(request()->input('page',1)-1)*5);
  12. }
  13. /**
  14. * Show the form for creating a new resource.
  15. *
  16. * @return IlluminateHttpResponse
  17. */
  18. public functioncreate()
  19. {
  20. returnview('members.create');
  21. }
  22. /**
  23. * Store a newly created resource in storage.
  24. *
  25. * @param IlluminateHttpRequest $request
  26. * @return IlluminateHttpResponse
  27. */
  28. public functionstore(Request $request)
  29. {
  30. request()->validate([
  31. 'name'=>'required',
  32. 'email'=>'required',
  33. ]);
  34. Member::create($request->all());
  35. returnredirect()->route('members.index')
  36. ->with('success','Member created successfully');
  37. }
  38. /**
  39. * Display the specified resource.
  40. *
  41. * @param int $id
  42. * @return IlluminateHttpResponse
  43. */
  44. public functionshow(Member $member)
  45. {
  46. returnview('members.show',compact('member'));
  47. }
  48. /**
  49. * Show the form for editing the specified resource.
  50. *
  51. * @param int $id
  52. * @return IlluminateHttpResponse
  53. */
  54. public functionedit(Member $member)
  55. {
  56. returnview('members.edit',compact('member'));
  57. }
  58. /**
  59. * Update the specified resource in storage.
  60. *
  61. * @param IlluminateHttpRequest $request
  62. * @param int $id
  63. * @return IlluminateHttpResponse
  64. */
  65. public functionupdate(Request $request,Member $member)
  66. {
  67. request()->validate([
  68. 'name'=>'required',
  69. 'email'=>'required',
  70. ]);
  71. $member->update($request->all());
  72. returnredirect()->route('members.index')
  73. ->with('success','Member updated successfully');
  74. }
  75. /**
  76. * Remove the specified resource from storage.
  77. *
  78. * @param int $id
  79. * @return IlluminateHttpResponse
  80. */
  81. public functiondestroy($id)
  82. {
  83. Member::destroy($id);
  84. returnredirect()->route('members.index')
  85. ->with('success','Member deleted successfully');
  86. }
  87. }
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppMember;

class MemberController extends Controller
{
    public function index()
    {
        $members = Member::latest()->paginate(10);
        return view('members.index',compact('members'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        return view('members.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        request()->validate([
            'name' => 'required',
            'email' => 'required',
        ]);
        Member::create($request->all());
        return redirect()->route('members.index')
                        ->with('success','Member created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show(Member $member)
    {
        return view('members.show',compact('member'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function edit(Member $member)
    {
        return view('members.edit',compact('member'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request,Member $member)
    {
        request()->validate([
            'name' => 'required',
            'email' => 'required',
        ]);
        $member->update($request->all());
        return redirect()->route('members.index')
                        ->with('success','Member updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        Member::destroy($id);
        return redirect()->route('members.index')
                        ->with('success','Member deleted successfully');
    }
}


Blade View Files

In this step, I will create some view files to add members, list members, edit members with master layouts.

  • default.blade.php
  • index.blade.php
  • form.blade.php
  • create.blade.php
  • edit.blade.php
  • show.blade.php

resources/views/layouts/default.blade.php

  1. <!DOCTYPEhtml>
  2. <htmllang="en">
  3. <head>
  4. <metacharset="utf-8">
  5. <metahttp-equiv="X-UA-Compatible"content="IE=edge">
  6. <metaname="viewport"content="width=device-width, initial-scale=1">
  7. <title>Laravel 5.5 CRUD example</title>
  8. <linkhref="{{asset('css/app.css')}}"rel="stylesheet">
  9. </head>
  10. <body>
  11. <divclass="container">
  12. @yield('content')
  13. </div>
  14. </body>
  15. </html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 5.5 CRUD example</title>
    <link href="{{asset('css/app.css')}}" rel="stylesheet">
</head>
<body>
 
<div >
    @yield('content')
</div>
 
</body>
</html>


resources/views/members/index.blade.php

  1. @extends('layouts.default')
  2. @section('content')
  3. <divclass="row">
  4. <divclass="col-lg-12 margin-tb">
  5. <divclass="pull-left">
  6. <h2>Members CRUD</h2>
  7. </div>
  8. <divclass="pull-right">
  9. <aclass="btn btn-success"href="{{ route('members.create') }}"> Create New Member</a>
  10. </div>
  11. </div>
  12. </div>
  13. @if ($message = Session::get('success'))
  14. <divclass="alert alert-success">
  15. <p>{{ $message }}</p>
  16. </div>
  17. @endif
  18. <tableclass="table table-bordered">
  19. <tr>
  20. <th>No</th>
  21. <th>Name</th>
  22. <th>Email</th>
  23. <thwidth="280px">Operation</th>
  24. </tr>
  25. @foreach ($members as $member)
  26. <tr>
  27. <td>{{ ++$i }}</td>
  28. <td>{{ $member->name}}</td>
  29. <td>{{ $member->email}}</td>
  30. <td>
  31. <aclass="btn btn-info"href="{{ route('members.show',$member->id) }}">Show</a>
  32. <aclass="btn btn-primary"href="{{ route('members.edit',$member->id) }}">Edit</a>
  33. {!! Form::open(['method' => 'DELETE','route' => ['members.destroy', $member->id],'style'=>'display:inline']) !!}
  34. {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
  35. {!! Form::close() !!}
  36. </td>
  37. </tr>
  38. @endforeach
  39. </table>
  40. {!! $members->render() !!}
  41. @endsection
@extends('layouts.default')
@section('content')
    <div >
        <div >
            <div >
                <h2>Members CRUD</h2>
            </div>
            <div >
                <a  href="{{ route('members.create') }}"> Create New Member</a>
            </div>
        </div>
    </div>
    @if ($message = Session::get('success'))
        <div >
            <p>{{ $message }}</p>
        </div>
    @endif
    <table >
        <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  href="{{ route('members.show',$member->id) }}">Show</a>
            <a  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/show.blade.php

  1. @extends('layouts.default')
  2. @section('content')
  3. <divclass="row">
  4. <divclass="col-lg-12 margin-tb">
  5. <divclass="pull-left">
  6. <h2> Show Member</h2>
  7. </div>
  8. <divclass="pull-right">
  9. <aclass="btn btn-primary"href="{{ route('members.index') }}"> Back</a>
  10. </div>
  11. </div>
  12. </div>
  13. <divclass="row">
  14. <divclass="col-xs-12 col-sm-12 col-md-12">
  15. <divclass="form-group">
  16. <strong>Name:</strong>
  17. {{ $member->name}}
  18. </div>
  19. </div>
  20. <divclass="col-xs-12 col-sm-12 col-md-12">
  21. <divclass="form-group">
  22. <strong>Email:</strong>
  23. {{ $member->email}}
  24. </div>
  25. </div>
  26. </div>
  27. @endsection
@extends('layouts.default')
 
@section('content')
    <div >
        <div >
            <div >
                <h2> Show Member</h2>
            </div>
            <div >
                <a  href="{{ route('members.index') }}"> Back</a>
            </div>
        </div>
    </div>
    <div >
        <div >
            <div >
                <strong>Name:</strong>
                {{ $member->name}}
            </div>
        </div>
        <div >
            <div >
                <strong>Email:</strong>
                {{ $member->email}}
            </div>
        </div>
    </div>
@endsection


resources/views/members/form.blade.php

  1. <divclass="row">
  2. <divclass="col-xs-12 col-sm-12 col-md-12">
  3. <divclass="form-group">
  4. <strong>Name:</strong>
  5. {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
  6. </div>
  7. </div>
  8. <divclass="col-xs-12 col-sm-12 col-md-12">
  9. <divclass="form-group">
  10. <strong>Email:</strong>
  11. {!! Form::email('email', null, array('placeholder' => 'Email','class' => 'form-control')) !!}
  12. </div>
  13. </div>
  14. <divclass="col-xs-12 col-sm-12 col-md-12 text-center">
  15. <buttontype="submit"class="btn btn-primary">Submit</button>
  16. </div>
  17. </div>
<div >
    <div >
        <div >
            <strong>Name:</strong>
            {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
        </div>
    </div>
    <div >
        <div >
            <strong>Email:</strong>
            {!! Form::email('email', null, array('placeholder' => 'Email','class' => 'form-control')) !!}
        </div>
    </div>
    <div >
            <button type="submit" >Submit</button>
    </div>
</div>


resources/views/members/create.blade.php

  1. @extends('layouts.default')
  2. @section('content')
  3. <divclass="row">
  4. <divclass="col-lg-12 margin-tb">
  5. <divclass="pull-left">
  6. <h2>Add New Member</h2>
  7. </div>
  8. <divclass="pull-right">
  9. <aclass="btn btn-primary"href="{{ route('members.index') }}"> Back</a>
  10. </div>
  11. </div>
  12. </div>
  13. @if (count($errors) > 0)
  14. <divclass="alert alert-danger">
  15. <strong>Whoops!</strong> There were some problems with your input.<br><br>
  16. <ul>
  17. @foreach ($errors->all() as $error)
  18. <li>{{ $error }}</li>
  19. @endforeach
  20. </ul>
  21. </div>
  22. @endif
  23. {!! Form::open(array('route' => 'members.store','method'=>'POST')) !!}
  24. @include('members.form')
  25. {!! Form::close() !!}
  26. @endsection
@extends('layouts.default')
@section('content')
    <div >
        <div >
            <div >
                <h2>Add New Member</h2>
            </div>
            <div >
                <a  href="{{ route('members.index') }}"> Back</a>
            </div>
        </div>
    </div>
    @if (count($errors) > 0)
        <div >
            <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

  1. @extends('layouts.default')
  2. @section('content')
  3. <divclass="row">
  4. <divclass="col-lg-12 margin-tb">
  5. <divclass="pull-left">
  6. <h2>Edit Member</h2>
  7. </div>
  8. <divclass="pull-right">
  9. <aclass="btn btn-primary"href="{{ route('members.index') }}"> Back</a>
  10. </div>
  11. </div>
  12. </div>
  13. @if (count($errors) > 0)
  14. <divclass="alert alert-danger">
  15. <strong>Whoops!</strong> There were some problems with your input.<br><br>
  16. <ul>
  17. @foreach ($errors->all() as $error)
  18. <li>{{ $error }}</li>
  19. @endforeach
  20. </ul>
  21. </div>
  22. @endif
  23. {!! Form::model($member, ['method' => 'PATCH','route' => ['members.update', $member->id]]) !!}
  24. @include('members.form')
  25. {!! Form::close() !!}
  26. @endsection
@extends('layouts.default')
 
@section('content')
    <div >
        <div >
            <div >
                <h2>Edit Member</h2>
            </div>
            <div >
                <a  href="{{ route('members.index') }}"> Back</a>
            </div>
        </div>
    </div>
    @if (count($errors) > 0)
        <div >
            <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

Now you can perform the crud application after following above steps.

  • Laravel 5.2 CRUD (Create Read Update Delete) Example
  • Laravel 5 Ajax CRUD example



Show Demo
Source Code

Hope this code and post will helped you for implement Laravel 5.5 CRUD (Create Read Update Delete) Example from scratch. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

5  +  5  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US