Cannot Save Data - php

I was to Try to save any Invoice Card on Database but it not saved
What's Wrong With my code, I was Try to search to solve this but it not solved
Always Blank to database,
The View Form & Post
The Controller
Use Boostrap 3 from AdminLte Template
<?php
namespace App\Http\Controllers;
use App\Kwitansi;
use Illuminate\Http\Request;
use Haruncpi\LaravelIdGenerator\IdGenerator;
class KwitansiController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$kwitansi = Kwitansi::get();
return view('user.formkwitansi', ['kwitansi' => $kwitansi]);
}
public function store(Request $request)
{
$kwitansi = new Kwitansi;
$id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
$kwitansi->received = $request->received;
$kwitansi->registration = $request->registration;
$kwitansi->course = $request->course;
$kwitansi->trasnportation = $request->trasnportation;
$kwitansi->payment = $request->payment;
$kwitansi->kota = $request->kota;
$kwitansi->register_at = $request->register_at;
$request->validate([
'sum_rp' => 'required',
'sum_text' => 'required',
]);
$sum_rp = $request->registration + $request->course + $request->transportation;
function penyebut($nilai) {
$nilai = abs($nilai);
$huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
$temp = "";
if ($nilai < 12) {
$temp = " ". $huruf[$nilai];
} else if ($nilai <20) {
$temp = penyebut($nilai - 10). " belas";
} else if ($nilai < 100) {
$temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
} else if ($nilai < 200) {
$temp = " seratus" . penyebut($nilai - 100);
} else if ($nilai < 1000) {
$temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
} else if ($nilai < 2000) {
$temp = " seribu" . penyebut($nilai - 1000);
} else if ($nilai < 1000000) {
$temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
} else if ($nilai < 1000000000) {
$temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
} else if ($nilai < 1000000000000) {
$temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
} else if ($nilai < 1000000000000000) {
$temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
}
return $temp;
}
function terbilang($nilai) {
if($nilai<0) {
$hasil = "minus ". trim(penyebut($nilai));
} else {
$hasil = trim(penyebut($nilai));
}
return $hasil;
}
$sum_text = $request->sum_rp;
$kwitansi->sum_rp = $sum_rp;
$kwitansi->sum_text = terbilang($sum_text);
$kwitansi->save();
return redirect('kwitansi')->withSuccess('Added Succesfully');
}
}
The Blade View
Use Form and View in One Page
#extends('layouts.admin')
#section('title', 'Kwitansi')
#section('css')
<!-- DataTables -->
<link rel="stylesheet" href="{{ asset('adminlte/plugins/datatables-bs4/css/dataTables.bootstrap4.css') }}">
#section('js')
<!-- DataTables -->
<script src="{{ asset('adminlte/plugins/datatables/jquery.dataTables.js') }}"></script>
<script src="{{ asset('adminlte/plugins/datatables-bs4/js/dataTables.bootstrap4.js') }}"></script>
<script>
$(function () {
$("#example1").DataTable();
$('#example2').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
});
});
</script>
#endsection
#section('content')
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">DataTable User</h3>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h5><i class="icon fas fa-check"></i> Alert!</h5>
<p>{{ $message }}</p>
</div>
#endif
</div>
<!-- /.card-header -->
<div class="card-body">
<form action="{{ route('kwitansi.store') }}" method="POST" role="form" class="form-horizontal">
#csrf
<div class="form-group row">
<label for="name" class="control-label col-md-2">Terima Dari</label>
<div class="col-md-6">
<input type="text" name="received" class="form-control" placeholder="Received Form" />
</div>
</div>
<div class="form-group row">
<label for="registration" class="control-label col-md-2">Biaya Registrasi</label>
<div class="col-md-6">
<input type="text" name="registration" class="form-control" placeholder="Registration Fee" />
</div>
</div>
<div class="form-group row">
<label for="course" class="control-label col-md-2">Biaya Kursus</label>
<div class="col-md-6">
<input type="text" name="course" class="form-control" placeholder="Course Fee" />
</div>
</div>
<div class="form-group row">
<label for="trasnportation" class="control-label col-md-2">Biaya Transportasi</label>
<div class="col-md-6">
<input type="text" name="trasnportation" class="form-control" placeholder="Transportation Fee" />
</div>
</div>
<div class="form-group row">
<label for="payment" class="control-label col-md-2">Pembayaran Untuk</label>
<div class="col-md-6">
<input type="text" name="payment" class="form-control" placeholder="Payment Of" />
</div>
</div>
<div class="form-group row">
<label for="register_at" class="control-label col-md-2">Tanggal Registrasi</label>
<div class="col-md-6">
<input type="text" name="kota"class="form-control" value="Bandung" disabled hidden>
<input type="date" name="register_at"class="form-control">
</div>
</div>
<button type="submit" class="btn btn-primary" id="btnsubmit">Tambah Data</button>
<button type="reset" class="btn btn-warning" id="btncancel">Cancel</button>
</form>
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr>
<th>No.</th>
<th>received</th>
<th>registration Fee</th>
<th>Course Fee</th>
<th>Transportation Fee</th>
<th>Grand Total</th>
<th>Payment of</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($kwitansi as $k)
<tr>
<td>{{ $k->id }}</td>
<td>{{ $k->received }}</td>
<td>{{ $k->registration }}</td>
<td>{{ $k->course }}</td>
<td>{{ $k->transportation }}</td>
<td>{{ $k->sum_rp }}</td>
<td>{{ $k->payment }}</td>
<td>
{{-- <i class="fas fa-edit"></i>
<i class="fas fa-file"></i>
<form action="{{ route('user.destroy', $u->id)}}" method="post">
#csrf
#method('DELETE')
<button class="btn btn-sm btn-outline-danger" type="submit"><i class="fas fa-trash-alt"></i></button>
</form> --}}
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>No.</th>
<th>received</th>
<th>registration Fee</th>
<th>Course Fee</th>
<th>Transportation Fee</th>
<th>Grand Total</th>
<th>Payment of</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
#endsection
I used form and view in one page are this is the problem
This is my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Kwitansi extends Model
{
// $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
protected $table = 'kwitansis';
protected $fillable = [
'received',
'registration',
'course',
'trasnportation',
'sum_rp',
'payment',
'register_at',
];
protected $primarykey = 'id';
public $increment = false;
protected $keyType = 'string';
}

Remove these lines from your model:
protected $primarykey = 'id';
public $increment = false;
protected $keyType = 'string';

