Laravel 5 - Create Simple CRUD(Create Read Update Delete) application example

May 7, 2017 | Category : Laravel 5 Bootstrap Laravel PHP

In this tutorial, i am going to share with you how to create CRUD module in laravel 5 application. CRUD stand for Create, Read, Update and Delete. As we know crud module is always require for basic data input in database.

In this example i created "posts" module. i make posts table with title and content column. You can add post, view post, edit post and remove that post. I follow laravel rules and validation for creating this crud module. In this article i also use Form class to create laravel form.

you have to just follow few step and will create module as like bellow preview:

Layout:

Step 1: Install Laravel 5

If you haven't installed laravel in your system then first install with following command and get fresh Laravel application.

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

Step 2: Install laravelcollective/html package

In this step we require to install laravelcollective/html package for Form class. So you have to install by following command:

composer require laravelcollective/html

After successfully install package, open config/app.php file and add service provider and alias.

config/app.php

'providers' => [

....

'Collective\Html\HtmlServiceProvider',

],

'aliases' => [

....

'Form' => 'Collective\Html\FormFacade',

]

Step 3: Create posts table and model

here you have to create posts table in your database. First create migration for posts table using Laravel 5 php artisan command, so first run bellow command:

php artisan make:migration create_posts_table

After run above command, you will see a migration file in following path database/migrations and you have to simply put following code in migration file to create products table.

<?php

use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string('title');

$table->text('content');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::drop("posts");

}

}

Run migration file and run following command:

php artisan migrate

After create `posts` table, we should create model for product table. Create file in following path app/Post.php and put bellow couple of code in Post.php file:

app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

protected $fillable = ['title','content'];

}

Step 4: Add Route

in this step, we need to create route for posts CRUD, so just add resource route in your routes file.I added resource route because it will add index, show, create, show and delete routes automatically.So put bellow line of code in your route file.

routes/web.php

Route::resource('posts', 'PostController');

Step 5: Create Controller

Now we will create PostController in following path app/Http/Controllers, all routes will manage by this PostController.php file, so let's copy bellow code and paste on bellow file:

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;

class PostController extends Controller

{

public function index(Request $request)

{

$posts= Post::latest()->paginate(10);

return view('posts.index',compact('posts'))

->with('i', ($request->input('page', 1) - 1) * 10);

}

public function create()

{

return view('posts.create');

}

public function store(Request $request)

{

$this->validate($request, [

'title' => 'required',

'content' => 'required',

]);

Post::create($request->all());

return redirect()->route('posts.index')

->with('success','Post created successfully');

}

public function show($id)

{

$post= Post::find($id);

return view('posts.show',compact('post'));

}

public function edit($id)

{

$post= Post::find($id);

return view('posts.edit',compact('post'));

}

public function update(Request $request, $id)

{

$this->validate($request, [

'title' => 'required',

'content' => 'required',

]);

Post::find($id)->update($request->all());

return redirect()->route('posts.index')

->with('success','Post updated successfully');

}

public function destroy($id)

{

Post::find($id)->delete();

return redirect()->route('posts.index')

->with('success','Post deleted successfully');

}

}

Step 6: Create Blade Files

In last step, we will create blade file for listing, create, edit, show, form, default (which is master template).According to standard structure of Laravel, we create new files as listed bellow.

resources/views/layouts/default.blade.php

resources/views/posts/index.blade.php

resources/views/posts/form.blade.php

resources/views/posts/create.blade.php

resources/views/posts/edit.blade.php

resources/views/posts/show.blade.php

So, let's follow bellow files code:

resources/views/layouts/default.blade.php

<!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 CRUD Application Example</title>

<!-- Latest compiled and minified CSS -->

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</head>

<body>

<div class="container">

@yield('content')

</div>

</body>

</html>

resources/views/posts/index.blade.php

@extends('layouts.default')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Post CRUD</h2>

</div>

</div>

</div>

@if ($message = Session::get('success'))

<div class="alert alert-success">

<p>{{ $message }}</p>

</div>

@endif

<table class="table table-bordered">

<tr>

<th width="80px">No</th>

<th>Title</th>

<th>Content</th>

<th width="140px" class="text-center">

<a class="btn btn-success btn-sm" href="{{ route('posts.create') }}"><i class="glyphicon glyphicon-plus"></i></a>

</th>

</tr>

@foreach ($posts as $post)

<tr>

<td>{{ ++$i }}</td>

<td>{{ $post->title }}</td>

<td>{{ $post->content }}</td>

<td>

<a class="btn btn-info btn-sm" href="{{ route('posts.show',$post->id) }}"><i class="glyphicon glyphicon-th-large"></i></a>

<a class="btn btn-primary btn-sm" href="{{ route('posts.edit',$post->id) }}"><i class="glyphicon glyphicon-pencil"></i></a>

{!! Form::open(['method' => 'DELETE','route' => ['posts.destroy', $post->id],'style'=>'display:inline']) !!}

<button type="submit" style="display: inline;" class="btn btn-danger btn-sm"><i class="glyphicon glyphicon-trash"></i></button>

{!! Form::close() !!}

</td>

</tr>

@endforeach

</table>

{!! $posts->render() !!}

@endsection

resources/views/posts/form.blade.php

@if (count($errors) > 0)

<div class="alert alert-danger">

<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

<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Title:</strong>

{!! Form::text('title', null, array('placeholder' => 'Title','class' => 'form-control')) !!}

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Content:</strong>

{!! Form::textarea('content', null, array('placeholder' => 'Content','class' => 'form-control','style'=>'height:100px')) !!}

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12 text-center">

<button type="submit" class="btn btn-primary">Submit</button>

</div>

</div>

resources/views/posts/create.blade.php

@extends('layouts.default')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Add New Post</h2>

</div>

<div class="pull-right">

<br/>

<a class="btn btn-primary" href="{{ route('posts.index') }}"> <i class="glyphicon glyphicon-arrow-left"></i></a>

</div>

</div>

</div>

{!! Form::open(array('route' => 'posts.store','method'=>'POST')) !!}

@include('posts.form')

{!! Form::close() !!}

@endsection

resources/views/posts/edit.blade.php

@extends('layouts.default')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Edit Post</h2>

</div>

<div class="pull-right">

<br/>

<a class="btn btn-primary" href="{{ route('posts.index') }}"> <i class="glyphicon glyphicon-arrow-left"></i></a>

</div>

</div>

</div>

{!! Form::model($post, ['method' => 'PATCH','route' => ['posts.update', $post->id]]) !!}

@include('posts.form')

{!! Form::close() !!}

@endsection

resources/views/posts/show.blade.php

@extends('layouts.default')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2> Show Post</h2>

</div>

<div class="pull-right">

<br/>

<a class="btn btn-primary" href="{{ route('posts.index') }}"> <i class="glyphicon glyphicon-arrow-left"></i></a>

</div>

</div>

</div>

<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Title:</strong>

{{ $post->title}}

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Content:</strong>

{{ $post->content}}

</div>

</div>

</div>

@endsection

Now you can run your build your first Laravel CRUD Application...Enjoy....