CRUD appication in Laravel 5

We will building an simple laravel 5 CRUD admin panel where admin have controls to add new Book, Read book details, can edit book details and also delete book.Other focus areas are form validation with use of request and blade templating engine. I also demonstrate use of route resources and table migrations.

I trying to cover whole CRUD admin panel in 6 steps.

1.Installation

  • Set Route
  • Set Cntroller
  • Set Model
  • Set Table Migrations
  • Make new request, PublishBookRequest.php for Form Validation request in laravel 5.

set route(app/Http/routes.php)

<?php
Route::resource('book', 'BookController');

Now go to terminal and run  

php artisan route:list

 

METHOD URI NAME ACTION
GET book book.index App\Http\Controllers\BookController@index
GET book/create book.create App\Http\Controllers\BookController@create
POST book book.store App\Http\Controllers\BookController@store
GET book/{book} book.show App\Http\Controllers\BookController@show
GET book/{book}/edit book.edit App\Http\Controllers\BookController@edit
PUT book/{book} book.update App\Http\Controllers\BookController@update
DELETE book/{book} book.destroy App\Http\Controllers\BookController@destroy

 

set controller(app/Http/Controllers/BookController.php)

php artisan make:controller BookController

You just created your controller and look at app\Http\controllers and open BookController.php file.

<?php
<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class BookController extends Controller {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}
}

 

Set Model

php artisan make:model Book

Open model app/Book.php 

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model {

    protected $table = 'books';
	protected $fillable = [
        'title',
        'description',
        'author'
    ];

}

There are two variables are declared in Book model, Fillable attribute protect against mass-assignment while Table attribute direct our model to perticular table from database.

Set Table Migrations

php artisan make:migration create_books_table –table=books

Find new migration file databse/migrations/____create_books_table.php 

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('books', function(Blueprint $table)
		{
			$table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->string('author');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('books');
	}

}

 

Make new request(app/Http/Requests)

php artisan make:request PublishBookRequest

