Laravel: Simple CRUD Operation

Getting Started

First, we're going to create a new project and I'm gonna name it crud and add it to localhost with the name crud.dev. If you have no idea on how to do this, please refer to my tutorial Installing Laravel - PHP Framework.

Installing Laravel Collective

Next, we're gonna install Laravel Collective to handle our forms. You may visit the official website if you wanted to read the documentations using this link. 1. Open command prompt, navigate to our newly created project and type: composer require "laravelcollective/html":"^5.5.0" Note: Change the value of 5.5.0 depending on the laravel version that you are using. 2. After finishing the installation, open app.php located in config folder. Find 'providers' array and add the ff:
  1. Collective\Html\HtmlServiceProvider::class,
Find 'aliases' array and add the ff:
  1. 'Form' => Collective\Html\FormFacade::class,
  2. 'Html' => Collective\Html\HtmlFacade::class,

Setting up our Database

1. Open your phpMyAdmin and create a new database. In my case, I've created a database named crud. 2. In our project, open .env file and update the ff lines depending on your setting.
  1. DB_DATABASE=crud
  2. DB_USERNAME=root
  3. DB_PASSWORD=

Creating our Controller and Model

Next, we're going to create our controller and model to handle our table. 1. In command prompt, navigate to your project and type: php artisan make:controller MemberController This will create our controller in the form of MemberController.php located in app/Http/Controllers folder. 2. Open MemberController.php and edit it with the ff codes:
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6. use App\Member;
  7.  
  8. class MemberController extends Controller
  9. {
  10. public function index(){
  11. return view('show');
  12. }
  13.  
  14. public function getMembers(){
  15. $members = Member::all();
  16.  
  17. return view('show')->with('members', $members);
  18. }
  19.  
  20. public function save(Request $request){
  21. $member = new Member;
  22. $member->firstname = $request->input('firstname');
  23. $member->lastname = $request->input('lastname');
  24. $member->save();
  25.  
  26. return redirect('/');
  27. }
  28.  
  29. public function update(Request $request, $id){
  30. $member = Member::find($id);
  31. $input = $request->all();
  32. $member->fill($input)->save();
  33.  
  34. return redirect('/');
  35. }
  36.  
  37. public function delete($id)
  38. {
  39. $members = Member::find($id);
  40. $members->delete();
  41.  
  42. return redirect('/');
  43. }
  44. }
3. In command prompt, navigate to our project and type: php artisan make:model Member -m This will create our model Member.php located in app folder. It will also create the migration for us due to the -m that we added in creating the model in the form of, in my case 2017_11_11_074141_create_members_table.php file located in database/migrations folder. 4. Open Member.php and edit it with the ff codes:
  1. <?php
  2.  
  3. namespace App;
  4.  
  5. use Illuminate\Database\Eloquent\Model;
  6.  
  7. class Member extends Model
  8. {
  9. protected $fillable = ['firstname', 'lastname'];
  10. }
5. Open 2017_11_11_074141_create_members_table.php and edit it with ff codes:
  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreateMembersTable extends Migration
  8. {
  9. /**
  10.   * Run the migrations.
  11.   *
  12.   * @return void
  13.   */
  14. public function up()
  15. {
  16. Schema::create('members', function (Blueprint $table) {
  17. $table->increments('id');
  18. $table->string('firstname');
  19. $table->string('lastname');
  20. $table->timestamps();
  21. });
  22. }
  23.  
  24. /**
  25.   * Reverse the migrations.
  26.   *
  27.   * @return void
  28.   */
  29. public function down()
  30. {
  31. Schema::dropIfExists('members');
  32. }
  33. }
