Mini-course: How To Create Admin Panel in Laravel 5.4


In this chapter we will create forms for new entry and updating it, also will take care of the actual functionality on the back-end.

Create Controller and View

Somewhere in your resources/views/authors/index.blade.php file add a link to create new entry:

    <a href="{{ route('authors.create') }}" class="btn btn-default">Add New Author</a>

Creating a form is pretty easy, here’s the code.

app/Http/Controllers/AuthorsController.php:

    public function create()
    {
        return view('authors.create');
    }

And then resources/views/authors/create.blade.php:

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Add New Author</div>

                    <div class="panel-body">
                        <form action="{{ route('authors.store') }}" method="post">
                            {{ csrf_field() }}
                            First name:
                            <br />
                            <input type="text" name="first_name" value="{{ old('first_name') }}" />
                            <br /><br />
                            Last name:
                            <br />
                            <input type="text" name="last_name" value="{{ old('last_name') }}" />
                            <br /><br />
                            <input type="submit" value="Submit" class="btn btn-default" />
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

Visually, it looks like this:

laravel create form

Saving the data is also simple – in Controller we fill in the Author’s entry and redirect to the list:

    public function store(Request $request)
    {
        Author::create($request->all());
        return redirect()->route('authors.index');
    }    

Validation and Requests

All done with creating the authors, right? Wrong. What about validation of the data? Let’s make first_name and last_name required fields.

In store() method we need to change Request $request parameter to our custom request which would contain our rules for the validation. So let’s make that file with Artisan command:

php artisan make:request StoreAuthorRequest 

This will generate the file app/Http/Requests/StoreAuthorRequest.php and we fill it with this code:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreAuthorRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'first_name' => 'required',
            'last_name' => 'required'
        ];
    }
}

Comparing to the default empty Request file, we’ve changed two things:

  • Changed authorize() to return true instead of false
  • Added elements to rules() array, each of them is a field with its validation rules

And then we change Controller method to this:

    public function store(StoreAuthorRequest $request)
    {
        Author::create($request->all());
        return redirect()->route('authors.index');
    }    

Nothing has changed except for parameter class. Please also add this line to the top of the Controller file (PhpStorm did it automatically for me):

use App\Http\Requests\StoreAuthorRequest;    

Finally, we need to show validation errors somewhere in our resources/views/authors/create.blade.php, something like this:

...
<div class="panel-body">
    @if ($errors->count() > 0)
        <ul>
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    @endif
    <form action="{{ route('authors.store') }}" method="post">    
...

Now, if we fill the form with empty inputs and just hit Submit, we will see something like this:

laravel validation errors

If you have more fields and various validation rules, there are plenty of options – please read about them here in the official Laravel documentation.


Edit Form and Update

Guess what – there will be a lot of copy-paste code here, or repeating almost the same steps.

app/Http/Controllers/AuthorsController.php:

    public function edit($id)
    {
        $author = Author::findOrFail($id);
        return view('authors.edit', compact('author'));
    }    

Note that if the entry isn’t found in the database, system would throw 404 error page.

Now, resources/views/authors/edit.blade.php is almost a copy of create.blade.php, the differences are form action, form method hidden field and text field values:

...
    <div class="panel-heading">Edit Author</div>

    <div class="panel-body">
        @if ($errors->count() > 0)
            <ul>
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        @endif
        <form action="{{ route('authors.update', $author->id) }}" method="post">
            <input type="hidden" name="_method" value="PUT">
            {{ csrf_field() }}
            First name:
            <br />
            <input type="text" name="first_name" value="{{ $author->first_name }}" />
            <br /><br />
            Last name:
            <br />
            <input type="text" name="last_name" value="{{ $author->last_name }}" />
            <br /><br />
            <input type="submit" value="Submit" class="btn btn-default" />
        </form>
    </div>

To perform the update operation, we use Controller’s method update() and we will pass the same Request file for validation, cause rules are the same:

    public function update(StoreAuthorRequest $request, $id)
    {
        $author = Author::findOrFail($id);
        $author->update($request->all());
        return redirect()->route('authors.index');
    }    

Lastly, let’s show a success message in case of successful operation, we add this to Controller:

    public function store(StoreAuthorRequest $request)
    {
        Author::create($request->all());
        return redirect()->route('authors.index')->with(['message' => 'Author added successfully']);
    } 

    // ...


    public function update(StoreAuthorRequest $request, $id)
    {
        $author = Author::findOrFail($id);
        $author->update($request->all());
        return redirect()->route('authors.index')->with(['message' => 'Author updated successfully']);
    }

And then this piece of code in index.blade.php:

    @if (session('message'))
        <div class="alert alert-info">{{ session('message') }}</div>
    @endif    

Result:

laravel success message

That’s it about create/update forms and their processing. Next topic – how to delete the entry! Stay tuned.