Laravel Redirect To Another URL / Web Page - HTTP Laravel Redirects

PHP Laravel MySQL CRUD Application

Today, We want to share with you PHP Laravel MySQL CRUD Application.In this post we will show you CRUD Operations in Laravel PHP Framework, hear for Laravel 5.7 CRUD Operations Tutorial step by step we will give you demo and example for implement.In this post, we will learn about CRUD (Create Read Update Delete) in a Laravel 5.7 App with an example.

PHP Laravel MySQL CRUD Application

There are the Following The simple About PHP Laravel MySQL CRUD Application Full Information With Example and source code.

As I will cover this Post with live Working example to develop simple crud application in laravel 5.7, so the

Laravel 5.7 CRUD Tutorial With Example from scratch

for this example is following below.

In this Laravel 5.7 Insert Update Delete Examples, I am creating CRUD for products table. After all these steps, your output will look like this.

Create Laravel Project:

First, we need to create first of all simple crud application in laravel 5 by runing following command in your terminal.

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

Configure .env file:

After creating a laravel project, open your project in your any editor and open .env file and configure your database setting in .env change following value in that file like that

.env change

DB_DATABASE=databasename
DB_USERNAME=root
[email protected]!#7854 

Make Laravel Auth: laravel crud generator

Next, I am create laravel bydefault authentication by run following command. laravel 5.7all the CRUD Auth provide ready made authentication system so I am use that.

php artisan make:auth   

Create Route:

Now, open your first of all main nav call routes/web.php file and add one route using recource in this file for our products crud. here i am use resource instade of all changes saperate route.

routes/web.php

Route::resource('products', 'productsController');

Simple add above line in your web.php file with Onther Examples with step by step PHP Laravel 5.7 insert update delete in MySQL Example

Change in app.blade.php file:

Next, I am change some path in resources/views/layouts/app.blade.php file so, open this file and laravel 5.7 crud step by step copy this all the source code as well as past in your app.blade.php file.

resources/views/layouts/app.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>{{ config('app.name', 'Laravel') }}</title>
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <script type="text/javascript">
      var current_page_url = "<?php echo URL::current(); ?>";
      var current_page_fullurl = "<?php echo URL::full(); ?>";
      var CSRF_TOKEN='{{ csrf_token() }}';
    </script>
  </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" aria-expanded="false">
            <span class="sr-only">Web Site Name</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('/home') }}">
            CBTF
            </a>
          </div>
          <div class="collapse navbar-collapse" id="app-navbar-collapse">
            <!-- Left Side Of Navbar -->
            <ul class="nav navbar-nav">
               
            </ul>
            <!-- Right Side Of Navbar -->
            <ul class="nav navbar-nav navbar-right">
              <!-- Authentication Links -->
              @guest
              <li><a href="{{ route('login') }}">Sign In</a></li>
              <li><a href="{{ route('register') }}">Sign Up</a></li>
              @else
              <li><a href="{{ URL::route('products.index') }}">products</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
                {{ Auth::user()->name }} <span class="caret"></span>
                </a>
                <ul class="dropdown-menu">
                  <li>
                    <a href="{{ route('logout') }}"
                      onclick="event.preventDefault();
                      document.getElementById('logout-form').submit();">
                    Logout
                    </a>
                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                      {{ csrf_field() }}
                    </form>
                  </li>
                </ul>
              </li>
              @endguest
            </ul>
          </div>
        </div>
      </nav>
      <div class="container">
        <div class="row">
          <div class="col-md-10 col-md-offset-1">
            @include('alert')
          </div>
        </div>
      </div>
      @yield('content')
    </div>
    @include('productDeleteModel')
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    <script src="{{ asset('js/custom.js') }}"></script>
  </body>
</html>

Create productDeleteModel.blade.php file:

After, create productDeleteModel.blade.php file for pure soft delete CRUD Product delete confurm model on this path resources/views

  PHP – Split a String into Array with Delimiter

productDeleteModel.blade.php

<form action="" method="POST" class="product-model-remove-record">
  <div id="custom-width-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="custom-width-modalLabel" aria-hidden="true" style="display: none;">
    <div class="modal-dialog" style="width:55%;">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h4 class="modal-title" id="custom-width-modalLabel">Delete Record</h4>
        </div>
        <div class="modal-body">
          <h4>You Want You Sure Delete This Record?</h4>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default waves-effect remove-data-from-delete-form" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-danger waves-effect waves-light">Delete</button>
        </div>
      </div>
    </div>
  </div>
</form>

Create alert.blade.php file:

And then, create alert.blade.php file in this path resources/views I am create this file for all notification alert like when I am insert data and display success message and failed message or any warning message.

resources/views/alert.blade.php

