Receiving parameters by URL loads all the content - laravel

I have a project that shows orders between dates with two dates
Route:
Route::get('/order/manage/all/{date1?}{date2?}', [\App\Http\Controllers\OrderController::class, 'all'])->name('order.manage.all');
View:
<form method="GET" action="{{route('order.manage.all')}}" id="buscador">
<div class="row">
<div class="form-group col">
<label for="date1" class="col-md-4 col-form-label">Fecha1</label>
<input type="date" class="mb-2"name="date1"/>
</div>
<div class="form-group col">
<label for="date2" class="col-md-4 col-form-label">Fecha2</label>
<input type="date" class="mb-2" name="date2"/>
</div>
<div class="form-group col">
<input class="btn btn-primary" type="submit" value="Filtrar"/>
</div>
</div>
</form>
#foreach($orders as $order)
<div class="card mb-5 line">
<h3 class="text-center">{{"Fecha de pedido: ".$order->date_order." | "."Referencia: ".$order->reference}} </h3>
<h3 class="text-center">{{$order->address->name." ".$order->address->surname1." ".$order->address->surname2}}</h3>
<h3 class="text-center">{{$order->address->address." (".$order->address->region.", ".$order->address->city.")"}}</h3>
<p class="text-center">{{\OrderItemHelper::countOrderItems($order->id)}} productos</p>
</div>
#endforeach
Controller:
public function all($date1 = null, $date2 = null) {
var_dump($date1);
var_dump($date2);
if (!empty($date1) && !empty($date2)) {
$orders = Order::whereBetween('date_order', [$date1, $date2])->get();
} else {
$orders = Order::orderBy('date_order', 'desc')->get();
}
return view('order.all', [
'orders' => $orders
]);
}
The problem I have is that when I receive these parameters by the URL (when doing the var_dump of $date1 it loads me all the content of the URL. And the $date2 returns null)

You are not actually using the route parameters here. You are using the request inputs from the query string. Route parameters are from the URI (which does not include the query string).
With what you are doing you would drop the parameters from the route definition and get the dates from the request.
Route::get('/order/manage/all', [\App\Http\Controllers\OrderController::class, 'all'])->name('order.manage.all');
public function all(Request $request)
{
$date1 = $request->input('date1');
$date2 = $request->input('date2');
...
}
Though, it looks like you may have a misconfigured server to go along with this as the query string might be being passed without the '?' and its ending up as a part of the path [based on your data dump].

Related

How to use laravel redirect back with compact

I am trying to pass value from the price page via input and redirect back to the price page with a value that has been calculated. I am using two functions for this; one is for get price()-PagesController#pricing and the other one is for post feeCal()-PagesController#feeCal.
public function pricing(Request $request)
{
return response()->view('pages.price');
}
public function feeCal(Request $request)
{
$value = $request->input('price');
if ($value > 500 or $value > 20000) {
$fee = $value * 0.015;
}
// dd($fee);
return redirect()->back()->compact('fee');
}
<form action="{{ route('page.vfee')}}" method="POST">
#csrf
<div class="row">
<input type="number" name="price" class="form-control rounded mb-3" placeholder="Type the price here">
</div>
<div class="row">
<input type="submit" class="btn btn-danger w-100
rounded" value="GET TOTAL FEE">
</div>
</form>
<div class="card-footer">
<div class="text-muted">Total fee</div>
<div class="text-danger">
{{ $fee ?? '' }}
</div>
</div>
When you try to input a value it returns a black value but when you dump the fee variable in the controller function you get a result.
Try one of following
return redirect()->back()->with(compact('fee'));
or
return redirect()->back()->with('fee', $fee);

pass user request in form action route in laravel 8

here is my simple form
<form id="test-form" class="white-popup-block mfp-hide">
<div class="popup_box ">
<div class="popup_inner">
<h3>Make an Appointment</h3>
<form action="{{route('doctorwithdatepopup',['date'=>$date,'id'=>$doctorsid])}}" method="POST">
#csrf
<div class="row">
<div class="col-xl-6">
<input id="datepicker" placeholder="Pick date" name="date">
</div>
#php
$Department = DB::table('departments')->orderBy('id','desc')->get();
#endphp
<div class="col-xl-6">
<select class="form-select wide" id="departmentid" name="departmentid">
<option data-display="Select Department">Department</option>
#foreach ($Department as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
</select>
</div>
<div class="col-xl-12">
<select class="form-select wide" id="doctorsid" name="doctorsid" class="">
</select>
</div>
<br>
<br>
<div class="col-xl-12">
<button type="submit" class="boxed-btn3">Search</button>
</div>
</div>
</form>
</div>
</div>
</form>
inaction ['date'=>$date,'id'=>$doctorsid] these two data I want pass based on user selection how can I do that?
for example
$date = $request->date
this one can handle in the controller but in action URL how can I pass user enter values ?
Little tricky. Try to make 2 routes for that, first route to get user form requests. Second, your "doctorwithdatepopup" routes.
web.php
Route::post('url', [YourController::class, 'store'])->name('storeform');
Route::get('url2/{date}/{id}', [YourController::class, 'show'])->name('doctorwithdatepopup');
YourController.php
public function store(Request $request)
{
// Some Validation, Logic, etc
return redirect()->route('doctorwithdatepopup', ['date' => $request->date, 'id' => $doctorId]);
}
public function show($date, $id)
{
return view('your view', compact('date', 'id'));
}

