getting errors when showing data on page using ajax - ajax

I am adding a search functionality to my user admin page and I am using AJAX for search but I have not been able to show data on my page. It gives an error.
I have tried adding single quotation or double quotation on every side but it just give me an error every time
this is the controller function:
public function search(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data =User::where('name', 'like', '%'.$query.'%')->get();
}
else
{
$data =User::orderBy('created_at' ,'desc')->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $merchant)//That how i am showing data on the page
{
$output .=
"<tr>
<td>"{$users->name}"
"#if($users->allowded == 0)" //I need to add these if else functionality to my code but these thing are giving error
"#endif"
</td>
<td>{{$users->email}}</td>
<td>{{$users->permission->permission}}</td>
<td>
<a href="#" class="btn btn-xs btn-success">
<span style="padding-right: 16px;">Make Him Salaried User
</span>
</a>
<a href="#" class="btn btn-xs btn-success">
<span style="padding-right: 16px;">Make Him Commesioned User
</span>
</a>
<a href="#" class="btn btn-xs btn-success">
<span style="padding-right: 16px;">Make Him Salaried and Commesionded User
</span>
</a>
</td>
<td>
#if($users->user_status)
<a href="" class="btn btn-xs btn-danger">
<span style="padding-right: 10px;">Make Him Unpaid User
</span>
</a>
#else
<a href="" class="btn btn-xs btn-success">
<span style="padding-right: 16px;">Make Him Paid User
</span>
</a>
#endif
</td>
<td>
#foreach($cashtransfer as $cash)
#if($cash->user_id == $users->id)
{{ $cash->amount}}
#endif
#endforeach
</td>
<td>
#if($users->allowded)
<a href="" class="btn btn-xs btn-danger">
<span style="padding-right: 16px;">Bloack User</span>
</a>
#else
<a href="" class="btn btn-xs btn-success">
<span style="padding-right: 16px;">Allow User</span>
</a>
#endif
</td>
<td>
</td>
<td>
<a href="" class="btn btn-xs btn-danger">
<span style="padding-right: 16px;">Delete User</span>
</a>
</td>
</tr>";
}
}
else
{
//This is The Out Variable which is taking data to the page
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
These Are the errors I am getting every time:
// ->when($request->has('query'), function($q){
// $q->where('name','like','%'. request('query').'%');
// })->get();
$data =User::where('name', 'like', '%'.$query.'%')->get();
}
else
{
$data =User::orderBy('created_at' ,'desc')->get();
// $pagi = "<div> {$data->links()}</div>";
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $merchant)
{
$output .= "
<tr>
<td>"{$users->name}"
"#if($users->allowded == 0)"
"#endif"
</td>
<td>{{$users->email}}</td>
<td>{{$users->permission->permission}}</td>
<td> <span style="padding-right: 16px;">Make Him Salaried User</span> <span style="padding-right: 16px;">Make Him Commesioned User</span> <span style="padding-right: 16px;">Make Him Salaried and Commesionded User</span></td>
<td>
#if($users->user_status)
<span style="padding-right: 10px;">Make Him Unpaid User</span>
#else
Why can't I just publish it?
I keep getting errors like I need more details

You cannot use blade inside normal strings. You have to use normal PHP to compose the output:
foreach($data as $merchant)
{
$optionalOutput = $users->allowded == 0 ? 'output if true' : 'output if false';
$output .= "<tr>
<td>{$users->name}
{$optionalOutput}
</td>";
// ...
}
Or you could move the code to a blade view:
foreach($data as $merchant)
{
$output .= view('path.to.view', [$merchant, $users])->render();
}

Related

problem in datatable when use in livewire component

i use livewire defer loading for load data after rendering page.
After opening the page, the information is successfully received and displayed in the table
But the problem is that I use datatable and when the received information is displayed, datatable becomes a simple table. As if I did not use datatable at all.
This is the livewire component code
class Cryptolist extends Component
{
public bool $loadData = false;
public function init()
{
$this->loadData = true;
}
public function render()
{
try {
if ($this->loadData) {
$api = new \Binance\API('api','secret');
$prices = $api->coins();
$one = json_encode($prices, true);
$coins = json_decode($one , true);
} else {
$coins = [];
}
return view('livewire.backend.crypto.cryptolist')->with('coins' , $coins);
}catch(\Exception $e)
{
return view('wrong')->with('e' , $e);
}
}
}
And this is the component view where the table is located and displays the received information
<div wire:init="init">
#if ($loadData)
<div id="loadesh1" wire:ignore>
<table class="datatable-init nk-tb-list nk-tb-ulist" data-auto-responsive="false">
<thead>
<tr class="nk-tb-item nk-tb-head">
<th class="nk-tb-col"><span class="sub-text">name</span></th>
<th class="nk-tb-col tb-col-mb"><span class="sub-text">balance</span></th>
</tr>
</thead>
<tbody>
#foreach ($coins as $item => $value)
<tr class="nk-tb-item">
<td class="nk-tb-col">
<div class="user-card">
<div class="user-avatar d-none d-sm-flex">
#if(file_exists(public_path() . '/img/crypto/'.strtolower($value['coin'].".svg")))
<img style="border-radius: 0"
src="{{asset('/img/crypto/'.strtolower($value['coin']))}}.svg" class="img-fluid"
alt="">
#else
<img style="border-radius: 0"
src="https://demo.rayanscript.ir/-/vendor/cryptocurrency-icons/32/color/noimage.png"
class="img-fluid" alt="">
#endif
</div>
<div class="user-info">
<span class="tb-lead english" style="font-weight: bolder">{{$value['name']}}</span>
<span class="english">{{$value['coin']}}</span>
</div>
</div>
</td>
<td class="nk-tb-col tb-col-mb" data-order="{{$value['coin']}}">
<div class="btn-group" aria-label="Basic example">
<button type="button" class="btn btn-sm btn-dim btn-light"
wire:click="getBalance('{{$value['coin']}}')">
<div wire:loading wire:target="getBalance('{{$value['coin']}}')">
<span class="spinner-border spinner-border-sm" role="status"
aria-hidden="true"></span>
</div>
<span class="w-120px" id="coin-{{$value['coin']}}">get balance</span>
</button>
<button type="button" class="btn btn-sm btn-dim btn-primary">add coin</button>
</div>
</td>
</tr><!-- .nk-tb-item -->
#endforeach
</tbody>
</table>
</div>
#else
Loading data...
#endif
</div>
What do you think is the problem, what code is written incorrectly?

How to get id of slider for get slider_group?

I have two tables sliders and slider_group.
In my controller in create function in laravel, I want the get the id that shows in browser show when I browse it shows like this.
http://localhost:8000/admin/sliders/create/21
blade
<a href="{{ route('admin::sliders.create', ['groupId', $sliderGroup->id]) }}" class="mr-1">
Now how to get the id of slider_group table to group_id of requisitions.
<tbody>
#foreach($sliderGroups as $sliderGroup)
<tr>
<td class="text-truncate">
<i class="la la-dot-circle-o success font-medium-1 mr-1"></i>
{{ $sliderGroup->id }}
</td>
<td class="text-wrap">
{{ $sliderGroup->title }}
</td>
<td class="text-wrap">
{{ getShamsiDate($sliderGroup->created_at) }}
</td>
<td>
<div class="row">
<a href="{{ route('admin::sliders.create', ['groupId', $sliderGroup->id]) }}" class="mr-1">
<i class="la la-plus text-grey text-shadow-custom font-medium-4 font-weight-normal"></i>
</a>
<a href="{{ route('admin::slider-groups.edit', $sliderGroup->id) }}" class="mr-1">
<i class="ft-edit text-grey text-shadow-custom font-medium-4 font-weight-normal"></i>
</a>
<form action="{{ route('admin::slider-groups.destroy', $sliderGroup) }}" method="post" #submit.prevent="confirmDelete">
#method('delete')
#csrf
<button type="submit" class="btn btn-default p-0">
<i class="ft-trash-2 text-grey font-medium-5 font-weight-normal"></i>
</button>
</form>
</div>
</td>
</tr>
#endforeach
</tbody>
I get this in address bar like this
http://localhost:8000/admin/sliders/create?groupId&3
It has an error.
404 | Not Found
Controller
public function index(Request $request)
{
if ($request->search) {
$sliderGroups = SliderGroup::search($request->search)->paginate(30);
} else {
$sliderGroups = SliderGroup::paginate(30);
}
if ($sliderGroups->count() == 0 && $request->search ) {
msg()->warning('it is not found.');
}
return view('slider::admin.groups.index', compact('sliderGroups'));
}
web.php
Route::group([
'prefix' => 'admin',
'as' => 'admin::',
], function() {
Route::resource('sliders', 'Admin\SliderController');
Route::resource('slider-groups', 'Admin\SliderGroupController');
});

How can I reduce executed queries in Laravel?

I have about 6 custom attributes on my model, and in my blade view, I loop through filtered models and use these attributes in some if-else statements, but it takes a lot of time to render, as it executes a lot of queries.
Here is an example of an attribute I have.
/**
* Determine if an invoice is due.
*
* #return bool
*/
public function getInvoiceDueAttribute()
{
if (!$this->invoice_frequency) {
return $this->finished && (!$this->invoiced || $this->outgoing_invoices()->whereNull('invoice_number')->count() > 0);
}
$last_invoice = $this->outgoing_invoices()
->where('invoiceable', true)
->latest()
->first();
return ($last_invoice ? $last_invoice->created_at : $this->created_at)
->startOfMonth()->addMonth($this->invoice_frequency)->isPast();
}
Blade:
#foreach($building->projects as $project)
...
<td class="text-center text-nowrap align-middle">
<a href="{{ route('outgoing-invoices.indexPre', ['project' => $project->id]) }}"
class="btn btn-sm btn-{{ $project->invoice_state_color }} #cannot ('Invoice view') disabled #endcannot">
#if ($project->invoice_ok)
<i class="fa fa-check"></i> Számlázva
#elseif ($project->invoice_in_progress)
<i class="fa fa-rotate-right"></i> Folyamatban
#elseif ($project->invoice_due)
<i class="fa fa-times"></i> Számlázatlan
#else
<i class="fa fa-times"></i> Nem esedékes
#endif
</a>
</td>
<td class="text-center text-nowrap align-middle">
#if ($project->invoice_with_project_id)
Havi riportban
#else
<a href="{{ route('outgoing-invoices.index', ['project' => $project->id]) }}"
class="btn btn-sm btn-{{ $project->payment_state_color }} #cannot ('Invoice view') disabled #endcannot">
#if ($project->payment_ok)
<i class="fa fa-check"></i> Nincs fizetetlen számla
#elseif (is_null($project->payment_ok))
<i class="fa fa-times"></i> Nem esedékes
#else
<i class="fa fa-rotate-right"></i> Folyamatban
#endif
</a>
#endif
</td>
...
#endforeach
To be clear, my goal is to improve performance by reducing queries or any other way.
I also accept best-practice advice for any part of my code. Thank you for your help!

product is not deleting from cart

hi m trying to delete product from cart but its not deleting , any suggestion to fix it,when i click on submit button then it says 404|not found
controller:
public function deleteCartProduct(Product $product)
{
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->delProduct($product);
Session::put('cart', $cart);
return redirect()->route('product.cart')->with('flash_message_success', 'Product product has been removed from Cart');
}
model
public function deleteProduct($product)
{
if ($this->contents) {
if (array_key_exists($product->product_slug, $this->contents)) {
$delProduct = $this->contents[$product->slug];
$this->totalQty -= $delProduct['qty'];
$this->totalPrice -= $delProduct['price'];
array_forget($this->contents, $product->slug);
}
}
}
blade file
#foreach($contents as $slug => $cartItem)
<form action="{{ route('deleteCartProduct', $product) }}" method="POST">
#csrf
<tr class="table-row">
<td class="column-1">
<div class="cart-img-product b-rad-4 o-f-hidden">
<img src="{{ URL::to('/') }}/images/backend_images/product_images/{{ $cartItem['product']->product_image }}" alt="IMG-PRODUCT">
</div>
</td>
<td class="column-2">{{ $cartItem['product']->product_name }}</td>
<td class="column-3">${{ $cartItem['product']->product_price }}</td>
<td class="column-4">
<div class="flex-w bo5 of-hidden w-size17">
<button class="btn-num-product-down color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-minus" aria-hidden="true"></i>
</button>
<input class="size8 m-text18 t-center num-product" type="number" name="num-product1" value="{{ $cartItem['qty'] }}">
<button class="btn-num-product-up color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-plus" aria-hidden="true"></i>
</button>
</div>
</td>
<td class="column-5">${{ $cartItem['price'] }}</td>
<td class="column-5">
<input type="submit" class="btn btn-danger value="Remove Product">
</td>
</tr>
</form>
#endforeach
route:
Route::get('/cart/delete-product/{id}','ProductController#deleteCartProduct')->name('deleteCartProduct');
Your route should be Route::delete instead of Route::get and then in the form add this as well:
#method('delete')
I saw your error on the button:
<input type="submit" class="btn btn-danger value="Remove Product">
Change it with this:
<input type="submit" class="btn btn-danger" value="Remove Product">
Missing quote..
EDIT
Your route should be this:
Route::delete('/cart/delete-product/{id}','Admin\ProductController#deleteCartProduct')->name('deleteCartProduct');
You need to change the code in a controller as below.
public function deleteCartProduct(Product $product)
{
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->deleteProduct($product);
Session::put('cart', $cart);
return redirect()->route('product.cart')->with('flash_message_success', 'Product product has been removed from Cart');
}
You defined it as method="POST" in blade. and "get" in route. So you need to change verb to Route::post

Getting 500 Internal Error in laravel

I am new to laravel. I want to fetch the data from database and put it to datatable. This is my html
<div class="tab-pane" id="th_days_client" >
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<i class="material-icons">flag</i>
{{ $title }}
</h4>
<span class="pull-right">
<i class="fa fa-fw fa-chevron-up clickable"></i>
<i class="fa fa-fw fa-times removepanel clickable"></i>
</span>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="th_days_client_data" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
The jQuery for this is :
var th_days_client;
$(document).ready(function () {
th_days_client = $('#th_days_client_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"columns":[
{"data":"name"},
{"data":"email"},
{"data":"mobile"},
{"data":"actions"}
],
"ajax": "{{ url('client') }}" + ((typeof $('#th_days_client_data').attr('data-id') != "undefined") ? "/" + $('#id').val() + "/" + $('#th_days_client_data').attr('data-id') : "/th_days_client_data")
});
});
controller Function for this is :
public function th_days_client_data(Datatables $datatables)
{
$clientObj = new Client;
$client = $clientObj->get()
->map(function ($client) {
return [
'id' => $client->id,
'name' => $client->first_name.' '.$client->last_name,
'email' => $client->email,
'mobile' => $client->mobile
];
});
return $datatables->collection($client)
->addColumn('actions', '#if(Sentinel::inRole(\'admin\'))
<a href="{{ url(\'client/\' . $id . \'/edit\' ) }}" title="{{ trans(\'table.edit\') }}">
<i class="fa fa-fw fa-pencil text-warning "></i> </a>
#endif
<a href="{{ url(\'client/\' . $id . \'/show\' ) }}" title="{{ trans(\'table.details\') }}" >
<i class="fa fa-fw fa-eye text-primary"></i> </a>
#if(Sentinel::inRole(\'admin\'))
<a href="javascript:void(0)" onclick="deleteClient({{$id}})" title="{{ trans(\'table.delete\') }}">
<i class="fa fa-fw fa-trash text-danger"></i> </a>
#endif')
->removeColumn('id')
->rawColumns(['actions'])->make();
}
My route is
Route::group(['prefix' => 'client'], function () {
Route::get('data', 'Users\ClientsController#data');
Route::get('pending_client_data', 'Users\ClientsController#pending_client_data');
Route::get('th_days_client_data', 'Users\ClientsController#th_days_client_data');
Route::get('{client}/edit', 'Users\ClientsController#edit');
Route::post('{client}/update', 'Users\ClientsController#update');
Route::get('{client}/show', 'Users\ClientsController#show');
Route::get('{client}/delete', 'Users\ClientsController#delete');
});
When I am running this then I am getting 500 Internal Error. When I go to laravel.log file then the error is :
[2018-08-01 08:59:27] local.ERROR: Method [th_days_client_data] does not exist on [App\Http\Controllers\Users\ClientsController]. {"exception":"[object] (BadMethodCallException(code: 0): Method [th_days_client_data] does not exist on [App\\Http\\Controllers\\Users\\ClientsController]. at /var/www/webroot/ROOT/files/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:68)
How can I solve this ?

Resources