Laravel how to access, in a view, a value passed by a controller, but inside a script section - ajax

From a request handler I pass a parameter to a request view:
public function sol_solicitante(Request $request, $param){
return view('solicitante.solicitudes', compact('param'));
}
The view that the controller invokes is:
#extends('layouts.app')
#section('title','Buzón Solicitudes')
#section('css')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.6/css/responsive.bootstrap4.min.css">
#endsection
#section('content')
<div class="container mt-4">
<div>
<h2>Buzón De Solicitudes</h2>
</div>
<div class="card">
<div class="card-body">
<!--
<a href="crear">
<button type="button" class="btn btn-success float-right">Crear Solicitud</button>
</a>
</h2>
-->
<table class="table table-hover" id="buzonsolicitudes">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Nombre</th>
<th scope="col">Estado</th>
<th scope="col"> </th>
</tr>
</thead>
</table>
</div>
</div>
</div>
#endsection
#section('js')
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.6/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.6/js/responsive.bootstrap4.min.js"></script>
<script>
$('#buzonsolicitudes').DataTable({
"ajax": "{{ route('datatable.sol_solicitante',['param' => '1'])}}",
"columns":[
{data:'id'},
{data:'nombre'},
{data:'estadologico'},
{data:'btn'}
],
responsive: true,
autoWidth: false,
"language": {
"lengthMenu": "Mostrar " +
`<select class="custom-select" custom-select-sm form-control form-control-sm>
<option value='10'>10</option>
<option value='25'>25</option>
<option value='50'>50</option>
<option value='100'>100</option>
<option value='-1'>Todos</option>
</select>` +
" registros por página",
"zeroRecords": "Nada encontrado - disculpa",
"info": "Mostrando página _PAGE_ de _PAGES_",
"infoEmpty": "Ningún registro disponible",
"infoFiltered": "(filtrado de _MAX_ registros totales)",
'search':'Buscar',
'paginate':{
'next':'siguiente',
'previous':'anterior'
}
}
});
</script>
#endsection
What I don't know is how to access, in the view, the parameter sent by the controller, since I must pass it as a parameter to the Ajax call; Something like:
<script>
var p= param
$('#buzonsolicitudes').DataTable({
"ajax": "{{ route('datatable.sol_solicitante',['param' => p])}}",
This that I put does not work and checking I do not find how it should be.
I appreciate all help, thank you.

php codes are processed on server. the blade compiles all variables before page loads. look you are already using route helper. just pass the variable to the helper as you do in other places.
"ajax": "{{ route('datatable.sol_solicitante', ['param' => $param]) }}"
this will generate the route as you defined on your web.php file like mysite.com/datatable/sol_solicitante/param_value

You should create a script in blade file. In that script, you add init some variables with value from controller

Add this in your script
var data ={!! $data->id !!}; //data->id is variable send by controller
you can directly access this variable in script
Try this hope it works

Related

How to get my link to display as a link from my laravel controller

I'm trying to send an error message with a link. The issue I'm having is that when I get the error I get the html version of my link
EG: Please go to product
What I would like is for my error message to say Please go to product where as product would be a link.
Here is my code
public function updateProduct(Product $product)
{
if(!empty($product->status))
{
$url = "Product";
return redirect()->route('product.index', [$product])->with('error', "Go to $url.");
}
}
and in my index.blade.php
I have this
#section('content')
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<table class="table">
#foreach($products as $product)
<tr>
<td>
{{ $product->name }}
</td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</div>
#endsection
#push('js')
<script type="text/javascript">
#if(session('error'))
Swal.fire('Error!', '{{ session('error') }}', 'error');
#endif
</script>
#endpush
you are sending html as response. you have to use {!! !!} to print that response as your expectation.
#push('js')
<script type="text/javascript">
#if (session('error'))
Swal.fire('Error!', '{!! session('error') !!}', 'error');
#endif
</script>
#endpush
this will show the swal as Go to Product

Fill table depending dropdown list selected value in Laravel vuejs Axios

I am trying to get data in the table code are as below
I want to autofill the table with the depending dropdownlist selected value. i’ve been finding solution since days but didn’t get any success. I’m very new at this.
If anyone could help to get me out from this issue i’ll be very grateful. Thank You.
Here Is my HTML code
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">employees Table</h3>
<div class="card-body">
<div class="md-3">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<select
name="company_id"
id="company_id"
:class="{'is-invalid':form.errors.has('company_id')}"
class="form-control"
v-model="form.company_id"
#change="getEmployeesbyCompany()"
>
<option value selected>Select Company</option>
<option
v-for="Company in Companies.data"
:key="Company.id"
>{{Company.Company}}</option>
</select>
<has-error :form="form" field="company_id"></has-error>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<div class="col-md-12"></div>
<table class="table table-hover">
<!-- <thead>
</thead>-->
<tbody>
<tr>
<th>ID</th>
<th>Badge#</th>
<th>Company</th>
<th>BadgeType</th>
<th>Nationality</th>
<th>Last Name</th>
<th>First Name</th>
<th>Telphonenumber</th>
<th>Position</th>
<th>SupervisorName</th>
<th>SupervisorNumber</th>
<th>Issuedate</th>
<th>Tazker</th>
<th>Expiredate</th>
<th>Serialnumber</th>
<th>Modify</th>
</tr>
<tr v-for="employee in employees.data" :key="employee.id">
<td>{{employee.id}}</td>
<td>{{employee.BadgeCode|UppCaseFirstLetter}}</td>
<!-- <td>{{employee.company_id}}</td> -->
<td>{{Company.Company}}</td>
<td>
<span class="tag tag-success">{{employee.BadgeType}}</span>
</td>
<td>{{Nationality.nationality}}</td>
<td>{{employee.lastname |UppCaseFirstLetter}}</td>
<td>{{employee.firstname |UppCaseFirstLetter}}</td>
<td>{{employee.telphonenumber |UppCaseFirstLetter}}</td>
<td>{{employee.position |UppCaseFirstLetter}}</td>
<td>{{employee.supervisorname |UppCaseFirstLetter}}</td>
<td>{{employee.supervisornumber|UppCaseFirstLetter}}</td>
<td>{{employee.Issuedate|mydate}}</td>
<td>{{employee.tazker|UppCaseFirstLetter}}</td>
<td>{{employee.Expiredate |mydate}}</td>
<td>{{employee.serialnumber |UppCaseFirstLetter}}</td>
</tr>
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer">
<pagination :data="employees" #pagination-change-page="getResults"></pagination>
</div>
</div>
<!-- /.card -->
</div>
My #change="getEmployeesbyCompany" method:
methods: {
getEmployeesbyCompany: function() {
axios.get("api/getEmployees", {
params: {company_id: this.form.company_id}})
.then( function(response) {this.employees = response.data;}.bind(this)
);
}
Route:
Route::get('getEmployees','API\EmployeeController#getEmployees');
My getEmployees(){} method:
public function getEmployees(Request $request)
{
$employees = Employee::where('company_id',$request->company_id)->get();
return $employees;
}
My data() in Vue Component:
data() {
return {
editMode: false,
selectedTicketInvoiceId: false,
Companies: {},
Nationalities: {},
employees: {},
form: new Form({id: "",BadgeCode: "",BadgeType: "",company_id: "",
nationality_id: "",lastname: "",firstname: "",telphonenumber: "",
position: "",supervisorname: "", supervisornumber: "",
issuedate: "",tazker: "", expiredate: "", serialnumber: "" })};
}
The issue is that your table is using employees.data in the v-for directive. This works fine on the initial page load, because employees is a Laravel paginator, so the data property is defined, and it contains the array of employees, as expected.
However, your controller function is simply returning an array of employees. You are saving that array to your Vue instance's employees property. So now employees.data is undefined, and your table is empty.
To fix the issue, you can update your controller function like this:
public function getEmployees(Request $request)
{
$employees = Employee::where('company_id',$request->company_id)->get();
return ['data' => $employees]; // or return response()->json(['data' => employees]);
}

Make modal pop-up when an items quantity in database is below a specific number like 5 in Laravel

I want my modal to pop-up in a blade when the quantity of a stock item is below a specific number like 5. I have the modal but I don't know how to call/instantiate it. Help me please.
https://laracasts.com/discuss/channels/laravel/models-views-controllers There wasn't a solution in this dicussion, thats why I pleading for your assistance.
Here is my modal in index.blade.php:
<div class="modal fade" id="modal-danger">
<div class="modal-dialog">
<div class="modal-content bg-danger">
<div class="modal-header">
<h4 class="modal-title">Danger Modal</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-outline-light">Save changes</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
Here is my controller:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sales Report</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.2/css/buttons.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap4.min.css">
</head>
<body>
<table id="example" class="table table-striped table-bordered dt-responsive nowrap" style="width:100%">
<caption><h3>Sales Report</h3></caption>
<thead>
<tr>
<th>Sales ID</th>
<th>Stock ID</th>
<th>Product Name</th>
<th>Sale Quantity</th>
<th>Unit Selling Price</th>
<th>Total Sales Cost</th>
<th>Sold On</th>
</tr>
</thead>
<tbody>
#foreach($sales as $key => $sale)
<tr>
<td>{{$sale->sales_id}}</td>
<td>{{$sale->stock_id}}</td>
<td>{{$sale->product_name}}</td>
<td>{{$sale->sale_quantity}}</td>
<td>{{$sale->unit_selling_price}}</td>
<td>{{$sale->total_sales_cost}}</td>
<td>{{$sale->updated_at}}</td>
</tr>
#endforeach
</tbody>
</table>
</body>
</html>
Here is screenshot of the stock table:
screenshot of the stock table
I believe you have a controller to return your view. So, just count the stock items and return it as a variable to your view, like this:
$items = Stock::count();
return view('your-view')->with([
'itemsCount' => $items,
]);
Then, in your view, do something like this:
<input type='hidden' value='{{ $itemsCount }}' id="items-count">
<script>
$(document).ready(function(){
if($("#items-count").val() < 5) {
$("#your-modal-id").modal("show");
}
});
</script>
Update
To count a specific stock;
$items = Stock::where('stock_name', $stockName)->first()->stock_quantity;
//If you want to count every single stock, just do it with a for or foreach loop
return view('your-view')->with([
'itemsCount' => $items,
]);
Hope this helps.

Live Search using Ajax and Getting Error "500 (Internal Server Error)" on Laravel 5.8

I was following tutorial to Live Search using ajax on Laravel, but in the implementation I get error:
GET http://localhost:8000/search?search=k 500 (Internal Server Error)
I was following this tutorial 3 times but always getthis same error. I modified like this:
<!DOCTYPE html>
<html>
<head>
<meta name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search">
<input type="hidden" name="_method" value="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function() {
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
my controller:
public function search(Request $request)
{
if($request->ajax()) {
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products) {
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
I was trying this code for 3 different database and always get the same error 500 .
You have call ajax using get method, so first check your route file.
I think you are calling search method using post method.
Also in ajax code default is get method
you have to specify : method : post
you need to declare variable in Jquery/Javascript like below :
var value=$(this).val();
and pass this variable like below in ajax :
data:{'search':value}
Change above lines ,it should work !

How to call edit method of the resource controller using AJAX in Laravel5.6

In my laravel project I am using resource controller for update. but it is not working. I tried but it failed.
my blade
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<title>{{ config('app.name') }}</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
<link href="{{ asset('css/style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>{{ config('app.name') }}</h1>
<form class="dis-none" id="FormAjax">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" rows="3" id="address"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="country">Country</label>
<input type="text" class="form-control" id="country" />
</div>
</div>
</div>
<button type="submit" id="SaveAjax" class="btn btn-success">Save Form</button>
<button type="button" id="cancel" class="btn btn-danger">Cancel</button>
</form>
<div id="ShowAjax" class="row">
<button type="button" id="AddForm" class="btn btn-success">Add Form</button>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Country</th>
<th>Action</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#AddForm").click(function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
$('#UpdateForm').text('Save Form');
});
$("#SaveAjax").click(function () {
$("#FormAjax").hide();
$("#ShowAjax").fadeIn();
});
$(document).on('click', '#cancel', function () {
$('#name').val('');
$('#country').val('');
$('#address').val('');
});
$(document).on('click', '#edit', function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
name = $(this).parent().parent().find('#ename').text();
address = $(this).parent().parent().find('#eaddress').text();
country = $(this).parent().parent().find('#ecountry').text();
$('#name').val(name);
$('#address').val(address);
$('#country').val(country);
$('#SaveAjax').text('Edit');
$('#SaveAjax').prop('id', 'UpdateForm');
$('#UpdateForm').attr('data-id', $(this).data('id'));
});
$(document).on('click', '#UpdateForm', function () {
name = $('#name').val();
country = $('#country').val();
address = $('#address').val();
url = "peoples";
id = $(this).data('id');
editUrl = url + '/' + id + '/edit';
$.get( {{ route('editUrl') }}, {name:name, country:country, address:address, id:id}, function (data) {
console.log('success');
});
});
});
</script>
</body>
</html>
route/web.php
Route::resource('peoples', 'PeopleController');
PeopleController.php
public function edit(People $people)
{
if($request->ajax()) {
$request->validate([
'name' => 'required',
'address' => 'required',
'country' => 'required',
]);
$people = People::find($request->id);
$people->name = $request->name;
$people->address = $request->address;
$people->country = $request->country;
$people->save();
return response()->json();
}
}
When I try type in browser http://localhost:8000/peoples I see this error.
Route [editUrl] not defined. (View: C:\xampp\htdocs\Tutorials
Laravel\Ajax\resources\views\peoples.blade.php)
You cannot use the route() helper here as you have not named your routes. Instead, try using the url() helper to generate the URL.
url(id . '/edit')
But, here I see another problem as the id will come in dynamically when the JS executes by which time the Laravel helper would have already executed. So, I would suggest the following approach:
url = {{ base_url() }} + '*apiPrefix*' + '/peoples/' + id + '/edit'

Resources