middleware conflicts with controller __construct middleware (request validation error not working)

I am using middleware for user roles.
But when I am using middleware in Controller __construct method, request validation does not work properly. It doesnt show any errors, session error bag returns null. I am not able to see any errors when form submit. But when I have disabled middleware in construct I can see request validation errors.
web.php middleware + controller _construct middleware = request validation doesnt works.
web.php middleware + without _construct middleware = works fine.
without web.php middleware + _construct middleware = works fine.
I showed the details in my codes.
I tried every method for a week but I couldn't solve it.
I look forward to your help sincerely.
web.php
Route::group(['middleware' => ['client.role:paying']], function () {
Route::get('/pay_section', 'HomepageController#showPaySection');
Route::get('/pay_success', 'HomepageController#showPaySuccess');
Route::get('/pay_error', 'HomepageController#showPayError');
Route::post('/pay_section', 'HomepageController#doPaySection');
});
HomepageController (like this my form request validation doesnt works because of middleware)
public function __construct()
{
$this->middleware(function ($request, $next) {
$client = auth()->guard('client');
if ($client->check()){
$request->session()->put('client_id', $client->user()->id);
}else{
$request->session()->put('client_id', -1);
}
$this->_cid = $request->session()->get('client_id'); // client
View::share(['cid' => $this->_cid]);
return $next($request);
});
}
HomepageController (like this my codes works perfect. I am able to see request validation errors there is no problem.)
public function __construct()
{
$this->_cid = 2; // client
View::share(['cid' => $this->_cid]);
}
Middleware ClientRole.php
public function handle($request, Closure $next, ...$roles)
{
$currentRole = array();
$client = auth()->guard('client');
if ($client->check()){
$currentRole[] = 'client';
}else{
$currentRole[] = 'guest';
}
if (session()->has('shop_cart')) {
$currentRole[] = 'shopping';
}
if (session()->has('order')) {
$currentRole[] = 'paying';
}
$currentRole[] = 'paying';
foreach($roles as $role) {
if(in_array($role, $currentRole))
return $next($request);
}
return redirect('/');
}
HomepageController form action
public function doPaySection(CreditcardRequest $request)
{
$validated = $request->validated();
// it doesnt show any errors when form empty. But it should be.
// without middleware it shows error on my view when form empty.
}
View
<div class="messages">
#if ($errors->any())
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Error!</h3>
#foreach ($errors->all() as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif
</div>
<form action="{{ action('HomepageController#doPaySection') }}" method="post"
class="needs-validation" novalidate>
#csrf
<div class="row">
<div class="col-md-6 mb-3">
<label for="ccname">Name on card</label>
<input type="text" class="form-control" name="cc_name" id="ccname" placeholder="" value="" required>
<small class="text-muted">Full name as displayed on card</small>
<div class="invalid-feedback">
Name on card is required
</div>
</div>
<div class="col-md-6 mb-3">
<label for="ccnumber">Credit card number</label>
<input type="text" class="form-control" name="cc_number" id="ccnumber" placeholder="" value="" >
<div class="invalid-feedback">
Credit card number is required
</div>
</div>
</div>
<div class="row">
<div class="col-md-3 mb-3">
<label for="ccexp">Expiration</label>
<input type="text" class="form-control" name="cc_exp" id="ccexp" placeholder="" value="1209" required>
<div class="invalid-feedback">
Expiration date required
</div>
</div>
<div class="col-md-3 mb-3">
<label for="cccvv">CVV</label>
<input type="text" class="form-control" name="cc_cvv" id="cccvv" placeholder="" value="333" required>
<div class="invalid-feedback">
Security code required
</div>
</div>
</div>
<hr class="mb-4">
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit">
<i class="fa fa-check"></i> Submit
</button>
</form>
You may set SESSION_DRIVER=file in you .env file
Then run php artisan config:clear
Seems related

How to display selected value and image in edit page to perform update operation using laravel

