CRUD (Create Read Update Delete) operation in Laravel 5

By : PHPErrorCode October 12, 2017 287 Views laravel

today, in this post i Will teach you how to created a crud(create read update delete) operation in laravel aplication. crud means create read update and delete operation, so i share with you full semple crud operation example in laravel application.

The CRUD operations are the basic requirements of the website, so we will created a smole basic example of crud (create read update and delete) operation in laravel 5.5 web application. which usefull for your laravel 5.5 aplication.

If you are beginner for laravel developer, you are a right place. so you follow example few steps below.

Step 1: Installation Laravel

you have not installed laravel in your system. if yes, so install laravel project below command

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

Guidelines:

How To Create new laravel Projet in ubuntu, full guide follow this link -- Laravel_Ubuntu

How To Create new laravel Projet in windows, full guide follow this link -- Laravel_Windows

Step 2: Installation HTML Class

you have not installed laravelcollective/html in your laravel project. if yes, you can install from here : -- laravelcollective/html

Step 3: Create Table

In this step Use the migration to create a table, so use below command to create migration.

php artisan make:migration create_blog_table --create=blogs

After this command you will go to this path database/migration and then a file will be received and you have to put the following code in the transfer file to create a blog table.

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

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

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

After craete 'blogs' table file,To create a table in the MySQL database, add the following command

php artisan migrate

Step 4: Create Model

In this step create a model, so use below command to create model.

php artisan make:model Blog

After creating blog model go to this path app/blog.php and then a blog.php file will be received and you open this file and add the following code.

namespace App;

use Illuminate\Database\Eloquent\Model;

use DB;
use Config;

class Blog extends Model
{
    protected $table = 'blogs';
    protected $guarded = array();

    public function getData()
    {
    	return static::select('blogs.*')->paginate(4);
    }

    public function addData($input)
    {
    	$data = static::create($input);
    	return $data->id;
    }

    public function findData($id)
    {
    	return static::find($id);
    }

    public function updateData($id,$input)
    {
    	return static::where('id',$id)->update($input);
    }

    public function deleteData($id)
    {
    	return static::where('id',$id)->delete();
    }
}

Step 5: Create Route

Now in this step i create a resource route. It is able to use all the Route of CRUD like add index, create, show, edit update and delete route, so Go to this path routes/web and run below command.

Route::resource('Blog/CRUD','BlogController');
Using the above Resource Route, you will get a Route list as per the image below
crud route list in laravel

Step 6: Create Contriller

now we need create new controller as BlogController in this path app/Http/Controllers/BlogController.php. so use below command to create new BlogController.php Controller.

php artisan make:controller PhotoController --resource

The controller will handle all the route methods for which the following code is added to the BlogController.fop file.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Blog;

class BlogController extends Controller
{
    public function __construct()
    {
        $this->blog = new Blog;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = $this->blog->getData();
        return view('blog.index',compact('data',$data));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('blog.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'description' => 'required',
        ]);

        $input = array_except($request->all(),array('_token'));
        $this->blog->addData($input);
        return Redirect()->route('CRUD.index')->with('success','Blog created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = $this->blog->findData($id);
        return view('blog.show',compact('data',$data));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = $this->blog->findData($id);
        return view('blog.edit',compact('data',$data));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required',
            'description' => 'required',
        ]);

        $input = array_except($request->all(),array('_token','_method'));
        $this->blog->updateData($id,$input);
        return Redirect()->route('CRUD.index')->with('success','Blog update successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->blog->deleteData($id);
        return Redirect()->route('CRUD.index')->with('success','Blog delete successfully');
    }
}

Step 7: Create View File

Now, Goto resources/views/ than create new blog directory after create 4 file

resources/views/blog/

  1. index.blade.php
  2. create.blade.php
  3. shoe.blade.php
  4. edit.blade.php

index.blade.php

now we will creae layout for items listing in this file

<!DOCTYPE html>
<html lang="en">
<head>
  <title>CRUD (Create Read Update Delete) operation in Laravel 5</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body style="background: #f4511e;">
