Tuesday, 28 March 2017

Create, Edit, Update and Destroy functionality using Laravel 5.3

In this tutorial we will create basic CRUD functionality (Create, Edit, Update and Delete) using Laravel 5.3. There are a few changes done in the latest version of Laravel 5.3 that I found that broke my earlier code. Many tutorials that are available online are not up to date and were not much helpful so I decided to write a tutorial.

First of all we will have to create a resource route in your routes/web.php. This is one of the change in Laravel 5.3: In earlier versions there was just one routes.php file but in Laravel 5.3 the routes have been split into three files.

Note that I am adding this route to resource controller for an admin section.

------------------------------------------------------------------------------------
Route::group(['prefix' => 'admin'], function () {
  ...
  Route::resource('/categories', 'admin\CategoryController');
  ...
});

----------------------------------------------------------------

we have to install a package using composer to make HTML and FORM functionality work. Laravel 5.3 does not come with HTML and FORM package installed.

-------------------------------------------------------------------------
composer require "laravelcollective/html":"^5.2.0"
-------------------------------------------------------------------------

Next in the config/app.php we have to add the following providers and aliases at the end of each arrays like shown below:

------------------------------------------------------------
'providers'[

Collective\Html\HtmlServiceProvider::class,
],


'aliases' => [

'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
'Input' => Illuminate\Support\Facades\Input::class,

],

------------------------------------------------------------

Next, We will have to create a controller using the following PHP artisan command in the command line editor. Make sure you are creating this inside your project directory.

------------------------------------------------------------

php artisan make:controller CategoryController --resource
------------------------------------------------------------

This command will create a Category resource controller with a few empty functions/methods such as index, create, edit, update, show and destroy. Note that these are REST functions.
The file will be created in Http/Controllers/CategoryController.php but we need this in the admin section so we will have to create a simple admin folder inside Controllers directory and move the CategoryController.php inside the admin/ folder.

In doing this we have changed its location so now we have to change the namespace as well. The namespace now changes from:



------------------------------------------------------------
namespace App\Http\Controllers;
To

namespace App\Http\Controllers\admin;


------------------------------------------------------------

Remember also to add the following entities and classes at the top of the file

------------------------------------------------------------
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Category;
use Validator;
use DB, Session, Crypt, Hash;
use Illuminate\Support\Facades\Input;
------------------------------------------------------------

Now, since this is an admin section I want to make sure that only the logged in user can access this page. To do this we will have to add authentication code inside our constructor in the CategoriesController.php page. You can also write a middleware to achieve this.

------------------------------------------------------------

public function __construct()
{
$this->middleware('auth');
}


------------------------------------------------------------


The Index() function

The below code needs to be added to the index function. The index function will handle listing of the categories along with the edit and delete buttons.

------------------------------------------------------------

public function index()
{
    // get all the categories
    $categories = DB::table('categories')->paginate(15);
    // load the view and pass the categories
    return view('admin.category.index', ['categories' => $categories]);
}

------------------------------------------------------------



We are simply querying the categories table and trying to paginate the results. The DB::table(‘categories’) part will fetch all the categories and the paginate function will paginate the results in 15 records each.

Next, We have to send the results to the view file. Usually view files goes inside resources/views/ directory but since this is an admin section we have to create a separate admin directory inside resources/views and add all the admin views inside it. So for CategoryController.php the views will be in resources/views/admin/category/ folder.
Lets have a closer look to the following line that we added in the controller.

------------------------------------------------------------

return view('admin.category.index', ['categories' => $categories]);
------------------------------------------------------------



We are going to send $categories array to admin/category/index.blade.php file. We use a dot notation to separate the directory.

This is what the index.blade.php looks like:

---------------------------------------------------------------
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <h1>All Categories</h1>
        <div><a href="{{ URL::to('admin/categories/create') }}">Create a Category</a></div>
        <!-- will be used to show any messages -->
        @if (Session::has('message'))
            <div class="alert alert-info">{{ Session::get('message') }}</div>
        @endif
        <table class="table table-striped table-bordered">
            <thead>
                <tr>
                    <td>ID</td>
                    <td>Category name</td>
                    <td>Actions</td>
                </tr>
            </thead>
            <tbody>
            @foreach($categories as $key => $value)
                <tr>
                    <td>{{ $value->id }}</td>
                    <td>{{ $value->name }}</td>
                    <td>
                        <a class="btn btn-small btn-info" href="{{ URL::to('admin/categories/' . $value->id . '/edit') }}">Edit</a>
                        {{ Form::open(array('url' => 'admin/categories/' . $value->id, 'class' => 'btn btn-small')) }}
                            {{ Form::hidden('_method', 'DELETE') }}
                            {{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}
                        {{ Form::close() }}
                    </td>
                </tr>
            @endforeach
            {{ $categories->links() }}
            </tbody>
        </table>
    </div>
</div>
@endsection
---------------------------------------------------------------
We are extending the default Laravel layouts.app. To generate pagination links the following code needs to be added to the index.blade.php file.

-----------------------------------------------------------


{{ $categories->links() }}
-----------------------------------------------------------


The create() function

The create function will just display the view at resources/views/admin/category/create.blade.php



-----------------------------------------------------------
public function create()
{
    return view('admin.category.create');

}

-----------------------------------------------------------

And the create.blade.php file looks like:


-----------------------------------------------------------
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
         
        <h1>Create a Category</h1>
         
        <!-- show errors -->
        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        {{ Form::open(array('url' => 'admin/categories')) }}
            <div class="form-group">
                {{ Form::label('name', 'Name') }}
                {{ Form::text('name', Input::old('name'), array('class' => 'form-control')) }}
            </div>
            {{ Form::submit('Create Category!', array('class' => 'btn btn-primary')) }}
        {{ Form::close() }}
    </div>
</div>
@endsection
-----------------------------------------------------------

The store() function

The store function will validate the input and store the data in the categories table.


-----------------------------------------------------------

public function store(Request $request)
{
    // validate
    // read more on validation at http://laravel.com/docs/validation
    $rules = array(
        'name'       => 'required',
    );
    $validator = Validator::make(Input::all(), $rules);
    $this->validate($request, [
        'name' => 'required'
    ]);
    if ($validator->fails()) {
        return redirect('admin/categories/create')
                    ->withErrors($validator)
                    ->withInput();
    } else {
        // store
        $category = new Category;
        $category->name = Input::get('name');
        $category->visible = 1;
        $category->save();
        // redirect
        Session::flash('message', 'Successfully created Category!');
        return redirect('admin/categories');
         
    }
}
-----------------------------------------------------------

The edit() function

The edit function displays the existing data in the input fields. It uses the layout resources/views/admin/category/edit.blade.php

-----------------------------------------------------------
public function edit($id)
{
    // get the category
    $category = Category::find($id);
    // show the edit form and pass the category
    return view('admin.category.edit')
    ->with('category', $category);

}

-----------------------------------------------------------
…and the edit.blade.php view looks like below:

-----------------------------------------------------------

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <h1>Edit {{ $category->name }}</h1>
        {{ Form::model($category, array('route' => array('categories.update', $category->id), 'method' => 'PUT')) }}
            <div class="form-group">
                {{ Form::label('name', 'Name') }}
                {{ Form::text('name', null, array('class' => 'form-control')) }}
            </div>
            {{ Form::submit('Edit the Category!', array('class' => 'btn btn-primary')) }}
        {{ Form::close() }}
    </div>
</div>
@endsection
-----------------------------------------------------------

The update() function

The update function will update the existing category.

-------------------------------------------------------------

public function update($id, Request $request)
{
    // validate
    // read more on validation at http://laravel.com/docs/validation
    $rules = array(
        'name'  => 'required',
    );
    $validator = Validator::make(Input::all(), $rules);
    $this->validate($request, [
        'name' => 'required'
    ]);
    if ($validator->fails()) {
        return redirect('admin/categories/create')
                    ->withErrors($validator)
                    ->withInput();
    } else {
        // store
        $category = Category::find($id);
        $category->name = Input::get('name');
        $category->visible = 1;
        $category->save();
        // redirect
        Session::flash('message', 'Successfully updated category!');
        return redirect('admin/categories');
         
    }

}
-------------------------------------------------------------

Finally the destroy() function

The destroy function deletes a category from the categories table.

-------------------------------------------------------------
public function destroy($id)
{
    // delete
    $category = Category::find($id);
    $category->delete();
    // redirect
    Session::flash('message', 'Successfully deleted the category!');
    return redirect('admin/categories')->with('status', 'Category Deleted!');
}
-------------------------------------------------------------

No comments:

Post a Comment

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in Laravel

  WampServer: Download this file:  http://curl.haxx.se/ca/cacert.pem Place this file in the  C:\wamp64\bin\php\php7.1.9  folder Open  php.in...

Popular Articles