All for Joomla The Word of Web Design

laravel 5.5 crud application example code

custom 404 page laravel

In this tutorial i will shows how you can create basic crud(create, read, update and delete) module in laravel 5.5 application. Laravel is a popular open-source PHP MVC Framework with lots of advanced development features. Laravel released it’s new version 5.5 as few days ago.

If you are learner or beginner of crud example in laravel 5.5 application then you are a right place. It’s always help to more understand or learn from crud application for beginner developer.

Here, i will create insert, update, delete and view with pagination example of articles. You can simply create new article, view article, edit article and remove article from lists. I make very simple example using Laravel Form builder using resource route. I make resource controller for crud application in laravel 5.5. So you have to just follow few step and get full example of CRUD application. end of article you will get layout like as bellow screen shot.

Result:

 

Step 1 : Install Laravel 5.5

I am going to show you scratch, So we require to get fresh Laravel 5.5 version application using bellow command, So open your terminal OR command prompt and run bellow command:

Step 2 : Install Laravel Collective

Here, we will install laravelcollective/html composer package for form builder so open your terminal and run bellow command:

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

config/app.php

'providers' => [
	....
	Collective\Html\HtmlServiceProvider::class,
],
'aliases' [
	....
	'Form' => Collective\Html\FormFacade::class,
        'Html' => Collective\Html\HtmlFacade::class,
],

Step 3: Database Configuration

In this step we have to make database configuration for example database name, username, password etc for our crud application of laravel 5.5. So let’s open .env file and fill all details like as bellow:

.env

Step 4: Create articles Table and Model

we are going to create crud application for article. so we have to create migration for articles table using Laravel 5.5 php artisan command, so first fire bellow command:

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create articles table.

<?php

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

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

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

After setting the migration file run the migrate command to create the table.

After creating table we have to create model for “articles” table so just run bellow command and create new model:

Ok, so after run bellow command you will find app/Article.php and put bellow content in Article.php file:

app/Article.php

Step 5: Add Resource Route

In this is step we need to add resource route(Create all the routes for crud) for article crud application. so open your routes/web.php file and add following route.

routes/web.php

Route::resource('articles','ArticleController');

Step 6: Create ArticleController

Here,We need a controller to manage the Crud action .So run bellow command and create a new controller as ArticleController.

After running this command we will find new controller file in this path app/Http/Controllers/ArticleController.php.

In this controller we  will get seven methods by default as bellow methods:

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy()

We will change the create the functions as per our requirement.So, let’s copy bellow code and put on ArticleController.php file.

app/Http/Controllers/ArticleController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Article;
class ArticleController extends Controller

{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index()
    {
        $articles = Article::latest()->paginate(5);
        return view('articles.index',compact('articles'))
            ->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('articles.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',
            'body' => 'required',
        ]);
        Article::create($request->all());
        return redirect()->route('articles.index')
                        ->with('success','Article created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function show($id)
    {
        $article = Article::find($id);
        return view('articles.show',compact('article'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function edit($id)
    {
        $article = Article::find($id);
        return view('articles.edit',compact('article'));
    }

    /**
     * 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',
            'body' => 'required',
        ]);

        Article::find($id)->update($request->all());
        return redirect()->route('articles.index')
                        ->with('success','Article updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function destroy($id)
    {
        Article::find($id)->delete();
        return redirect()->route('articles.index')
                        ->with('success','Article deleted successfully');
    }

}

Step 7: Create Blade Files (View File)

So, now we are in last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder “articles” then create blade files of crud oprations. So finally you have to create following given blade file in the articles folder in the view folder:

1) layout.blade.php

2) index.blade.php

3) show.blade.php

4) form.blade.php

5) create.blade.php

6) edit.blade.php

So let’s create following file and paste the bellow code.

resources/views/layout.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ env('APP_NAME') }}|{{ ($pageTitle)??"" }}</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">

                    <!-- Collapsed Hamburger -->
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                        <span class="sr-only">Toggle Navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>

                    <!-- Branding Image -->
                    <a class="navbar-brand" href="{{ url('/') }}">
                        {{ config('app.name', 'TemplateBench') }}
                    </a>
                </div>

                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <!-- Left Side Of Navbar -->
                    <ul class="nav navbar-nav">
                        &nbsp;
                    </ul>

                    <!-- Right Side Of Navbar -->
                </div>
            </div>
        </nav>
        <div class="container">
        	@yield('content')
        </div>
    </div>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

resources/views/articles/index.blade.php

@extends('layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 5.5 CRUD Operation</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('articles.create') }}"> <i class="fa fa-plus"></i></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>#</th>
            <th>Title</th>
            <th>Body</th>
            <th width="300px">Action</th>
        </tr>
    @foreach ($articles as $article)
    <tr>
        <td>{{ $loop->iteration }}</td>
        <td>{{ $article->title}}</td>
        <td>{{ $article->body}}</td>
        <td>
            <a class="btn btn-info" href="{{ route('articles.show',$article->id) }}"><i class="fa fa-eye"></i></a>
            <a class="btn btn-primary" href="{{ route('articles.edit',$article->id) }}"><i class="fa fa-pencil"></i></a>
            {!! Form::open(['method' => 'DELETE','route' => ['articles.destroy', $article->id],'style'=>'display:inline']) !!}
            <button class="btn btn-danger" type="submit"><i class="fa fa-trash"></i></button>
            {!! Form::close() !!}
        </td>
    </tr>
    @endforeach
    </table>
    {!! $articles->links() !!}
@endsection

resources/views/articles/show.blade.php

@extends('layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Article</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('articles.index') }}"> <i class="fa fa-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>
                {{ $article->title}}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Body:</strong>
                {{ $article->body}}
            </div>
        </div>
    </div>
@endsection

resources/views/articles/form.blade.php

<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>Body:</strong>
            {!! Form::textarea('body', null, array('placeholder' => 'Body','class' => 'form-control','style'=>'height:150px')) !!}
        </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/articles/create.blade.php

@extends('layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Add New Article</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('articles.index') }}"> <i class="fa fa-arrow-left"></i></a>
            </div>
        </div>
    </div>
    @if (count($errors) < 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    {!! Form::open(array('route' => 'articles.store','method'=>'POST')) !!}
         @include('articles.form')
    {!! Form::close() !!}
@endsection

resources/views/articles/edit.blade.php

@extends('layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit Article</h2>
            </div>
            <div class="pull-right">
               <a class="btn btn-primary" href="{{ route('articles.index') }}"> <i class="fa fa-arrow-left"></i></a>
            </div>
        </div>
    </div>
    @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
    {!! Form::model($article, ['method' => 'PATCH','route' => ['articles.update', $article->id]]) !!}
        @include('articles.form')
    {!! Form::close() !!}
@endsection

Now we are ready to run our crud application example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/articles

Thanks you for visiting my site. I hope it will help you …

3 Comments

  • Sangeet Kumar Reply

    November 2, 2017 at 5:52 pm

    Thanks sir

  • randhir kumar Reply

    November 25, 2017 at 4:10 pm

    help full tutorial

    • Abhi Singh Reply

      November 25, 2017 at 6:53 pm

      Thanks randhir Kumar,please share post with your friends . If you like it

Leave a Comment

Login

Welcome! Login in to your account

Remember me Lost your password?

Lost Password