<div class="container">
<div class="col-md-9" style="background: #fff;">
  	<h1 class="col-md-8">Blog List</h1>
  	<a href="{{URL::route('CRUD.create')}}">
  		<button class="btn btn-primary btn-lg col-md-4 text-right">Create</button>
  	</a>
  	@if ($message = Session::get('success'))
  		<div class="alert alert-success alert-dismissable col-md-12">
		    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
		    <strong>{{ $message }}</strong>
		</div>
    @endif
  	<table class="table table-bordered">
	    <thead>
		    <tr>
		        <th width="12%">Title</th>
		        <th>Description</th>
		        <th width="28%">Action</th>
		    </tr>
	    </thead>
	    <tbody>
    	@if(!empty($data))
		@foreach($data as $key => $value)
		    <tr>
		        <td>{{$value->title}}</td>
		        <td>{{$value->description}}</td>
		        <td>
                                <a href="{{URL::route('CRUD.show',$value->id)}}" class="btn btn-success">Show</a>
		        	<a href="{{URL::route('CRUD.edit',$value->id)}}" class="btn btn-warning">Update</a>
		        	{!! Form::open(['method' => 'DELETE','route' => ['CRUD.destroy', $value->id],'style'=>'display:inline']) !!}
		            {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
		            {!! Form::close() !!}

		        </td>
		    </tr>
	    @endforeach
		@endif
			<tr>
				<td colspan="3">{!! $data->render() !!}</td>
			</tr>
	    </tbody>
  	</table>
</div>
</div>
</body>
</html>
Run Index blade file after Preview image:
crud insert record in laravel 5.5

create.blade.php

now we will creae layout for add records in mysql database in this file

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Create new record in laravel</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body style="background: #f4511e;">
  <div class="container">
    <br>
    <div class="col-md-8" style="background: #fff;">
      <h2 class="text-center">Create New Blog</h2>
      <form action="{{URL::route('CRUD.store')}}" method="post">
        {{ csrf_field() }}
        <div class="form-group {{ $errors->has('title') ? ' has-error' : '' }}">
          <label for="email">Title:</label>
          <input type="text" class="form-control" id="title" placeholder="Enter Title" name="title">
          @if ($errors->has('title'))
              <span class="help-block">
                  <strong>{{ $errors->first('title') }}</strong>
              </span>
          @endif
        </div>
        <div class="form-group {{ $errors->has('description') ? ' has-error' : '' }}">
          <label for="pwd">Description:</label>
          <textarea class="form-control" placeholder="Enter Description" name="description"></textarea>
          @if ($errors->has('description'))
              <span class="help-block">
                  <strong>{{ $errors->first('description') }}</strong>
              </span>
          @endif
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <br>
    </div>
  </div>
</body>
</html>
Run create blade file after Preview image:
create new record in laravel crud

shoe.blade.php

now we will creae layout for view single record in this file

<!DOCTYPE html>
<html lang="en">
<head>
  <title>CRUD (Create Read Update Delete) operation in Laravel 5</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body style="background: #f4511e;">
  <div class="container">
    <br>
    <div class="col-md-8" style="background: #fff;">
        <h1 class="col-md-6">Shoe Blog</h1>
        <a href="{{URL::route('CRUD.create')}}">
          <button class="btn btn-primary btn-lg col-md-3 text-right" >Create New Blog</button>
        </a>
        <a href="{{URL::route('CRUD.index')}}">
          <button class="btn btn-success btn-lg col-md-3 text-right" >Blog List</button>
        </a>
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>Title</th>
              <th>Description</th>
            </tr>
          </thead>
          <tbody>
              <tr>
                <td>{{$data->title}}</td>
                <td>{{$data->description}}</td>
              </tr>
          </tbody>
        </table>
    </div>
  </div>
</body>
</html>
Run show blade file after Preview image:
show record in laravel crud

edit.blade.php

Now we will create the layout for editing records in this file, then submit the form for your updated data.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Edit record in laravel</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body style="background: #f4511e;">
  <div class="container">
    <br>
    <div class="col-md-8" style="background: #fff;">
      <h2 class="text-center">Edit Blog</h2>
      {!! Form::model($data, ['method' => 'PATCH','route' => ['CRUD.update', $data->id]]) !!}
        {{ csrf_field() }}
        <div class="form-group {{ $errors->has('title') ? ' has-error' : '' }}">
          <label for="email">Title:</label>
          <input type="text" class="form-control" value="{{$data->title}}" id="title" name="title">
          @if ($errors->has('title'))
              <span class="help-block">
                  <strong>{{ $errors->first('title') }}</strong>
              </span>
          @endif
        </div>
        <div class="form-group {{ $errors->has('description') ? ' has-error' : '' }}">
          <label for="pwd">Description:</label>
          <textarea class="form-control" rows="6" name="description">{{$data->description}}</textarea>
          @if ($errors->has('description'))
              <span class="help-block">
                  <strong>{{ $errors->first('description') }}</strong>
              </span>
          @endif
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <br>
    </div>
  </div>
</body>
</html>
Run edit blade file after Preview image:
edit record in laravel crud

I hope this post will lot of help you.

thanks....