Ok Thanks Guys For Helping, I Have Solved The Problem.
I Only Delete Some function on Controller adn Worked for Me
$request->validate([
'sum_rp' => 'required',
'sum_text' => 'required',
]);
$sum_rp = $request->registration + $request->course + $request->transportation;
function penyebut($nilai) {
$nilai = abs($nilai);
$huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
$temp = "";
if ($nilai < 12) {
$temp = " ". $huruf[$nilai];
} else if ($nilai <20) {
$temp = penyebut($nilai - 10). " belas";
} else if ($nilai < 100) {
$temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
} else if ($nilai < 200) {
$temp = " seratus" . penyebut($nilai - 100);
} else if ($nilai < 1000) {
$temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
} else if ($nilai < 2000) {
$temp = " seribu" . penyebut($nilai - 1000);
} else if ($nilai < 1000000) {
$temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
} else if ($nilai < 1000000000) {
$temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
} else if ($nilai < 1000000000000) {
$temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
} else if ($nilai < 1000000000000000) {
$temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
}
return $temp;
}
function terbilang($nilai) {
if($nilai<0) {
$hasil = "minus ". trim(penyebut($nilai));
} else {
$hasil = trim(penyebut($nilai));
}
return $hasil;
}
$sum_text = $request->sum_rp;
$kwitansi->sum_rp = $sum_rp;
$kwitansi->sum_text = terbilang($sum_text);
Only Delete This function and add it to Helper Class

Related

Filter table data upon date range selection in laravel and vuejs

Hello I'm following a Shopify Admin REST API and laravel related tutorial.
Currently I have following laravel function to fetch some data from Shopify REST API.
public function bestSelling(Request $request)
{
$organisation = Organisation::findOrFail(Auth::user()->organisation);
// Check if the data is already in the cache
$products = Cache::get('best-selling-products');
if ($products) {
return view('reports.shopify.best-selling', ['products' => $products,'organisation'=>$organisation]);
}
$startDate = $request->input('start_date');
$endDate = Carbon::parse($request->input('end_date'))->addDay()->format('Y-m-d');
if (!$startDate) {
$startDate ='2000-01-01' ;
}
if(!$endDate) {
$endDate = Carbon::now()->format('Y-m-d');
}
// Best selling products list
// Set up the Shopify API request to get a list of all orders placed today
$url = "https://APIKEY:AUTHCODE#somestore.myshopify.com/admin/api/2022-10/orders.json?status=any&created_at_min=$startDate&created_at_max=$endDate"; // append the query to the URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Shopify-Access-Token:AUTHCODE', // access token
]);
// Send the request
$response = curl_exec($ch);
$response = json_decode($response);
curl_close($ch);
// Group and sort the orders by product to find the best selling products
$productCounts = [];
foreach ($response->orders as $order) {
foreach ($order->line_items as $item) {
if (!isset($productCounts[$item->product_id])) {
$productCounts[$item->product_id] = 0;
}
$productCounts[$item->product_id] += $item->quantity;
}
}
arsort($productCounts);
$topProductIds = array_keys(array_slice($productCounts, 0, 50, true)); // get the top 10 best selling products
// Get the details for the top products
$products = [];
foreach ($topProductIds as $productId) {
$url = "https://APIKEY:AUTHCODE#somestore.myshopify.com/admin/api/2022-10/products/$productId.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Shopify-Access-Token: AUTHCODE', // access token
]);
// Send the request
$response = curl_exec($ch);
$response = json_decode($response);
curl_close($ch);
// Check if the product has an image and a title
if (isset($response->product->image) && !empty($response->product->image)) {
$image = $response->product->image->src;
} else{
$image = null;
}
if (isset($response->product->title) && !empty($response->product->title)) {
$title = $response->product->title;
} else {
$title = "Untitled Product";
}
if (isset($response->product->vendor) && !empty($response->product->vendor)) {
$vendor = $response->product->vendor;
} else {
$vendor = "N/A";
}
if (isset($response->product->product_type) && !empty($response->product->product_type)) {
$product_type = $response->product->product_type;
} else {
$product_type = "N/A";
}
// Calculate the gross sales value and total returns
$grossSales = 0;
$totalDiscounts = 0;
$totalReturns = 0;
foreach ($response->product->variants as $variant) {
if ($variant->inventory_quantity > 0) {
$grossSales += $variant->price * $productCounts[$productId];
$totalDiscounts += $variant->compare_at_price - $variant->price;
$totalReturns += ($variant->compare_at_price * $productCounts[$productId]) - ($variant->price * $productCounts[$productId]);
}
}
$netSales = $grossSales - $totalReturns - $totalDiscounts;
// Add the product details to the list of top products
$productDetails = [
'id' => $productId,
'title' => $title,
'image' => $image,
'vendor'=>$vendor,
'product_type'=>$product_type,
'gross_sales'=> round($grossSales,2),
'total_sales' => $productCounts[$productId],
'total_discounts' => round($totalDiscounts, 2),
'total_returns' => round($totalReturns, 2),
'net_sales' => round( $netSales, 2)
];
array_push($products, $productDetails);
}
// Store the data in the cache for 60 minutes
Cache::put('best-selling-products', $products, now()->addMinutes(60));
return view('reports.shopify.best-selling', ['products' => $products,'organisation'=>$organisation]);
}
This is my resources/views/reports/shopify/best-selling.blade.php
#extends('layouts.app')
#section('content')
<div id="app">
<best-selling :products="{{ json_encode($products) }}"></best-selling>
</div>
#endsection
And following is my web.php
Route::get('/reports/shopify/best-selling', 'ShopifyReportsController#bestSelling')->name('reports.shopify.best-selling');
And This is my front end component, BestSelling.vue
<template>
<div class="container">
<h3 class="mb-4">Best Selling Products</h3>
<div class="row">
<div class="col-sm-12 col-12">
<div class="table-group-top">
<vue-ctk-date-time-picker v-model="dateRange" :format="'YYYY-MM-DD'" :only-date="true" :range="true" :placeholder="'Select a date range'"></vue-ctk-date-time-picker>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="45" height="32" viewBox="0 0 42 45">
</svg>
<a data-target="#demo-default-modal" data-toggle="modal" style="cursor:pointer;"><i class="feather icon-settings f-30"></i></a>
<a id="export_all" style="cursor:pointer;"><i class="feather icon-download-cloud f-30"></i></a>
</div>
</div>
</div>
<div class="modal fade" id="demo-default-modal" role="dialog" tabindex="-1" aria-labelledby="demo-default-modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="col border-bottom">
<h4 class="modal-title">Columns</h4>
</div>
<div class="form-check form-check-inline mb-3" v-for="col in columns" :key="col">
<input class="form-check-input" type="checkbox" :id="col" :value="col" v-model="selectedColumns">
<label class="form-check-label" :for="col">{{ col }}</label>
</div>
</div>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" placeholder="Search products" v-model="searchQuery">
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th v-if="selectedColumns.includes('id')">Product ID</th>
<th v-if="selectedColumns.includes('title')">Product Name</th>
<th v-if="selectedColumns.includes('vendor')">Vendor</th>
<th v-if="selectedColumns.includes('product_type')">Product Type</th>
<th v-if="selectedColumns.includes('gross_sales')">Gross Sales</th>
<th v-if="selectedColumns.includes('total_discounts')">Discounts</th>
<th v-if="selectedColumns.includes('total_returns')">Returns</th>
<th v-if="selectedColumns.includes('net_sales')">Net Sales</th>
<th v-if="selectedColumns.includes('total_sales')">No Of Items Sold</th>
</tr>
</thead>
<tbody>
<tr v-for="product in paginatedProducts" :key="product.id">
<td v-if="selectedColumns.includes('id')">{{ product.id }}</td>
<td v-if="selectedColumns.includes('title')">{{ product.title }}</td>
<td v-if="selectedColumns.includes('vendor')">{{ product.vendor }}</td>
<td v-if="selectedColumns.includes('product_type')">{{ product.product_type }}</td>
<td v-if="selectedColumns.includes('gross_sales')">{{ product.gross_sales }}</td>
<td v-if="selectedColumns.includes('total_discounts')">{{ product.total_discounts }}</td>
<td v-if="selectedColumns.includes('total_returns')">{{ product.total_returns }}</td>
<td v-if="selectedColumns.includes('net_sales')">{{ product.net_sales }}</td>
<td v-if="selectedColumns.includes('total_sales')">{{ product.total_sales }}</td>
</tr>
</tbody>
</table>
<!-- Pagination -->
<div class="d-flex justify-content-center">
<nav>
<ul class="pagination">
<li class="page-item" :class="{disabled: currentPage === 1}">
<a class="page-link" href="#" aria-label="Previous" #click.prevent="currentPage = currentPage - 1">
<span aria-hidden="true">«</span>
</a>
</li>
<li v-for="pageNumber in totalPages" :key="pageNumber" class="page-item" :class="{active: currentPage === pageNumber}">
<a class="page-link" href="#" #click.prevent="currentPage = pageNumber">{{ pageNumber }}</a>
</li>
<li class="page-item" :class="{disabled: currentPage === totalPages}">
<a class="page-link" href="#" aria-label="Next" #click.prevent="currentPage = currentPage + 1">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
<!---->
</div>
</template>
<script>
export default {
props: {
products: {
type: Array,
required: true,
},
columns: {
type: Array,
default: () => ['id', 'title', 'vendor','product_type','gross_sales','total_discounts','total_returns','net_sales','total_sales']
}
},
data() {
return {
selectedColumns: this.columns,
searchQuery: '', // The search term entered by the user
currentPage: 1,
itemsPerPage: 10,
dateRange: {
start: null,
end: null
}
}
},
computed: {
filteredProducts() {
return this.products.filter(product => {
// Check if the search term is present in any of the selected columns
return this.selectedColumns.some(column => {
return String(product[column]).toLowerCase().includes(this.searchQuery.toLowerCase());
});
});
},
totalPages() {
return Math.ceil(this.filteredProducts.length / this.itemsPerPage);
},
paginatedProducts() {
const startIndex = (this.currentPage - 1) * this.itemsPerPage;
const endIndex = startIndex + this.itemsPerPage;
return this.filteredProducts.slice(startIndex, endIndex);
},
},
};
</script>
Here, every thing works fine.
And This is my app.js
import BestSelling from './components/reports/shopify/BestSelling.vue';
const app = new Vue({
el: '#app',
components: {
ReportsShopifyIndex,``your text``
BestSelling,
},
});
BUT
I'm struggling to filter my table data upon the date range selection....
How can I filter my table data upon the date range(start and end dates) selection...

