Responsive Advertisement

Laravel Add , Update, Delete in Singal Page CRUD By Ajax Easy Way

Route:

Route::get('/cuisines','backEnd\contentManagement\CuisinesController@index');
Route::post('/data/cuisines','backEnd\contentManagement\CuisinesController@cuisinesList');
Route::match(['get','post'],'/cuisine/add','backEnd\contentManagement\CuisinesController@add');
Route::match(['get','post'],'/cuisine/edit/{cuisine_id}','backEnd\contentManagement\CuisinesController@edit');
//soft-delete of cusisine
Route::match(['get','post'],'/cuisine/delete/{cuisine_id}','backEnd\contentManagement\CuisinesController@delete');

Controller


<?php

namespace App\Http\Controllers\backEnd\contentManagement;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth, Hash;
use App\Cuisine;



class CuisinesController extends Controller
{

    public function index()
        {
            $page = 'cuisines';
            return view('backEnd.contentManagement.cuisines.index', compact('page'));
        }

    public function cuisinesList()
        {

            $draw = @$_POST['draw'];
            $row = @$_POST['start'];
            $rowperpage = @$_POST['length']; // Rows display per page
            $columnIndex = @$_POST['order'][0]['column']; // Column index
            $columnName = @$_POST['columns'][$columnIndex]['data']; // Column name
            $columnSortOrder = @$_POST['order'][0]['dir']; // asc or desc
            $searchValue = @$_POST['search']['value']; // Search value

            $listing = Cuisine::select('*')
            ->whereNull('deleted_at')
            ->skip($_POST['start'])
            ->take($_POST['length']);

            $listing = $listing->orderBy($columnName,$columnSortOrder);

            $recordCount = Cuisine::whereNull('deleted_at')
            ->count();

            $with_filter_count = $listing->count();

            // ----- search
            if($searchValue != ''){

                $listing = $listing->where('name','like','%'.$searchValue.'%');
                $with_filter_count = $listing->count();
            }

            if($with_filter_count == 0){
                $with_filter_count = $recordCount;
            }

            $allRecords = $listing->get()->toArray();

            // Total number of records without filtering
            $totalRecords = $recordCount;

            //Total number of record with filtering
            $totalRecordwithFilter = $with_filter_count;
            $data = array();

            foreach ($allRecords as $key => $value) {

                $joined_on = date('d M, Y', strtotime($value['created_at']));
                $encoded_id = $value['id'];
                // $encoded_id = base64_encode($value['id']);

                $action = '<a href="'.url('/admin/cuisine/edit/'.$encoded_id).'" title="Edit"><i class="fa fa-edit"></i>
                </a>
                <a href="'.url('/admin/cuisine/delete/'.$encoded_id).'" title="Send Credential"><i class="fas fa-trash-alt"></i>
                </a>';

                $data[] = array(
                    "name"=>ucfirst($value['name']),
                    "action"=>$action,
                );
            }
           
            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordwithFilter,
                "aaData" => $data
            );
            echo json_encode($response);
        }

    public function add(Request $request)
        {
            if($request->isMethod('post'))
            {
                $data = $request->all();
                //$id = $this->route('post');
                $validatedData = $request->validate
                ([
                    'name'=>'required|max:20|min:3',
                ]);

                $cusisineData = new Cuisine;
                $cusisineData->name = $data['name'];

                if($cusisineData->save())
                {
                    return redirect('/admin/cuisines')->with('success','Cuisine added successfully');
                }
                else
                {
                    return redirect('/admin/cuisines')->with('errors',COMMON_ERROR);
                }
            }
            $page = 'cuisines';
            return view('backEnd.contentManagement.cuisines.form', compact('page'));
        }

    public function edit(Request $request,$cuisine_id)
        {
            $cuisine_detail = Cuisine::where('id',$cuisine_id)->first();
            if ($request->isMethod('post')){
                $data = $request->all();
                $this->validate($request,[
                    'name'=>'required|max:20|min:3',
                ]);          
                $cuisine_detail->name    = $data['name'];

                if ($cuisine_detail->save()) {
                    return redirect('/admin/cuisines')->with('success','Cuisine Updated Successfully');
                }else{
                    return redirect()->back()->with('errors',COMMON_ERROR);
                }
            }
            $page = 'cuisines';
            return view('backEnd.contentManagement.cuisines.form',compact('page','cuisine_detail','cuisine_id'));
        }

    public function delete($cuisine_id)
        {
            $del = Cuisine::where('id',$cuisine_id)->update(['deleted_at'=> date('Y-m-d h:i:s')]);
            if ($del)
                {
                    return redirect()->back()->with('success','Cuisine deleted successfully');
                }
                else
                {
                    return redirect()->back()->with('errors',COMMON_ERROR);
                }
        }
}