6. In command prompt, navigate to your project and type: php artisan migrate It will then create our database migration. If you have an error like this: [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t oo long; max key length is 767 bytes (SQL: alter table `users` add unique ` users_email_unique`(`email`)) You can solve this by opening AppServiceProvider.php located in app/Providers folder. Add this line: use Illuminate\Support\Facades\Schema; In boot add this line: Schema::defaultStringLength(191); migrate error Run php artisan migrate again and make sure that your database is empty because it will have another error if its not.

Creating our Routes

In routes folder, open web.php and edit it with the ff codes:
  1. <?php
  2.  
  3. Route::get('/', 'MemberController@index');
  4.  
  5. Route::get('/', 'MemberController@getMembers');
  6.  
  7. Route::post('/save', 'MemberController@save');
  8.  
  9. Route::patch('/update/{id}', ['as' => 'member.update', 'uses' => 'MemberController@update']);
  10.  
  11. Route::delete('/delete/{id}', ['as' => 'member.delete', 'uses' => 'MemberController@delete']);

Creating our Views

In resources/views folder, create the ff files: app.blade.php
  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <title>Laravel Crud Operation</title>
  4. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  5. <link rel="stylesheet" href="/css/app.css">
  6. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  7. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  8. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  9. </head>
  10. <div class="container">
  11. @yield('content')
  12. </div>
  13. @include('modal')
  14.  
  15. </body>
  16. </html>
show.blade.php
  1. @extends('app')
  2.  
  3. @section('content')
  4. <h1 class="page-header text-center">Laravel Crud Operation</h1>
  5. <div class="row">
  6. <div class="col-md-10 col-md-offset-1">
  7. <h2>Members Table
  8. <button type="button" data-target="#addnew" data-toggle="modal" class="btn btn-primary pull-right"><i class="fa fa-plus"></i> Member</button>
  9. </h2>
  10. </div>
  11. </div>
  12. <div class="row">
  13. <div class="col-md-10 col-md-offset-1">
  14. <table class="table table-bordered table-responsive table-striped">
  15. <th>Fisrtname</th>
  16. <th>Lastname</th>
  17. <th>Action</th>
  18. </thead>
  19. @foreach($members as $member)
  20. <tr>
  21. <td>{{$member->firstname}}</td>
  22. <td>{{$member->lastname}}</td>
  23. <td><a href="#edit{{$member->id}}" data-toggle="modal" class="btn btn-success"><i class='fa fa-edit'></i> Edit</a> <a href="#delete{{$member->id}}" data-toggle="modal" class="btn btn-danger"><i class='fa fa-trash'></i> Delete</a>
  24. @include('action')
  25. </td>
  26. </tr>
  27. @endforeach
  28. </tbody>
  29. </table>
  30. </div>
  31. </div>
  32. @endsection
modal.blade.php
  1. <!-- Add Modal -->
  2. <div class="modal fade" id="addnew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  3. <div class="modal-dialog" role="document">
  4. <div class="modal-content">
  5. <div class="modal-header">
  6. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  7. <h4 class="modal-title text-center" id="myModalLabel">Add New Member</h4>
  8. </div>
  9. <div class="modal-body">
  10. {!! Form::open(['url' => 'save']) !!}
  11. <div class="form-group">
  12. <div class="row">
  13. <div class="col-md-2" style="margin-top:7px;">
  14. {!! Form::label('firstname', 'Firstname') !!}
  15. </div>
  16. <div class="col-md-10">
  17. {!! Form::text('firstname', '', ['class' => 'form-control', 'placeholder' => 'Input Firstname', 'required']) !!}
  18. </div>
  19. </div>
  20. </div>
  21. <div class="form-group">
  22. <div class="row">
  23. <div class="col-md-2" style="margin-top:7px;">
  24. {!! Form::label('lastname', 'Lastname') !!}
  25. </div>
  26. <div class="col-md-10">
  27. {!! Form::text('lastname', '', ['class' => 'form-control', 'placeholder' => 'Input Lastname', 'required']) !!}
  28. </div>
  29. </div>
  30. </div>
  31. </div>
  32. <div class="modal-footer">
  33. <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
  34. <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save</button>
  35. {!! Form::close() !!}
  36. </div>
  37. </div>
  38. </div>
  39. </div>
action.blade.php
  1. <!-- Edit Modal -->
  2. <div class="modal fade" id="edit{{$member->id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  3. <div class="modal-dialog" role="document">
  4. <div class="modal-content">
  5. <div class="modal-header">
  6. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  7. <h4 class="modal-title text-center" id="myModalLabel">Edit Member</h4>
  8. </div>
  9. <div class="modal-body">
  10. {!! Form::model($members, [ 'method' => 'patch','route' => ['member.update', $member->id] ]) !!}
  11. <div class="form-group">
  12. <div class="row">
  13. <div class="col-md-2" style="margin-top:7px;">
  14. {!! Form::label('firstname', 'Firstname') !!}
  15. </div>
  16. <div class="col-md-10">
  17. {!! Form::text('firstname', $member->firstname, ['class' => 'form-control']) !!}
  18. </div>
  19. </div>
  20. </div>
  21. <div class="form-group">
  22. <div class="row">
  23. <div class="col-md-2" style="margin-top:7px;">
  24. {!! Form::label('lastname', 'Lastname') !!}
  25. </div>
  26. <div class="col-md-10">
  27. {!! Form::text('lastname', $member->lastname, ['class' => 'form-control']) !!}
  28. </div>
  29. </div>
  30. </div>
  31. </div>
  32. <div class="modal-footer">
  33. <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
  34. {{Form::button('<i class="fa fa-check-square-o"></i> Update', ['class' => 'btn btn-success', 'type' => 'submit'])}}
  35. {!! Form::close() !!}
  36. </div>
  37. </div>
  38. </div>
  39. </div>
  40.  
  41. <!-- Delete Modal -->
  42. <div class="modal fade" id="delete{{$member->id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  43. <div class="modal-dialog" role="document">
  44. <div class="modal-content">
  45. <div class="modal-header">
  46. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  47. <h4 class="modal-title text-center" id="myModalLabel">Delete Member</h4>
  48. </div>
  49. <div class="modal-body">
  50. {!! Form::model($members, [ 'method' => 'delete','route' => ['member.delete', $member->id] ]) !!}
  51. <h4 class="text-center">Are you sure you want to delete Member?</h4>
  52. <h5 class="text-center">Name: {{$member->firstname}} {{$member->lastname}}</h5>
  53. </div>
  54. <div class="modal-footer">
  55. <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
  56. {{Form::button('<i class="fa fa-trash"></i> Delete', ['class' => 'btn btn-danger', 'type' => 'submit'])}}
  57. {!! Form::close() !!}
  58. </div>
  59. </div>
  60. </div>
  61. </div>

Running our Project

In your web browser, type the name that you added in localhost for your project in my case, crud.dev. You should now be able to CRUD. That ends this tutorial. Happy Coding :)

Comments

Submitted byneithan (not verified)on Sun, 12/10/2017 - 12:01

i will save this code for educational purpose

Add new comment