Handle a list of files over laravel CRUD

I'm working on a form where you have to enter all information you need and at the end, on save all information will be saved at the same times. The form have a list of images where you can add, change and delete pictures.
The way it was made is that all inputs refer to the name carousels[]. Adding the file is alright, the problem is that this way I have no way to identify in backend which file I have to delete or change.
I'm wondering if any Laravel master know a better way to handle a list of files over a form the way a need it to work. So I would be able to add new images, replace an old image by a new one and/or delete a specific image.
There are the pieces of code I'm working with.
Frontend:
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="carrousels[]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Backend
public function update(UpdateRequest $request)
{
try {
$id = $request->id;
$carrouselFolder = config('constants.DEFAULT.UPLOAD_FOLDERS.CARROUSEL');
$carrousels = [];
Log::debug($request->carrousels);
if ($request->carrousels) {
foreach ($request->carrousels as $image) {
if (!empty($image)) {
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
}
return redirect()->to(route('...'))
->with('toastSuccess', '...');
} catch (\Exception $e) {
return redirect()->back()->with('toastError', $e->getMessage());
}
}
send another parameter with old carousel, retrive it in controller then if both not empty, delete the old image . you can try this
View code
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="text" name="oldcarrousels[{{$i}}]" value="{{ !empty($carrousel[$i]) ?$carrousel[$i] :'' }}">
<input type="file" name="carrousels[{{$i}}]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Controller code
foreach ($request->carrousels as $in=>$image) {
if (!empty($image)) {
if (!empty($request->oldcarrousels[$in]) || $request->oldcarrousels[$in]!='') {
//image deleting code here
}
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}

(Undefined offset:0) can't generate more data to trouble shoot

This morning my web app was working. After a few posts were made I tried to login and get the Undefined offset:0 error.
The only information I'm getting from Laravel is that it's in the file path laravel\framework\src\Illuminate\Support\Collection.php
On this file it's saying the error is on line 1688:
public function offsetGet($key)
{
return $this->items[$key];
}
Based on what I found online the issue is related to a bad data call. Perhaps trying to pull data that doesn't exist. I have looked through my database and last 4 Posts and Comments did not have any file attachments so I am not sure where to start looking.
Additionally, the code was written a few years ago by a coworker which makes it more difficult for me to decipher.
Here is my blade file:
#if(app('request')->input('gid'))
<input type="hidden" class="groupid_SeeMore" value="{{app('request')->input('gid')}}"/>
#endif
#foreach($timeline as $post)
<?php
/** the Below Script will grab all Group Names that go with the post and combine into a single stirng **/
$groups= array();
if(strpos($post->grouppermissions,"|")===false){
foreach(explode(',',$post->grouppermissions) as $id){
if($id!=""){
$group = DB::table('groups')->where('groupid','=',$id)->get();
// $groups[] .= $group[0]->name;
$groups[].=explode('|',$group[0]->name)[0];
}
}
}elseif(strpos($post->grouppermissions,"|")!==false){
foreach(explode(',',$post->grouppermissions) as $group){
if($group!="")$groups[].=explode('|',$group)[0];
}
}
$groups=implode(',',$groups);
?>
#if($post->status==0)
<div id="{{$post->id}}" class="Post_Container {{$post->type}} {{$post->type}}{{$post->id}}">
#endif
#if($post->status==1)
<div id="{{$post->id}}" class="Post_Container_Two {{$post->type}} {{$post->type}}{{$post->id}}"><center><p id="cldpsttxt">This post has been closed</center>
#endif
#if($post->favorite==0)
<div class="Post_Header Post_CCthbckgrnd" id="Post_Header{{$post->id}}">
#endif
#if($post->favorite==1)
<div class="Post_Header Post_CCthbckgrnd_Two" id="Post_Header{{$post->id}}"><center><p id="fvrtpsttxt">This post has been Favorited</center>
#endif
<input type="hidden" class="lastid" value="{{$post->id}}"/>
<input type="hidden" class="recent_comment" value="{{$post->recent_comment}}"/>
<div class="Profile_Picture_Container">
<div class="Profile_Picture"><img style="width:100%; height:100%;" src="https://www.vqventure.com/{{$post->pinfo[0]->img}}"/></div>
</div>
#if($groups !="")
<div class="Ginfo">
<center>
<!-- Below the if statement looks for posts with only one group permission-->
#if(strpos($groups, ",") === false)
<b>{{$groups}}</b>
#endif
<!-- Below the if statement looks for posts with multiple group permissions-->
#if(strpos($groups, ",") !== false)
<?php
$key = -1;
$perm = explode(',',$post->grouppermissions);
?>
#foreach(explode(',',$groups) as $group)
<?php $key++;?>
#if($group!="")
<b>{{$group}}</b>
#endif
#endforeach
#endif
</center>
</div>
#endif
<div class="Username_Container">
<div class="Username_Location">
<!--This will be the owner of the post name, for a business it will be the employee name-->
<div class="Username"><b>{{$post->pinfo[0]->name}}</b></div>
</div>
</div>
#if($post->bid != 0 && $post->bid==$user->bid || $post->bid==0 && $post->owner == $user->email)
<div class="Favorite_Container">
<button id="favorite" class="favorite{{$post->id}}" type="{{$post->favorite}}" type2="Timeline"value="{{$post->id}}"></button>
<button id="openclose" class="status{{$post->id}}" type="{{$post->status}}" type2="Timeline" value="{{$post->id}}"></button>
#if($user->bid!=0)
<div class="keywordTypes">
<select class="keywordType" id="{{$post->id}}">
<?php
$cat=$post->category;
if($cat=="")$cat="No category";
?>
<option value="{{$post->category}}" selected>{{$cat}}</option>
#foreach(explode('#$#',$types) as $type)
#if($type!="")<option value="{{$type}}">{{$type}}</option>#endif
#endforeach
</select>
</div>
#endif
</div>
#endif
<b style="position:absolute; top:10%; right:22%;">#{{$post->id}}</b>
#if($post->bid != 0 && $user->admin==1 && $post->bid==$user->bid || $post->owner == $user->email )
<div class="Delete_Button_Container">
<button class="PostDeleteButton" value="{{$post->id}}" id="DeleteMainBTN"></button>
</div>
#endif
</div>
<center>
<!-- Video -->
#if($post->videos!="[]")
<div class="Post_ContentContainer">
<div class="Post_Thumbnail_Container" pid="{{$post->id}}">
<a class="watchVideo" type="" id="{{$post->videos[0]->url}}">
<center> <div class="Post_Thumbnail">
<?php
$vpic = substr($post->videos[0]->url,0,-3)."jpg";
$vpic2 = str_replace("_correted","",$vpic);
?>
<img style="width:100%; height:100%;"src="https://www.vqventure.com/{{$vpic}}" onerror="this.src='https://www.vqventure.com/{{$vpic2}}'" class="video_thumbnail"/>
</div></center>
</a>
</div>
</div>
#endif
<!-- PDF -->
#if($post->else!="[]")
#if($post->else[0]->pics!="" || $post->else[0]->pdf!="")
<div class="Post_ContentContainer">
<div class="Post_Thumbnail_Container" pid="{{$post->id}}">
#if($post->else[0]->pdf!="")
<center><div class="Post_Thumbnail"><a id="wtfPDF" href="https://www.vqventure.com/<?php echo explode('$!$',$post->else[0]->pdf)[0];?>"><img id="PDF_postview" src="https://www.vqventure.com/imgs/pdf.jpeg"/></a></div></center>
#endif
<!-- Images -->
#if($post->else[0]->pics!="")
<center>
<div>
<ul class="Post_Thumbnail" style="list-style-type: none;" id="IMAGES">
#foreach(explode("$!$",$post->else[0]->pics) as $file)
#if($file !="")
<li><img id="IMG_postview" pid="{{$post->id}}"src="https://www.vqventure.com/{{$file}}" class="IMG_postview{{$post->id}}"/></li>
#endif
#endforeach
</ul>
</div>
</center>
#endif
</div>
</div>
<!--This is the end of if pics and pdf-->
#endif
#endif
</center>
<div class="Post_Info_Container2 Post_CCthbckgrnd">
<div class="Post_Info_Header">
<div class="Date_Container">
<!--Input the Date here -->
<?php
$date= explode(' ',$post->timestamp)[0];
$time= explode(" ",$post->timestamp)[1];
?>
<div class="Date"><center><b>{{$date}}</b></center></div>
</div>
<div class="VidTime_Container">
<!--Input the length of the video here -->
<div class="VidTime"><center></center></div>
</div>
<div class="TimeStamp_Container">
<!--Input the TimeStamp here -->
<div class="TimeStamp"><center><b>{{$time}}</b></center></div>
</div>
</div>
#if($post->videos!="[]")
<div class="Post_Title_Container">
<div class="Post_Title_Name"><center><b>Title:</b></center></div>
<div class="Post_Title">{{$post->videos[0]->title}}</div>
</div>
#endif
<div class="Post_Description_Container">
<div class="Post_Description_Name"><center><b>Description:</b></center></div>
<div class="Post_Description">
#if($post->videos!="[]") {!!nl2br(e($post->videos[0]->description)) !!}
#else
<p>{!! nl2br(e($post->else[0]->post)) !!}</p>
#endif</div>
</div>
</div>
#if($showComments=="yes")
<div class="Post_CommentContainer" id="Make_Comment{{$post->id}}">
<textarea class="Post_Comment_TextContainer Post_Comment_TextContainer{{$post->id}}" placeholder="Comment" maxlength="300" rows="2" onkeydown="expandtext(this);" ></textarea>
<input type="hidden" class="gperms{{$post->id}}" value="{{$post->grouppermissions}}"/>
<button class="ChooseFile"><label id="CF" for="CFile{{$post->id}}"></label> <input type="file" name="imgs[]" class="CFile" id="CFile{{$post->id}}" multiple/></button>
<input type="hidden" value="{{ csrf_token() }}" class="CToken{{$post->id}}"/>
<div class="Post"><button id="Pst" pid="{{$post->id}}" ></button></div>
</div>
#if($post->comments!="[]")
<div class="Post_CommentFeedContainer Post_CommentFeedContainer{{$post->id}}">
#foreach($post->comments as $comment)
#if($comment->owner==$user->email)
<div class="Owner_CommentContainer" id="CommentId{{$comment->id}}">
<div class="OCC_Left">
<div class="C_Owner_Name"><center>{{$comment->info[0]->name}}</center></div>
</div>
<div class="OCC_Right">
<div class="C_TimeStamp"><center>{{$comment->timestamp}}</center></div>
#if($post->bid != 0 && $post->bid==$user->bid || $post->bid==0 && $comment->owner == $user->email)
<button class="Delete_Button" value="{{$comment->id}}" id="C_dltbtn" type="Timeline"></button>
#endif
</div>
<div id="CTwo">{!!nl2br(e($comment->comment)) !!}</div>
#if($comment->files!="")
<div class="Owner_Media_Container CommentImages" cid="{{$comment->id}}">
#foreach(explode('#%%#',$comment->files) as $file)
#if(strpos($file, '.pdf') === false && $file!="")<div class="Media_Thumbnail"><img style="width:100%; height:100%;" src="https://www.vqventure.com/{{$file}}" class="CImage{{$comment->id}}"/></div>
#elseif(strpos($file, '.pdf') !== false)<div class="Media_Thumbnail"><img style="width:100%; height:100%;" src="https://www.vqventure.com/imgs/pdf.jpeg"/></div>
#endif
#endforeach
</div>
#endif
</div>
#endif
#if($comment->owner!=$user->email)
<div class="Guest_CommentContainer CommentImages" id="CommentId{{$comment->id}}" cid="{{$comment->id}}">
<div class="GCC_Left">
#if($comment->files!="")
<div class="Guest_Media_Container">
#foreach(explode('#%%#',$comment->files) as $file)
#if(strpos($file, '.pdf') === false && $file!="")<div class="Media_Thumbnail" ><img style="width:100%; height:100%; " src="https://www.vqventure.com/{{$file}}" class="CImage{{$comment->id}}"/></div>
#elseif(strpos($file, '.pdf') !== false)<div class="Media_Thumbnail" ><img style="width:100%; height:100%; " src="https://www.vqventure.com/imgs/pdf.jpeg"/></div>
#endif
#endforeach
</div>
#endif
#if($comment->files!="")
<div class="C_TimeStamp_Guest_Two"><center>{{$comment->timestamp}}</center></div>
#endif
#if($comment->files=="")
<div class="C_TimeStamp_Guest"><center>{{$comment->timestamp}}</center></div>
#endif
</div>
<div class="GCC_Right">
<div class="C_Guest_Name"><center>{{$comment->info[0]->name}}</center></div>
#if($post->bid != 0 && $post->bid==$user->bid && $user->admin==1|| $post->bid==0 && $comment->owner == $user->email)
<button class="Delete_Button" value="{{$comment->id}}" id="C_dltbtn"></button>
#endif
</div>
<div id="COne">{!! nl2br(e($comment->comment)) !!}</div>
</div>
#endif
#endforeach
</div>#endif
#if($post->comments!="[]") <div class="ExpandComment_Container" ><center><div class="Display_AllComments"><button class="Show_All_Comments" id="{{$post->id}}" action=1>Expand Comments...</button></div></center></div> #endif
#endif
</div>
<div id="loading-image" style="display:none; top: 10px; position:relative;"><i>Uploading Comment Please wait....</i></div>
#endforeach
And here is my controller:
public function timeline(Request $request){
if(!isset($this->user->email)){
if(!$request->queryType)return redirect('/');
}
if(isset($this->user->email)){
$email = $this->user->email;
// This needs to query where permissions are equal to the email and the owner = email
$mygroups= groups::where('owner','=',$email)->orwhere('groupadmin','LIKE',"%$email%")->orwhere('members','LIKE',"%$email%")->get();
$groups= "";
foreach($mygroups as $group){
if($group!="")$groups.=','.$group->groupid."$!$".$group->name;
}
$groups=explode(',',$groups);
$timeline = timeline::with('else','videos','comments');
if(!$mygroups->isEmpty()){
$timeline = $timeline->where(function ($query) use($groups) {
for ($i = 0; $i < count($groups); $i++){
if($groups[$i]!=""){
$gid=explode('$!$',$groups[$i])[0];
$gname = explode('$!$',$groups[$i])[1];
$query->orWhere('grouppermissions', 'like', '%' . $gid .'%')
->orWhere('grouppermissions', 'like', '%' . $gname .'%');
}
}
});
$timeline=$timeline->orwhere('owner','=',$this->user->email);
}
if($mygroups->isEmpty()) $timeline=$timeline->where('owner','=',$this->user->email);
if($request->queryType=="Original")$timeline=$timeline->orderBy('id','desc');
if($request->queryType=="Recent" || !$request->queryType)$timeline = $timeline->orderBy('recent_comment','desc')->orderBy('timestamp','desc');
$timeline=$timeline->limit(15)->get();
foreach($timeline as $g){
//THis is for grab business or user info for a post , maynot need it
$pinfo = user::where('email','=',$g['owner']);
$pinfo = $pinfo->get();
$g['pinfo']=$pinfo;
if($g['pinfo'][0]['name']==null)$g['pinfo'][0]['name']=$g['pinfo'][0]['companyname'];
$g['type']="";
foreach($g['comments'] as $c){
$info = user::select("name","img","phone")->where('email','=',$c['owner']);
$info = $info->limit(1)->get();
$c['info']=$info;
$ctimestamp = strtotime($c['timestamp']);
$cdate = new DateTime("#".$ctimestamp); // will snap to UTC because of the
$cdate->setTimezone(new DateTimeZone('America/New_York'));
$c['timestamp']=$cdate->format('Y-m-d H:i:s');
}
$timestamp = strtotime($g['timestamp']);
$date = new DateTime("#".$timestamp); // will snap to UTC because of the
$date->setTimezone(new DateTimeZone('America/New_York'));
$g['timestamp']=$date->format('Y-m-d H:i:s');
}
//if($this->user->admin==1){
//the $list will need to be the businesses branches data exploded by ','
$branches = DB::table('users')
->wherein('email',explode(',',$this->user->branches))->select('bid','email','name')
->get();
// The next few lines are for invitessent
// }
$sess= $this->user->invitessent;
$emails = explode(",",$sess);
$info = array();
foreach($emails as $email){
$test =user::select("name","img")->where('email','=',$email)->limit(1)->get();
if(!$test->isEmpty())$info[]=$test;
}
$website = $this->user->website;
$posts = DB::table('inquiry')->select('*')->where('bid','=', $this->user->bid)->latest()->get();
$types="";
if($this->user->bid!=0){
$biz= user::select('keywords')->where(array(['bid','=',$this->user->bid],['admin','=',1]))->limit(1)->get();
$types = $biz[0]->keywords;
}
if(!$request->queryType)return view('layouts.Timeline',['timeline'=>$timeline,'types'=>$types,'branches'=>$branches, 'posts'=>$posts ,'showComments'=>'yes','user'=>$this->user,'gp_admins'=>'','gp_members'=>'','type'=>'timeline']);
if($request->queryType)return view('includes.Timeline_Posts',['timeline'=>$timeline,'types'=>$types,'user'=>$this->user,'showComments'=>'yes']);
}
}
In addition to fixing the issue and allowing users to access their data, I am hoping someone can help me understand what caused the issue in the first place.
The entire project is in the process of being re-built and I would like to avoid issues with the revamp from lessons learned on this structure. However, I need a quick fix to get it back online until we complete the revamp.
UPDATE:
I changed the code to use ->first instead of [0] but its still giving the same issue. I think the issue is related to the following line of code but not sure how....
<?php
$key = -1;
$perm = explode(',',$post->grouppermissions);
?>
#foreach(explode(',',$groups) as $group)
<?php $key++;?>
So far I have not been able to get any progress...

Laravel datatable. Illegal string offset 'start'

I have a datatable that works great. However, on the last column I have a button which should do another query and then build a second datatable, based on these results.
As you can see on the following example, when I click on the button 'searchMom' in the first row, it should run a query based on john newman´s mother('mary newman') and put the results on the panel called "Mom".
But it´s not working.
Please see the image and the code below:
View: viewFamily.blade.php
<div class="row">
<div class="col-md-12" id="rowFamily01">
<div class="panel">
<div class="panel-heading">
<div class="box-tools pull-right">
<button type="button" class="btn btn-xs panel_expand"><i class="material-icons md-18">expand_less</i></button>
</div>
<div class="panel-title">Find a person</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-9">
<div class="form-group">
<label class="control-label" for="inputPersonSearch" >Search: </label>
<input id="inputPersonSearch" class="form-control" type="text" name="inputPersonSearch" form="formPerson">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="control-label" for="btnPersonSearch" style="color: white;">Search:</label>
<button id="btnPersonSearch" class="form-control btn btn-success" type="submit" title="Search" form="formPerson">Search</button>
</div>
</div>
</div>
<div class="row" style="width:100%; margin-left: 0%;">
<div class="col-md-12 datatable" id="datatable-main">
</div>
</div>
</div>
</div>
</div>
</div>
routes: diego_routes.php
Route::group(['prefix' => 'diego', 'namespace' => 'Diego'], function () {
Route::get("/", "DiegoController#index")->name("index");
Route::get("viewFamily", "DiegoController#viewFamily")->name("viewFamily");
Route::post("searchPerson", "DiegoController#searchPerson")->name("searchPerson");
Route::get("searchMom/{mom}", "DiegoController#searchMom")->name("searchMom");
});
controller: DiegoController.php
public function searchMom($mom){
$input = $mom;
//dd($input);
//begining select query
$query = TD_CP_CIDADAO::where('CID_INT_ID_CIDADAO', '>=', "0");
if(!empty($input["filtro"])){
foreach($input["filtro"] as $k=>$v){
if(!empty($k) and !empty($v)){
//$searchValues = preg_split('/,/', $v, -1, PREG_SPLIT_NO_EMPTY);
$searchValues = array_map('trim', $v);
//dd($searchValues);
$query->where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('CID_STR_DS_NOME', 'like', "%{$value}%");
}
});
}
}
}
//order data
if(!empty($input["order"]) and count($input["order"]) > 0)
{
foreach($input["order"] as $v){
$position = $v["column"];
$column = $input["columns"][$position]["data"];
$dir = !empty($v["dir"])? $v["dir"] : "asc";
$query->orderBy($column, $dir);
}
}
//other params...
$query->skip($input["start"])->take($input["length"]);
$json_data["data"] = $query->get()->toArray();
$json_data["recordsTotal"] = $query->count();
$json_data["recordsFiltered"] = $json_data["recordsTotal"];
$json_data["draw"] = $input["draw"];
return response()->json($json_data);
}
javascript: diego.js
$(document).on("click", ".btnMom", function(e){
e.preventDefault();
$("#newPanels").empty();
$("#newPanels").append(panelMom);
$("#datatable-mom").append(tableMom);
$("#datatable-mom").css("font-size", "12px");
if($.fn.dataTable.isDataTable('table#tbMom')){
$("table#tbMom").DataTable().destroy();
}
$.fn.dataTable.ext.errMode = 'throw';
var filtros = $(this).serializeArray().reduce(function(a, x) { a[x.name] = x.value; return a; }, {});
var options = {
serverSide: true,
processing: true,
retrieve: true,
ajax: {
dataSrc: 'data',
url : $(this).data("url"),
type: 'get',
async: false,
data: {filtro:filtros}
},
columns : columnsMom,
lengthMenu : [ 5, 10, 25 ]
};
$("table#tbMom").DataTable(options);
});
var columnsMom = [
{ data: 'CID_INT_ID_CIDADAO', visible:false},
{ data: 'CID_STR_DS_NOME'},
{ data: 'CID_DAT_DT_NASCIMENTO',
render: function(data, type, row){
return converterData(data);
}, className: "text-center"},
{ data: 'CID_STR_NM_MAE'},
{ data: 'CID_STR_NM_PAI'},
{ data: 'CID_INT_NR_RG', className: "text-center"},
{ data: 'CID_INT_NR_CPF', className: "text-center"},
{ data: 'acao',
render: function(data, type, row, meta){
var b0 = '\n\
\n\
';
return b0;
},orderable: false, className: "text-center"
}];
var panelMom =
`
<div class="panel" id="panelMom">
<div class="panel-heading">
<div class="box-tools pull-right">
<button type="button" class="btn btn-xs panel_expand"><i class="material-icons md-18">expand_less</i></button>
<button type="button" class="btn btn-xs panel_remove"><i class="material-icons md-18">close</i></button>
</div>
<div class="panel-title">Mom</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12 datatable conteudod" id="datatable-mom">
</div>
</div>
</div>
</div>
`;
var tableMom =
`
<table id="tbMom" class="table table-hover compact" cellspacing="0" width="100%" >
<thead>
<tr>
<th class="hidden">ID</th>
<th>NAME</th>
<th>DOB</th>
<th>MOM</th>
<th>DAD</th>
<th class="text-center">DOC #</th>
<th class="text-center">FIELD #</th>
<th class="text-center">ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
`;
The error message:
The line 219 (controller) shown in error message:
Results on "dd($input)" inside the controller:
I appreciate any help to solve this problem!
Thank you!
You're setting the value of $input to the value of $mom, which is the last value in your URL, so mom equals Mary Newman but the rest of your code expects $input to be an array of parameters like order, columns and start.
You should assign the value of $input as the request parameters, e.g:
public function searchMom($mom)
{
$input = request()->input();
}
Alternatively instead of $input being an array you could use the Request object directly, e.g:
public function searchMom(Request $request, $mom)
{
$request->order;
$request->columns;
$request->start;
}