Blade File: index. thats is not main file it is only view file ;

Index.blade.php


@extends('backEnd.layouts.master')
@section('title','categories')
@section('content')

<div class="page-wrapper">
    <div class="page-breadcrumb">
        <div class="row">
            <div class="col-12 d-flex no-block align-items-center">
                <h4 class="page-title">Content Management </h4>
            </div>
        </div>
    </div>
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Categories</h5>
                        <div class="new_add_btn d-flex justify-content-end align-items-center mb-4">
                            <a href="{{ url('admin/category/add') }}" class="btn btn-primary mr-1">Add New</a>

                        </div>
                        <div class="table-responsive">
                            <table id="zero_config2"  class="table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Image</th>                                      
                                        <th>Action</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @include('backEnd.common.footer')
</div>
@endsection
@section('scripts')
<script>
    $('#zero_config2').DataTable({
        "order": [[ 0, "desc" ]],
        'processing': true,
        'serverSide': true,
        'serverMethod': 'post',
        'ajax':{
            'url': "{{ url('admin/data/categories') }}",
            "error": function(reason) {
                console.log(reason);
            }
        },
        "columns" : [
            { data: 'name' },
            { data: 'image' },          
            { data: 'action', name: 'action', orderable: false, searchable: false}
        ]
    });
</script>
@endsection


form.blade.php

Note: this is main file you can edit and update only one file;


<?php
    if(isset($categorieData)){
        $title = 'Edit';
        $form_id = 'CategoryForm';
$image_text = 'Update Image';
        $action  =  url('/admin/category/edit/'.$category_id);
    }else{
        $title = 'Add';
        $form_id = 'CategoryForm';
$image_text = 'Update Image';
        $action  =  url('/admin/category/add');
    }
?>


@extends('backEnd.layouts.master')
@section('title',$title.' Content Management')
@section('content')




<div class="page-wrapper">
<div class="page-breadcrumb">
<div class="row">
<div class="col-12 d-flex no-block align-items-center">
<h4 class="page-title">Content Management</h4>
<div class="ml-auto text-left">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{{ url('admin/categories') }}">Content</a></li>
<li class="breadcrumb-item active" aria-current="page">{{ $title }} category</li>
</ol>
</nav>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card">
<form class="form-horizontal" name="registration" method="post" action="{{ $action }}" id="user_form" enctype="multipart/form-data">
@csrf
<div class="card-body">
<h4 class="card-title">{{ $title }} Category</h4>  
<div class="form-group row">
<label class="col-sm-3 text-right control-label col-form-label">Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="Name" name="name" value="{{ isset($categorieData['name'])? $categorieData['name']: old('name') }}">
</div>
</div>
<label for="image" class="m-t-10"></label>                  
<?php
$image = DefaultImgPath;

if(!empty($categorieData['image'])){
$image = ContentCategoriesImgPath.'/'.$categorieData['image'];
}
?>
<div class="container-fluid" style="padding-left: 270px; padding-bottom: 20px;">
<div>
<img src="{{$image}}" id="old_image" alt="No image" class="img-fluid" width="15%" height="10%" accept=".jpg,.png,.gif,.jpeg">
</div>
<div>
<div class="Upload-img mt-3">
                                   <span class="uploader">
                                       <button type="button" class="btn btn-danger">{{ $image_text }}</button>
                                        <input type="file" name="image" id="img_upload"  class="img_cls">
                                       <!-- <span class="img_load">
                                           <input type="hidden" name="image" id="img_upload"  class="img_cls">
                                       </span> -->
                                   </span>
                               </div>
</div>
</div>
</div>


@if($errors->any())
<div class="form-group row">
<label class="col-sm-3 text-right control-label col-form-label"></label>
<div class="col-sm-7">
   <div class="alert alert-danger">
       <ul>
           @foreach ($errors->all() as $error)
               <li>{{ $error }}</li>
           @endforeach
       </ul>
   </div>
</div>
</div>
@endif


<div class="error">

</div>

<div class="border-top">
<div class="card-body">
@csrf()
<button type="submit" class="btn btn-primary" style="float: right; margin-bottom: 20px">Submit</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
@include('backEnd.common.footer')  
</div>        
@endsection





Post a Comment

0 Comments