CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

09 January, 2021

Insert data in laravel

 Programing Coderfunda     January 09, 2021     Insert-Laravel, Laravel     No comments   

 

<?php 
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
<?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

?>
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Sitaare Zameen Par Full Movie Review
     Here’s a  complete Vue.js tutorial for beginners to master level , structured in a progressive and simple way. It covers all essential topi...
  • AI foot tracking model
    I am a student doing a graduation project. I urgently need to deal with this model (I am attaching a link). I've never worked with pytho...
  • Laravel Search String
      Laravel Search String is a package by   Loris Leiva   that generates database queries based on one unique string using a simple and custom...
  • Writing and debugging Eloquent queries with Tinkerwell
    In this article, let's look into the options that you can use with Tinkerwell to write and debug Eloquent queries easier. The post Wr...
  • The token request was rejected by the remote server
    error:invalid_granterror_description:The token request was rejected by the remote server.error_uri: https://documentation.openiddict.com/err...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (69)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • July (4)
  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

Loading...

Laravel News

Loading...

Copyright © CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda