How to create a CRUD controller in Laravel 5.8

CRUD operations are the Create, Read, Update, and Delete functions we do in an application. Let’s learn how to create a CRUD controller in Laravel 5.8 from scratch. Let’s consider this simple example of Laravel 5.8 crud app.

Step 1: Install Laravel and Create new Project

Firstly, we need to get Laravel 5.8 application using the command below. So open your terminal and run the command.

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

Step 2: Check Database Configuration

In the second step, we will make database configurations. For example, database name, username, password, and all other fields required for CRUD application of Laravel 5.8. Here we open .env file and fill in all details.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=here your database name(blogs)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)

Step 3: Create new Database Table

Next, we will create migration for “posts” table using Laravel 5.8 PHP artisan command as shown below.

php artisan make:migration create_posts_table --create=posts

This command creates a file in the ‘database/migrations’ directory. You can add your code for the posts table in your migration file as shown below.

<?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::dropIfExists('posts');
    }
}

Then run the ‘php artisan migrate’ command. This creates a new table with the specified columns as above in your database.

Step 4: Create new Routes

You will add routes in your routes/web.php file for the controller functions and their link with view (blade) files.

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

Step 5: Create new Model

You will now create a ‘Posts’ Model, with the code below.

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
   
class Posts extends Model
{
    protected $fillable = [
        'title', 'detail'
    ];
}

Step 6: Create new Controller

Next, create a new controller using the command below.

php artisan make:controller PostController

Now add the methods below in the Controller class. This creates a CRUD Controller.

<?php
  
namespace App\Http\Controllers;
  
use App\Product;
use Illuminate\Http\Request;
  
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::latest()->paginate(5);
  
        return view('posts .index',compact('posts'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }
   
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('products.create');
    }
  
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
  
        Product::create($request->all());
   
        return redirect()->route('products.index')
                        ->with('success','Product created successfully.');
    }
   
    /**
     * Display the specified resource.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        return view('posts.show',compact('post'));
    }
   
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function edit(Post $post)
    {
        return view('posts.edit',compact('post'));
    }
  
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Post  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        $request->validate([
            'title' => 'required',
            'content' => 'required',
        ]);
  
        $post->update($request->all());
  
        return redirect()->route('posts.index')
                        ->with('success','Post updated successfully');
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();
  
        return redirect()->route('posts.index')
                        ->with('success','Post deleted successfully');
    }
}

The multiple CRUD operations are defined above in the Controller class. These perform the functions to Read (View) original posts in database, Create a new post, save the post data, show option to edit a post, then update the edited records with validation. Then the destroy function in end deletes a selected post.

To view and perform these operations on the frontend we will create blade files.

Step 7: Create new Blade files

Since there are multiple operations and views, we will have to create a separate blade files for each.

This is the layout blade file. This is for the applications general layout.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5.8 CRUD Operations- scratchcoding.dev</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
  
<div class="container">
    @yield('content')
</div>
   
</body>
</html>

Then comes the index blade file. Extended by the first layout, this loops through all the posts and views the ones already in database. It also shows the options for CRUD operations like Edit and Delete.

@extends('posts.layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 5.8 CRUD Example from scratch - scratchcoding.dev</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('posts.create') }}"> Create New Post</a>
            </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>No</th>
            <th>Title</th>
            <th>Content</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($posts as $post)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $post->title}}</td>
            <td>{{ $post->content}}</td>
            <td>
                <form action="{{ route('post.destroy',$post->id) }}" method="POST">
   
                    <a class="btn btn-info" href="{{ route('post.show',$post->id) }}">Show</a>
    
                    <a class="btn btn-primary" href="{{ route('post.edit',$post->id) }}">Edit</a>
   
                    @csrf
                    @method('DELETE')
      
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
  
    {!! $posts->links() !!}
      
@endsection

Next comes the view, this one will allow user to add a new post.

@extends('posts.layout')
  
@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">
            <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <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
   
<form action="{{ route('posts.store') }}" method="POST">
    @csrf
  
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Title:</strong>
                <input type="text" name="title" class="form-control" placeholder="Title">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Content:</strong>
                <textarea class="form-control" style="height:150px" name="content" placeholder="Content"></textarea>
            </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>
   
</form>
@endsection

Next, we will create the edit blade.

@extends('posts.layout')
   
@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">
                <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
            </div>
        </div>
    </div>
   
    @if ($errors->any())
        <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
  
    <form action="{{ route('posts.update',$post->id) }}" method="POST">
        @csrf
        @method('PUT')
   
         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Title:</strong>
                    <input type="text" name="title" value="{{ $post->title}}" class="form-control" placeholder="Title">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Content:</strong>
                    <textarea class="form-control" style="height:150px" name="content" placeholder="Detail">{{ $post->content}}</textarea>
                </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>
   
    </form>
@endsection

Lastly, comes the show blade that lets us view a newly added post.

@extends('posts.layout')
@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">
                <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</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 the ‘php artisan serve’ command and run your CRUD application in the local browser.

Leave a Comment