Cannot retrieve data via checkbox in laravel

I have a project in which i want to retrieve value from database via checkbox. But i cannot do this.
My controller code is
public function browseProfessionals() {
$userRoles = UserRole::whereIn('role_id', [2,3])->get();
$users = array();
$showUsers = array();
foreach ($userRoles as $userRole) {
$users[] = User::find($userRole->user_id);
}
$valid_providers = array();
$all_providers = array();
$user_role_all_providers = UserRole::where('role_id', 2)->get();
foreach ($user_role_all_providers as $user_role_all_provider) {
$all_providers[] = User::where('id', $user_role_all_provider->user_id)->first();
}
foreach ($all_providers as $all_provider) {
$user = User::where('id', $all_provider->id)->first();
$user_detail = UserDetail::where('user_id', $all_provider->id)->first();
$user_meeting = UserMeeting::where('user_id', $all_provider->id)->first();
$user_time = UserTime::where('user_id', $all_provider->id)->first();
if (!empty($user_detail->avatar) && !empty($user_meeting->meeting_id) && !empty($user_time->hour_rate) && $user->is_active == 1 && $user->is_deleted == 0) {
$valid_providers[] = $all_provider;
}
}
$data = [
'valid_providers' => $showUsers,
'industries' => Industry::where('is_active', 1)->where('is_deleted', 0)->get(),
'degrees' => UserDegree::where('degree_id', $user->degree_id)->get(),
];
return view('frontends.browse-professionals', $data);
}
My Blade template is
#extends ('frontends.layouts.app')
#section ('main')
<div id="content-block" class="margin-top-140">
<div class="container-fluid block custom-container">
<h3 class="block-title">Browse Professionals</h3>
<div class="block-subtitle"><span>Connect</span> <span>Learn</span> <span>Inspire</span> <span>Thrive</span> </div>
<div class="row">
{{--<form action="" method="post">--}}
<div class="col-md-2 left-feild">
<div class="margin-bottom-30">
<h3>Search Filters</h3>
</div>
#if(Auth::check() && Auth::user()->user_role->role_id == 1000000)
<div class="be-vidget">
<h3 class="letf-menu-article"> Looking To </h3>
<div class="creative_filds_block">
<div class="radio">
<label><input type="radio" name="lookingTo" onclick="lookingTo(2)"> Seek Advice</label>
</div>
<div class="radio">
<label><input type="radio" name="lookingTo" onclick="lookingTo(3)"> Share Advice</label>
</div>
</div>
</div>
<script>
function lookingTo(e) {
$.ajax({
type: 'POST',
url: '{{ URL::to('looking/to') }}/' + e,
success: function (result) {
$('#browse_professionals').html(result);
}
});
}
</script>
#endif
<div class="be-vidget">
<h3 class="letf-menu-article">Professionals</h3>
<div class="-creative_filds_block">
<div class="fp-panel-wrap">
<a class="toggle-btn active" onclick="open_industry()" href="#" data-target="#ul_industry" id="a_industry">Industry</a>
<ul id="ul_industry" class="fp-panel open" style="overflow:scroll; height:200px;">
#if(!empty($industries))
#foreach($industries as $industry)
<li value="{{ $industry->id }}">{{ (!empty($industry['name'])) ? $industry['name'] : '' }} </li>
#endforeach
#endif
</ul>
<script>
function industry_search(e) {
$.ajax({
type: 'POST',
url: '{{ URL::to('professionals/industry') }}/' + e,
success: function (result) {
$('#education_experience').html(result);
$('#a_industry').attr('class', 'toggle-btn');
$('#ul_industry').css('display', 'none');
$('#education_experience').css('display', 'block');
$('#eduLevel').css('display', 'block');
$('#areaExperience').css('display', 'block');
}
});
}
function open_industry() {
$('#education_experience').css('display', 'block'); // display none hobe na. collapse hoye jabe
// $('#a_industry').attr('class', 'toggle-btn active');
// $('#ul_industry').css('display', 'block');
$('#education_experience').css('display', 'block');
$('#eduLevel').css('display', 'none');
$('#areaExperience').css('display', 'none');
}
</script>
<div id="education_experience" style="">
<a id="a_education" class="toggle-btn" href="#" data-target="#eduLevel">Education Level</a>
<ul id="eduLevel" class="no-link fp-panel" style="overflow:scroll; height:200px;">
#if(!empty($degrees))
#foreach($degrees as $degree)
<li value="{{ $degree->id }}">{{ (!empty($degree['name'])) ? $degree['name'] : '' }}</a> </li>
#endforeach
#endif
</ul>
<a id="a_experience" class="toggle-btn" href="#" data-target="#areaExperience">Areas of Experience</a>
<ul id="areaExperience" class="no-link fp-panel" style="overflow:scroll; height:200px;">
</ul>
</div>
</div>
</div>
</div>
<div class="be-vidget">
<h3 class="letf-menu-article">Meeting Preferences</h3>
<label>Price</label>
<br> <br>
<input type="hidden" id="price_ranger" class="range-slider" value="23"/>
<label style="margin-top: 30px;">Type</label>
<div class="form-group">
<select class="form-input" id="meeting_type">
<option value="3">All</option>
<option value="1">Phone Meeting</option>
<option value="2">Web Meeting</option>
</select>
</div>
</div>
<button id="search_professionals" type="button" class="btn color-2 size-2 btn-block hover-1">Apply Filter</button>
#if(Session::has('remove_filter'))
<button type="button" class="btn btn-danger size-2 btn-block hover-1">Remove Filter</button>
#endif
<script>
var industry = '';
$('#ul_industry li').click(function() {
industry = $(this).attr('value');
});
$("#search_professionals").click(function () {
var degrees = new Array();
$('input[name="degrees_checkbox"]:checked').each(function() {
degrees.push(this.value);
});
var experiences = new Array();
$('input[name="experiences_checkbox"]:checked').each(function() {
experiences.push(this.value);
});
var price_ranger = $("#price_ranger").val();
var price_ranger_array = price_ranger.split(",");
var start_price = price_ranger_array[0];
var end_price = price_ranger_array[1];
var meeting_type = $("#meeting_type").val();
$.ajax({
'type' : 'post',
'url' : '{{ URL::to('search/professionals') }}',
'data' : {
'industry' : industry,
'educationLevels' : degrees,
'areasOfExperiences' : experiences,
'start_price' : start_price,
'end_price' : end_price,
'meeting_type' : meeting_type
},
'success' : function (result) {
console.log(result);
$('#browse_professionals').html(result);
}
});
});
</script>
</div>
{{--</form>--}}
<div class="col-md-10">
<div id="browse_professionals" class="row _post-container_">
#if (!empty($valid_providers))
#foreach ($valid_providers as $provider)
<div class="category-1 custom-column-5">
<div class="be-post">
<figure class="ratio-4-3 be-img-block-alt">
<div class="ratio-inner" style="background-image: url('{{ !empty($provider->user_detail->avatar) ? URL::to($provider->user_detail->avatar) : '' }}')">
<img src="{{ !empty($provider->user_detail->avatar) ? URL::to($provider->user_detail->avatar) : '' }}" alt="{{ !empty($provider->username) ? URL::to($provider->username) : '' }}">
</div>
</figure>
<div class="be-post-title">{{ (!empty($provider->user_share->share)) ? str_limit($provider->user_share->share, 90) : '' }}</div>
<div class="author-post">
<span>{{ !empty($provider->user_detail->first_name) ? $provider->user_detail->first_name : '' }} {{ !empty($provider->user_detail->last_name) ? $provider->user_detail->last_name : '' }}</span>
</div>
<span>{{ (!empty($provider->user_detail->credentials)) ? str_limit($provider->user_detail->credentials, 25) : '' }}</span>
<div data-value="4" class="static-rating"></div>
<div class="info-block clearfix">
<a class="btn color-1 size-2 hover-1 pull-right" href="{{ !empty($provider->username) ? URL::to($provider->username) : '' }}">Contact</a>
<h3 class="rate"> ${{ (!empty($provider->user_time->hour_rate)) ? $provider->user_time->hour_rate : '' }} /hr</h3>
</div>
</div>
</div>
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
#endsection
My Searchcontroller is
public function searchProfessionals (Request $request)
{
$industry = $request->input('industry');
$educationLevels = $request->input('educationLevels');
$areasOfExperiences = $request->input('areasOfExperiences');
$startPrice = $request->input('start_price');
$endPrice = $request->input('end_price');
$meetingType = $request->input('meeting_type');
if ($meetingType == 1) {
$type = [1, 1];
} elseif ($meetingType == 2) {
$type = [2, 2];
} elseif ($meetingType === 3) {
$type = [1, 2];
} else {
$type = [1, 2];
}
$userMeetings = array();
$userRoles = array();
$users = array();
$showUsers = array();
$userHourRates = array();
// return response($industry);
$userIndus = UserIndustry::where('industry_id', $industry)->get();
if (!empty($userIndus)) {
foreach ($userIndus as $userInd) {
$userHourRates = UserTime::where('user_id', $userInd->user_id)->whereBetween('hour_rate', [$startPrice, $endPrice])->first();
}
// $userHourRates = UserTime::whereBetween('hour_rate', [$startPrice, $endPrice])->get();
if (!empty($userHourRates)) {
foreach ($userHourRates as $userHourRate) {
$userMeetings[] = UserMeeting::whereIn('meeting_id', $type)->where('user_id', $userHourRate->user_id)->first();
}
if (!empty($userMeetings)) {
foreach ($userMeetings as $userMeeting) {
$userRoles[] = UserRole::where('user_id', $userMeeting['user_id'])->where('role_id', '!=', 1)->first();
}
if (!empty($userRoles)) {
foreach ($userRoles as $userRole) {
$users[] = User::find($userRole['user_id']);
}
if (!empty($users)) {
foreach ($users as $u) {
$user = User::find($u['id']);
$userDetail = UserDetail::where('user_id', $u['id'])->first();
$userShare = UserShare::where('user_id', $u['id'])->first();
$userMeeting = UserMeeting::where('user_id', $u['id'])->first();
$userWeek = UserWeek::where('user_id', $u['id'])->first();
$userTime = UserTime::where('user_id', $u['id'])->first();
if (
$user['is_active'] == 1 && $user['is_deleted'] == 0 && !empty($userDetail['avatar']) && !empty($userDetail['first_name']) &&
!empty($userDetail['last_name']) && !empty($userDetail['credentials']) && !empty($userShare['share']) &&
!empty($userShare['seek']) && !empty($userMeeting['meeting_id']) && !empty($userWeek['week_id']) &&
!empty($userTime['start_time']) && !empty($userTime['end_time']) && !empty($userTime['hour_rate'])
) {
$showUsers[] = $u;
}
}
if (!empty($showUsers)) {
$string = '';
foreach ($showUsers as $showUser) {
$userShow = User::find($showUser->id);
$userDetailShow = UserDetail::where('user_id', $showUser->id)->first();
$userShareShow = UserShare::where('user_id', $showUser->id)->first();
$userRatingShow = Review::where('provider_id', $showUser->id)->orWhere('seeker_id', $showUser->id)->avg('rating');
$userTimeShow = UserTime::where('user_id', $showUser->id)->first();
$string .= '
<div class="category-1 custom-column-5">
<div class="be-post">
<figure class="ratio-4-3 be-img-block-alt">
<div class="ratio-inner" style="background-image: url(' . url($userDetailShow->avatar) . ')">
<img src="' . url($userDetailShow->avatar) . '" alt="omg">
</div>
</figure>
<div class="be-post-title">' . str_limit($userShareShow->share, 90) . '</div>
<div class="author-post">
<span>
<a href="' . url($userShow->username) . '">' .
$userDetailShow->first_name . ' ' . $userDetailShow->last_name . '
</a>
</span>
</div>
<span>' . $userDetailShow->credentials . '</span>
</div>
<div data-value="' . $userRatingShow . '" class="static-rating"></div>
<div class="info-block clearfix">
<a class="btn color-1 size-2 hover-1 pull-right" href="' . url($userShow->username) . '">Contact</a>
<h3 class="rate">$' . $userTimeShow->hour_rate . '/hr</h3>
</div>
</div>
</div>
';
}
return response($string);
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
} else {
return 'data not found.';
}
}
Please help me how can i show value via checkbox. Please help me solving this.
Try to debug your JavaScript by F12, and notice there is any error or not.
if not there is no Javascript problem, you can also check ajax request return data on network tab.

Categories