Hello,
I am new learner in Laravel and my first post in Stackoverflow so applogy to me for my mistake and English language.
I can create a project shoppingcart & perform CRUD operation where create product information such as product name, brand, description, price & image. I can done create & read operation easily. Below my product list that can be show in browser
enter image description here
When I click edit button browser can show like that below image to perform edit operation
enter image description here
where brand name & image can't shown edit product form
My productController code below like that
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\brand;
use App\Product;
use Illuminate\Support\Facades\DB;
class productController extends Controller
{
public function index(){
$product = DB::table('products')
->join('brands','products.brandID','=','brands.brandID')
-> select('products.*','brands.brandName')
->get();
return view('admin.product.productList',compact('product'));
}
public function create()
{
$product = brand::pluck('brandName','brandID');
return view('admin.product.createProduct',compact('product'));
}
public function store(Request $request)
{
// image upload
$product = $request->except('image');
$image = $request->image;
if ($image) {
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$product['image'] = $imageName;
}
Product::create($product);
return view('admin.product.productList', compact('product'));
}
public function show($id)
{
$product = Product::find($id);
return view('admin.product.editProduct',compact('product'));
}
public function edit($id)
{
}
public function delete($id){
$product= Product::find($id);
$data=$product->delete();
return view('admin.product.productList',compact('data'));
}
}
my editProduct.blade file code below like that
#extends('layouts.master')
#section('content')
<div class="container" align="center">
<div class="col-md-6 col-md-offset-3">
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Edit Product
</div>
<div class="panel-body">
<form action="edit" class="form-horizontal" method="POST>
{{csrf_field()}}
<div class="form-group">
<label for="name" class="col-md-4 control-label">Product Name :</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" value="{!! $product->productName !!}" name="name" required autofocus>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Brand :</label>
<div class="col-md-6">
<select name=" " class="form-control" >
<option>
</option>
</select>
</div>
</div>
<div class="form-group">
<label for="description" class="col-md-4 control-label">Description:</label>
<div class="col-md-6">
<input id="description" class="form-control" name="description" value="{!! $product->description !!}" required>
</div>
</div>
<div class="form-group">
<label for="price" class="col-md-4 control-label">Price:</label>
<div class="col-md-6">
<input id="price" value="{!! $product->price !!}" class="form-control" name="price" required>
</div>
</div>
<div class="form-group">
<label for="image" class="col-md-4 control-label">Image:</label>
<div class="col-md-6">
<input id="image" type="file" value="{!! $product->image !!}" class="btn-btn-default" name="image" value="Upload" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
ADD
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Here, brand name can be selected by HTML select attribute and value get another model Brand & the data can be retrieve from Brand model using join query which is included productController index method.
So how can I show brand name & image to edit in the editProduct blade file. Pls help me
There are couple of ways, here's 1 way.
In your controller.
public function edit($id)
{
$product = Product::find($id);
$data = [
'product_info' => $product
];
return view('your.edit.view.here', $data);
}
And inside your view, inside the FORM Tag, do the looping.
#foreach($product_info as $info)
// data info here
<input id="description" value="{{ $product->description }}" required>
#endforeach
EDIT::
Use Laravel Encryption, you need it especially web apps like shopping cart.
URL:: http://localhost:8000/product/show/encrypted_id_here
public function show($id) {
$id = decrypt($id);
}

Laravel 5 session()->keep method not working

I have a view with an input date field and a table beneath that. The table is populated based on the date entered. When the date is entered I use a POST method on the form which handles the DB request and returns the same view with the data. I'd like to also return the original date that was entered. I tried session()->keep and flashOnly methods. None return the input date to the view.
My controller:
public function groupTestAthletes(Request $request)
{
$inputDate = null;
$tests = null;
if ($request['tgroupdate']){
$inputDate = Carbon::createFromFormat('d/m/Y', $request['tgroupdate']);
$tests = Test::where('test_date', '=', $inputDate->format('Y-m-d'))
->orderBy('athlete_id', 'desc')
->get();
}
$request->session()->keep(['tgroupdate']);
//$request->flashOnly(['tgroupdate']);
return view('npr.test_athletes', ['tests' => $tests]);
My view:
<form class="form-inline" role="form" method="POST" action="{{ route('admin.search_tgroup') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="tgroupdate" class="control-label">Test Date</label>
<div class="input-group date" id="testgroupdatepicker">
<input name="tgroupdate" type="text" style="background-color:#ffffff" readonly=""
value="{{ Session::get('tgroupdate') }}" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Search Athletes
</button>
<input type="hidden" name="_token" value="{{ Session::token()}}">
</div>
</form>
You dont need to save the date in session. You can save the date in a variable,send it to the view and in the view you can check if variable exist using isset php function.
In Controller
public function groupTestAthletes(Request $request)
{
$inputDate = null;
$tests = null;
if ($request['tgroupdate']){
$inputDate = Carbon::createFromFormat('d/m/Y', $request['tgroupdate']);
$tests = Test::where('test_date', '=', $inputDate->format('Y- m-d'))
->orderBy('athlete_id', 'desc')
->get();
}
return view('npr.test_athletes', ['tests' => $tests,'selected_date' => $request['tgroupdate']]);
And in the view,
<form class="form-inline" role="form" method="POST" action="{{ route('admin.search_tgroup') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="tgroupdate" class="control-label">Test Date</label>
<div class="input-group date" id="testgroupdatepicker">
<input name="tgroupdate" type="text" style="background-color:#ffffff" readonly=""
value="#if(isset($selected_date)) $selected_date #endif" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Search Athletes
</button>
<input type="hidden" name="_token" value="{{ Session::token()}}">
</div>
</form>
Edit: This minor change in the view gave the optimal solution.
value="#if(isset($selected_date)){{$selected_date}}#endif"

Resources