Add rules to newly generated request file  

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class PublishBookRequest extends Request {

	/**
	 * 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 [
			'title' => 'required',
			'description' => 'required',
			'author' => 'required'
		];
	}

}

In above code, We defined validation rules for our Insert and Update form.

2.List All Records

View, resources/views/books/bookList.blade.php (Show all book listing)

<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
    <body>
    <div class="container">
        {{--Header Started--}}

        <div class="btn btn-block"><a href="{{ route('book.create')  }}"><h2>Add New Book</h2></a></div>
        @foreach( $allBooks as $book )
            <hr>
            <div class="row">
                {!! HTML::linkRoute('book.edit', 'Edit', array($book->id), ['class'=>'btn btn-default col-xs-2']) !!}
                {!! Form::open(['route' => ['book.destroy', $book->id], 'method' => 'delete']) !!}
                <input class="btn btn-default col-xs-2" type="submit" value="Delete" />
                {!! Form::close() !!}
            </div>
            <div><h1>{!! HTML::linkRoute('book.show', $book->title, array($book->id)) !!}</h1></div>
            <div>{{ $book->description }}</div>
            <div class="pull-right"><em>{{'Published by-'. $book->author }}</em>
            </div>
        @endforeach

        {{--Footer Finished--}}
    </div>
    </body>
</html>

 

Controller, index method(Every methods remain in BookController class)

Method URI NAME ACTION
GET book book.index App\Http\Controllers\BookController@index

 

<?php
/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
        //Select all records from books table via Book method
		$allBooks = Book::all();    //Eloquent ORM method to return all matching results
        
        //Redirecting to bookList.blade.php with $allBooks       
        return View('books.bookList', compact('allBooks'));
	}

 

3.Insert New Record

View, resources/views/books/addBook.blade.php (Add new book record)

 

<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        {{--Header Finished--}}

        <div><h1>Add New Book</h1></div>
        {!! Form::open(['action' => 'BookController@store']) !!}

            <div class="form-group">
                {!! Form::label('title', 'Title :') !!}
                {!! Form::text('title', null, ['class'=>'form-control', 'placeholder'=>'Enter Title']) !!}
            </div>

            <div class="form-group">
                {!! Form::label('description', 'Description :') !!}
                {!! Form::textarea('description', null,  ['class'=>'form-control', 'placeholder'=>'Description']) !!}
            </div>

            <div class="form-group">
                {!! Form::label('author', 'Author name :') !!}
                {!! Form::text('author', null,  ['class'=>'form-control', 'placeholder'=>'Author Name']) !!}
            </div>
            <br>
            <div class="form-group">
                {!! Form::submit( 'Submit', ['class'=>'btn btn-toolbar']) !!} <button class="btn btn-toolbar pull-right"><a href="/book">Back to Home</a></button>
            </div>
        {!! Form::close() !!}
        @if($errors->any())
            <ul class="alert alert-danger">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        @endif

        {{--Footer started--}}
    </div>
</body>
</html>

 

Controller, create and store methods(Every methods remain in BookController class)

Method URI NAME ACTION
GET book/create book.create App\Http\Controllers\BookController@create
POST book book.store App\Http\Controllers\BookController@store

 

<?php
/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
        //Redirecting to addBook.blade.php 
		return view('books.addBook');
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store(PublishBookRequest $requestData)
	{
        //Insert Query
        $book = new Book;
        $book->title= $requestData['title'];
        $book->description= $requestData['description'];
        $book->author= $requestData['author'];
        $book->save();

        //Send control to index() method where it'll redirect to bookList.blade.php
        return redirect()->route('book.index');
	}

4.Show Book Information

View, resources/views/books/showBook.blade.php (Book information)

<?php
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
    <body>
    <div class="container">
        {{--Header finished--}}
        <div class="row col-xs-8 col-xs-offset-2 img-rounded text-center" style="background-color: #eee;">
            <div ><h2>{{ $book->title }}</h2></div>
            <div >{{ $book->description }}</div>
            <div class="blockquote-reverse">Published by -{{ $book->author }}</div>
            <button class="btn btn-toolbar"><a href="/book">Back to Home</a></button>
        </div>
        {{--Footer Started--}}
    </div>
    </body>
</html>

 

Controller, show method(Every methods remain in BookController class)

Method URI NAME ACTION
GET book/{book} book.show App\Http\Controllers\BookController@show

 

<?php
/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
        //Get results by targeting id
        $book = Book::find($id);

        //Redirecting to showBook.blade.php with $book variable
        return view('books.showBook')->with('book',$book);
	}

5.Modify Book Information

View, resources/views/books/editBook.blade.php

 

<?php
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
        <div class="container">
        {{--Header Finished--}}

        <div><h1>Edit {{ $book->title }}</h1></div>
        {!! Form::model($book, ['route' => ['book.update', $book->id ], 'method'=>'PUT']) !!}
            <div class="form-group">
                {!! Form::label('title', 'Title :') !!}
                {!! Form::text('title', null, ['class'=>'form-control', 'placeholder'=>'Enter Title']) !!}
            </div>

            <div class="form-group">
                {!! Form::label('description', 'Description :') !!}
                {!! Form::textarea('description', null,  ['class'=>'form-control', 'placeholder'=>'Description']) !!}
            </div>

            <div class="form-group">
                {!! Form::label('author', 'Author name :') !!}
                {!! Form::text('author', null,  ['class'=>'form-control', 'placeholder'=>'Author Name']) !!}
            </div>
            <br>
            <div class="form-group">
                {!! Form::submit( 'Update', ['class'=>'btn btn-toolbar']) !!} <button class="btn btn-toolbar pull-right"><a href="/book">Back to Home</a></button>            </div>

            {!! Form::close() !!}
            @if($errors->any())
                <ul class="alert alert-danger">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            @endif

            {{--Footer Started--}}
     </div>
</body>
</html>

 

Controller, edit and update methods(Every methods remain in BookController class)

Method URI NAME ACTION
GET book/{book}/edit book.edit App\Http\Controllers\BookController@edit
PUT book/{book} book.update App\Http\Controllers\BookController@update

 

<?php
/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
        //Get Result by targeting id
        $book = Book::find($id);

        //Redirecting to editBook.blade.php with $book variable
        return view('books.editBook')->with('book',$book);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id, PublishBookRequest $requestData)
	{
        $book = Book::find($id);

        //Update Query
        $book->title = $requestData['title'];
        $book->description = $requestData['description'];
        $book->author = $requestData['author'];
        $book->save();

        //Redirecting to index() method of BookController class
        return redirect()->route('book.index');
	}

6.Delete Book

View, resources/views/books/bookList.blade.php (Add delete form with button)

This process has been done in bookList.blade.php view page.

<?php
{!! Form::open(['route' => ['book.destroy', $book->id], 'method' => 'delete']) !!}
        <input class="btn btn-default col-xs-2" type="submit" value="Delete" />
{!!Form::close() !!}

 

Controller, destroy method(Every methods remain in BookController class)

Method URI NAME ACTION
DELETE book/{book} book.destroy App\Http\Controllers\BookController@destroy

 

<?php
/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
    {
        //find result by id and delete 
        Book::find($id)->delete();

        //Redirecting to index() method
        return redirect()->route('book.index');
    }

 

Something to say? Tell us in comment section.