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

Related Posts:

  • Insert data in laravel  <?php Route:Route::get('/cuisines','backEnd\contentManagement\CuisinesController@index');Route::post('/data/cuisines','backEnd\contentM… Read More
  • Insert data in laravel <?php Route:Route::get('/cuisines','backEnd\contentManagement\CuisinesController@index');Route::post('/data/cuisines','backEnd\contentMa… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...
  • Enabling authentication in swagger
    I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. S...

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 (68)
  • 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

  • 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)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Locale-aware Number Parsing in Laravel 12.15 - 5/21/2025
  • Handle Fluent Values as Arrays with Laravel's array() Method - 5/18/2025
  • Chargebee Starter Kit for Billing in Laravel - 5/20/2025
  • Streamline Pipeline Cleanup with Laravel's finally Method - 5/18/2025
  • Validate Controller Requests with the Laravel Data Package - 5/19/2025

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