October CMS: AJAX form - ajax

My aim is to update a partial to show course dates when a date range is specified and submitted.
I have a function that works as expected.
user selects a start date
user selects an end date
the user clicks search
results are logged to the console
Here is the function
function onFetchDataFromServer()
{
$course = Course::findOrFail( $this->param('id') );
$start = Input::get('start_date');
$end = Input::get('end_date');
$dates = $course->coursemetas->whereBetween('date', array($start, $end));
return $dates;
}
Here is the markup
<form class="row gx-3 align-items-center" data-request="onFetchDataFromServer" data-request-success="console.log(data)"">
<div class="col-12 col-lg pxp-has-left-border">
<div class="input-group mb-3 mb-lg-0">
<span class="input-group-text"><span class="fa fa-calendar-o"></span></span>
<input type="date" class="form-control" id="startPicker" name="start_date" placeholder="Choose a start date">
</div>
</div>
<div class="col-12 col-lg pxp-has-left-border">
<div class="input-group mb-3 mb-lg-0">
<span class="input-group-text"><span class="fa fa-calendar-o"></span></span>
<input type="date" class="form-control" id="endPicker" name="end_date" placeholder="Choose an end date">
</div>
</div>
<div class="col-12 col-lg-auto">
<button type="submit">Search dates</button>
</div>
</form>
So the rather than logging the results to the console, I now would like to update a partial.
I have a partial in the view called 'course/metas'.
Can someone please help me?
Thanks in advance.

You can try something like this. Check the documents here.
This is for a page's PHP section:
function onFetchDataFromServer()
{
$course = Course::findOrFail( $this->param('id') );
$start = Input::get('start_date');
$end = Input::get('end_date');
$dates = $course->coursemetas->whereBetween('date', array($start, $end));
$this['dates'] = $dates;
return [
'#myDiv' => $this->renderPartial('coursemetas')
];
}
This is for component plugin:
function onFetchDataFromServer()
{
$course = Course::findOrFail( $this->param('id') );
$start = Input::get('start_date');
$end = Input::get('end_date');
$dates = $course->coursemetas->whereBetween('date', array($start, $end));
$this->page['dates'] = $dates;
return [
'#myDiv' => $this->renderPartial('#coursemetas')
];
}
Note the # sign sent with the renderPartial as this tells the framework to look inside the plugin folder for the partial. Or you can specify the partial path by component and partial name like this return $this->renderPartial('course::coursemetas');.

Related

Error message "The GET method is not supported for this route. Supported methods: POST." in laravel 8

Following is my controller. Method ProjectsView is to view all the listings. The second method BackendProjectSearch is for searching of projects. The first page of search result is displayed properly, but when we click on next page it gives the error "The GET method is not supported for this route. Supported methods: POST."
What should I do ?
public function ProjectsView(){
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
public function BackendProjectSearch(Request $request){
$request->validate(["search" => "required"]);
$item = $request->search;
$projects = Projects::where('project_name','LIKE',"%$item%")->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
Following are the routes for both the methods :
Route::post('/backend/project/search', [ProjectsController::class, 'BackendProjectSearch'])->name('backend.project.search');
Route::get('/view', [ProjectsController::class, 'projectsView'])->name('projects.view');
View code :
<div class="col-md-8">
<div class="header-navsearch">
<form class="form-inline mr-auto" method="post" action="{{route('backend.project.search')}}">
#csrf
<div class="nav-search">
<input type="search" name="search" class="form-control header-search" placeholder="Search projects…" aria-label="Search">
<button class="btn btn-primary" type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</div>
The route for this request should be post, not get.
Example
Route::post(-----);
Also, make sure to insert a CSRF token while making the request
it means you now cannot do something like the following.
Instead, you have to do something like...
<form action="{{ route('example') }}" method="POST">
#csrf {{-- According to the version of laravel --}}
{{-- Your other codes --}}
<button type="submit" class="">Submit</button>
</form>
You have to use the below code
return redirect()->route('projects.view')->with(['projects' => $projects]);
Your route might be little change
Route::get('/view/{projects?}', [ProjectsController::class, 'projectsView'])->name('projects.view');
and In your controller, you have to change function like this
public function ProjectsView($projects = null){
if($projects!=null){
return view('backend.projects.projects_view',compact('projects'));
}
else{
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects'));
}

Issue with passing values from Form and Controller to Blade in Laravel

I have issue with send values from address localhost/product/1/1 to my database, I want attach product 1 to customer 1 and add special prices below I add code
Route:
Route::get('/product/{customerID}/{productID}', 'CustomerController#insertCustomerProductForm')->name('add-product');
Route::post('/product/{customerID}/{productID}', 'CustomerController#insertCustomerProductAction');
to Controller
insertCustomerProductForm method:
public function insertCustomerProductForm($customerID, $productID)
{
return view('customer_products.create', [
'customer' => Customer::find('$customerID'),
'product' => Product::find('$productID'), ]); }
insetCustomerProductAction method:
public function insertCustomerProductAction (Request $request, $customerID, $productID) {
$newCustomerProduct = new CustomerProduct;
$newCustomerProduct->product_id = $productID;
$newCustomerProduct->customer_id = $customerID;
$newCustomerProduct->selling_customer_price = $request->input('selling_customer_price');
$newCustomerProduct->purchase_customer_price = $request->input('purchase_customer_price');
$newCustomerProduct->consumed_customer_price = $request->input('consumed_customer_price');
$newCustomerProduct->save(); }
Model CustomerProduct
class CustomerProduct extends Model
{
public function customers()
{
return $this->belongsToMany(Customer::class);
}
public function products()
{
return $this->belongsToMany(Product::class);
}}
and when I try use in blade set values for product of customer I have only from form values (selling_customer_price... etc) nothing about product and customer? I don't know why or this find method is problem? Because I have to store special price for special customer in this form.
below I add part of blade code
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dodaj Produkt') }} </div>
<div class="card-body">
<form method="post">
#csrf
<div class="form-group row">
{{ $customer }}
<label for="selling_customer_price " class="col-md-4 col-form-label text-md-right">{{ __('Cena Sprzedaży') }}</label>
<div class="col-md-6">
<input id="selling_customer_price " type="text" class="form-control{{ $errors->has('selling_customer_price ') ? ' is-invalid' : '' }}" name="selling_customer_price " value="" required autofocus>
#if ($errors->has('selling_customer_price '))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('selling_customer_price ') }}</strong>
</span>
#endif
</div>
my error looking like it don't see variables from form:
selling_customer_price, purchase_customer_price, consumed_customer_price
I have error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'selling_customer_price' cannot be null (SQL: insert into `customer_products` (`product_id`, `customer_id`, `selling_customer_price`, `purchase_customer_price`, `consumed_customer_price`, `updated_at`, `created_at`) values (1, 1, , , , 2018-07-09 12:39:03, 2018-07-09 12:39:03))
Where exactly is your error coming from in both cases? insertCustomerProductForm should be working fine, as long as you pass the right parameters in the URL like so: localhost/product/20/10
POST request generally don't need parameters in the URL itself. You can retrieve the POST variables by doing $_POST['selling_customer_price'] in your insertCustomerProductAction method.

How to return view in controller?

I need to pull in data to my view but this doesn't work:
return view ('sub-domain', ['worker' => $worker ]);
Here is my code:
public function aerospace(Request $request , Worker $worker ){
$worker = $worker->newQuery();
if ($request->has('profession')) {
$worker->where('profession', $request->input('profession'));
}
if ($request->has('state')) {
$worker->where('state', $request->input('state'));
}
if ($request->has('local_govt')) {
$worker->where('local_govt', $request->input('local_govt'));
}
return $worker->get();
The above code brings out an array of data from the database which I can then filter with "domain/sub-domain?state=xyz"
Now when I try to pass in the data into my views using
return view ('sub-domain', ['worker' => $worker ]);
The page is loaded but no $worker data is loaded on the page. How can I pull the data? Here is my view file
<div class="row">
<form method="GET" action="">
Profession:<input type="text" name="profession"> State:<input type="text" name="state"> Local Govt:<input type="text" name="local_govt">
<button type="submit">Filter</button>
</form>
</div>
<div class="row">
#foreach ($worker as $worker)
<div class="col-lg-3 col-md-6">
<div class="member">
<div class="pic"><img src="avatar/{{$worker->avatar}}" alt=""></div>
<div class="details">
<h4>{{$worker->name}} {{$worker->l_name}}</h4>
<span>{{$worker->profession}}</span><br>{{ $worker->state }}
</div>
</div>
</div> #endforeach
</div>
I want to filter data by certain parameters, if there's a better way to do that please do let me know. But first I need the data to display.
You are returning a query instance, not a collection or singular model. That's why the get() method works. So first do:
$worker = $worker->get();

Adding Avatar Image to Profile Laravel 5

i want build an Profile Picture Avatar Upload and display it in the Profile for every user.
Buts dont work with my method.
My Avatar Upload code:
<div class="form-group">
<div class="form-group">
<label for="exampleInputFile"><img src="/img/photos.png" height="80" width="80"> Upload Avatar:</label>
<input type="file" id="exampleInputFile" name="profileimage"></font></br>
</div>
</div>
Code where everyone see it in Profile:
<div class="pull-left margin-left-25">
#if($user->profileimage == false)
<img src="/img/icon.png" height="80" width="80">
#endif
#if($user->profileimage == true)
<img src="{{$user->profileimage}}" height="80" width="80">
#endif
ProfileController image content (Dont work for me):
if ($request->hasFile('image')) {
$file = $request->file('profileimage');
$size = $request->file('profileimage')->getSize();
if ($size > 500000) {
session()->flash('errormessage','Image is too large');
return redirect()->back()->withInput();
}
if (substr($file->getMimeType(), 0, 5) !== 'profileimage') {
session()->flash('errormessage','File is not an image');
return redirect()->back()->withInput();
}
if ($file->isValid()) {
$path = $request->profileimage->store('uploads','public');
} else {
session()->flash('errormessage','Image is not valid');
return redirect()->back()->withInput();
}
}
if ($request->image !== null) {
$product->image = $path;
}
What i have done wrong?
Thanks!
Why don't use Validator class?It will be so much easier than what you have coded. As the following,
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:500000',
]);
Add the above code inside the method in which you store the file and do your things.
It will do the validation for you, then continue whatever you want to do with the file. For more options please check the link provided.
Also, in your HTML code. You need to have a form in first place, action and its method, so your code should be:
<div class="form-group">
<div class="form-group">
<form action="{{ route('profile'}}" method="post">
<label for="exampleInputFile"><img src="/img/photos.png" height="80" width="80"> Upload Avatar:</label>
<input type="file" id="exampleInputFile" name="profileimage"></font></br>
</form>
</div>
</div>
And in your web.php, you should have the following line:
Route::get('/URL', 'ProfileController#MethodName')->name('profile');

Laravel applying search filers

I have a page which has a search box(input text) which takes a place name as input and returns all the nearby dealers.
I also happen to have filters (checkboxes) for all the brand
<div class="col-sm-12 col-md-12">
{!! Form::checkbox('filters',$bike_oem, false,['style'=>'padding-right:5px;'] ) !!} <span style="padding-left:5px;"></span>{{ $bike_oem }}
</div>
How do I implement get the value of filter in my controller ?
<div class="col-sm-12 col-md-12">
<input style="padding-right:5px;" name="Hyundai " type="checkbox" value="Y"> <span style="padding-left:5px;"></span>Hyundai
</div>
This is how each filter appears in the page. Is the code correct to fetch the value in controller ? Please suggest
You can get the value of checkbox in this way also(in controller)
public function myFunction(Request $request){
if (isset($request['Hyundai']) && ($request['Hyundai'] == "on")) {
$value = "Y";
}
}

Resources