@if ($errors->any())
<div class="alert alert-danger alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Error Alert!</strong> Please check the form below for errors
</div>
@endif
@if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Success Alert!</strong> <?php echo $message; ?>
</div>
<?php Session::forget('success');?>
@endif
@if ($message = Session::get('error'))
<div class="alert alert-danger alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Error Alert!</strong> <?php echo $message; ?>
</div>
<?php Session::forget('error');?>
@endif
@if ($message = Session::get('warning'))
<div class="alert alert-warning alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Waarning Alert!</strong> <?php echo $message; ?>
</div>
<?php Session::forget('warning');?>
@endif
@if ($message = Session::get('info'))
<div class="alert alert-indo alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  <span aria-hidden="true">×</span>
  </button>
  <strong>Information Alert!</strong> <?php echo $message; ?>
</div>
<?php Session::forget('info');?>
@endif

Create custom.js File:

Now, I am create custom.js file on this path public/js and in this file I am write js source code for out delete confirm model. this js main logic We can use any your laravel 5.7 project or application for delete records with confirmation model.

public/js/custom.js

$(document).ready(function(){
    // For A Delete product Record Popup
    $('.remove-record').click(function() {
        var id = $(this).attr('data-id');
        var url = $(this).attr('data-url');
        var token = CSRF_TOKEN;
        $(".product-model-remove-record").attr("action",url);
        $('body').find('.product-model-remove-record').append('<input name="_token" type="hidden" value="'+ token +'">');
        $('body').find('.product-model-remove-record').append('<input name="_method" type="hidden" value="DELETE">');
        $('body').find('.product-model-remove-record').append('<input name="id" type="hidden" value="'+ id +'">');
    });

    $('.remove-data-from-delete-form').click(function() {
        $('body').find('.product-model-remove-record').find( "input" ).remove();
    });
    $('.modal').click(function() {
        // $('body').find('.product-model-remove-record').find( "input" ).remove();
    });
}); 

Create products Table Migration:

Now, I am create products table migration by run following below command in CMD on terminal.

  CSS Glowing Border Blue Input Focus Highlights

php artisan make:migration create_products_tbl

After runing this command in your CMD(terminal) then one mingration file automatic generated in your this path Like database/migrations/ then here your diplay one new migration file therefor, open it as well as change like thai in this file.

database/migrations/

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

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

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

After change in this Database migration file then run this migration by following simple command in your CMD terminal.

php artisan migrate

Create products Table Model:

And then, create products table model in following path Like as a app/Product.php and add following source code in this file.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    protected $guarded = array();

    public function getProductData()
    {
        return static::orderBy('id', 'desc')->paginate(5);
    }

    public function AddProductData($input)
    {
        return static::create($input);
    }

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

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

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

Create productsController:

Now, create productsController.php file in this path Like app/Http/Controllers and simple data copy this following source code in this file.

app/Http/Controllers/productsController.php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\Product;

class productsController extends HomeController
{
    public function __construct()
    {
        parent::__construct();

        $this->Product = new Product;

        $this->moduleTitleS = 'products';
        $this->dirModuleName = 'products';

        view()->share('dirModuleName',$this->dirModuleName);
        view()->share('moduleTitleS',$this->moduleTitleS);
    }
    
    public function index()
    {
        $data = $this->Product->getProductData();
        
        return view($this->dirModuleName.'.index',compact('data'))
                         ->with('i',0);
    }
    
    public function create()
    {
        return view($this->dirModuleName.'.create');
    }
   
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|max:255',
            'products' => 'required',
        ]);

        $input = array_except($request->all(),array('_token'));

        $this->Product->AddProductData($input);

        \Session::put('success','Product Store Successfully!!');

        return redirect()->route('products.index');
    }

    public function edit($id)
    {
        $data = $this->Product->findProductData($id);

        return view($this->dirModuleName.'.edit',compact('data'));
    }
    
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required|max:255',
            'products' => 'required',
        ]);

        $input = array_except($request->all(),array('_token', '_method'));

        $this->Product->updateProductData($id, $input);

        \Session::put('success','Product Updated Successfully!!');

        return redirect()->route('products.index');
    }
    
    public function destroy($id)
    {
        $this->Product->destroyProductData($id);

        \Session::put('success','Product Delete Successfully!!');

        return redirect()->route('products.index');
    }
}   

Create All View Blade File:

Now, I am create all following Laravel 5.7 blade file one by one

  • 1.)index.blade.php
  • 2.)create.blade.php
  • 3.)edit.blade.php

resources/views/products/index.blade.php File:

Let’s Now, make this file and step by step copy and path following source code in this file for all products listing.

@extends('layouts.app')
@section('content')
<div class="container">
  <div class="row">
    <div class="col-md-10 col-md-offset-1">
      <div class="panel panel-default">
        <div class="panel-heading">
          <div class="row">
            <div class="col-md-10">
              <strong>All products Listing</strong>
            </div>
            <div class="col-md-2">
              <a href="{{ URL::route('products.create') }}" class="btn btn-info pull-right">Add products</a>
            </div>
          </div>
        </div>
        <div class="panel-body">
          <table class="table table-bordered">
            <tr>
              <th>Title</th>
              <th width="500">products Description</th>
              <th width="180" class="text-center">Action</th>
            </tr>
            @if(!empty($data) && $data->count())
            @foreach($data as $key => $value)
            <tr>
              <td>{{ $value->title }}</td>
              <td>
                @if (strlen($value->products) > 100)
                {!! substr(strip_tags(html_entity_decode($value->products)), 0, 100) . '.....' !!}
                @else
                {!! strip_tags($value->products) !!}
                @endif
              </td>
              <td class="text-center">
                <a href="{!! URL::route('products.edit', $value->id) !!}" class="btn btn-success">Edit</a>
                <a data-toggle="modal" data-url="{!! URL::route('products.destroy', $value->id) !!}" data-id="{{$value->id}}" data-target="#custom-width-modal" class="btn btn-danger remove-record">Delete</a>
              </td>
            </tr>
            @endforeach
            @endif
          </table>
        </div>
      </div>
      {!! $data->appends([])->render() !!}
    </div>
  </div>
</div>
@endsection

resources/views/products/create.blade.php File:

After that, create this file for create and insert products records in our database. step by step you all thw source copy this all following code and path in your this file.

  Laravel Simple CRUD Application Script

@extends('layouts.app')
@section('content')
<div class="container">
  <div class="row">
    <div class="col-md-10 col-md-offset-1">
      <div class="panel panel-default">
        <div class="panel-heading">Create Product</div>
        <div class="panel-body">
          <form class="form-horizontal" method="POST" action="{{ route('products.store') }}">
            {{ csrf_field() }}
            <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
              <label for="title" class="col-md-3 control-label">Product Title</label>
              <div class="col-md-7">
                <input id="title" type="text" class="form-control" name="title" value="{{ old('title') }}" required autofocus>
                @if ($errors->has('title'))
                <span class="help-block">
                <strong>{{ $errors->first('title') }}</strong>
                </span>
                @endif
              </div>
            </div>
            <div class="form-group{{ $errors->has('products') ? ' has-error' : '' }}">
              <label for="products" class="col-md-3 control-label">products Description</label>
              <div class="col-md-7">
                <textarea id="products" rows="6" class="form-control" name="products" required>{{ old('products') }}</textarea>
                @if ($errors->has('products'))
                <span class="help-block">
                <strong>{{ $errors->first('products') }}</strong>
                </span>
                @endif
              </div>
            </div>
            <div class="form-group">
              <div class="col-md-7 col-md-offset-3">
                <button type="submit" class="btn btn-success btn-block">
                Submit
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection 

resources/views/products/edit.blade.php

And then, I am create view Blade File edit file for update any data record in our Laravel MySQL database. this Source code like that

 <div class="panel-heading">Edit Product</div>
        <div class="panel-body">
          {{ Form::model($data, ['route' => ['products.update', $data->id], 'method' => 'patch', 'class' =>'form-horizontal']) }} 
          <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
            <label for="title" class="col-md-3 control-label">Product Title</label>
            <div class="col-md-7">
              <input id="title" type="text" class="form-control" name="title" value="{{ $data->title }}" required autofocus>
              @if ($errors->has('title'))
              <span class="help-block">
              <strong>{{ $errors->first('title') }}</strong>
              </span>
              @endif
            </div>
          </div>
          <div class="form-group{{ $errors->has('products') ? ' has-error' : '' }}">
            <label for="products" class="col-md-3 control-label">products Description</label>
            <div class="col-md-7">
              <textarea id="products" rows="6" class="form-control" name="products" required>{{ $data->products }}</textarea>
              @if ($errors->has('products'))
              <span class="help-block">
              <strong>{{ $errors->first('products') }}</strong>
              </span>
              @endif
            </div>
          </div>
          <div class="form-group">
            <div class="col-md-7 col-md-offset-3">
              <button type="submit" class="btn btn-success btn-block">
              Update
              </button>
            </div>
          </div>
          {{ Form::close() }}
        </div>
      </div>
    </div>
  </div>
</div>
@endsection 

Now I am ready to run Laravel Insert Update delete CRUD Project, Therefor run bellow command ro quick run on terminals:

php artisan serve

//Now you can test one by one Laravel route url in your browser like that:
http://localhost:8000/products

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP Laravel MySQL CRUD Application.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.