So I'm pretty new to laravel in general, and what I have is a search form that pulls information from the database and then calls it back on the same page, currently it's working like a redirect but I would like to know how to do this without having to refresh the page
This is the blade:
<form class="form-horizontal" role="form" id="policy-documents-search-form" action="/search" method="POST">
{{ csrf_field() }}
<fieldset>
<div class="form-group">
<label for="username" class="col-sm-6 control-label">Enter your policy number</label>
<div class="col-sm-8">
<input type="text" name="ordernumber" id="ordernumber" class="form-control"/>
<span class="text-danger">{{ $errors->first('ordernumber') }}</span>
</div>
</div>
#if (session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
#endif
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" class="btn btn-primary" id="search-button">Search</button>
</div>
</div>
<div class="form-group">
<div class="container">
#if(isset($order))
<h2>Your Policy Details</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Claims Telephone</th>
<th>Policy Wording</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ #$order->scheme->Description }}</td>
<td>{{ #$order->scheme->ClaimsTelephone1 }}</td>
<td>Policy Wording </td>
</tr>
</tbody>
</table>
#endif
</div>
</div>
</div>
</fieldset>
</form>
This is the Controller function:
public function search(Request $request) {
if ($this->validate($request, [
'ordernumber' => 'string|min:8|max:16',
], [
'ordernumber.string' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
'ordernumber.min' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
'ordernumber.max' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
]));
try {
$order = Order::findOrFail(decodeFullOrderNumber($request->ordernumber));
} catch (ModelNotFoundException $exception) {
return back()->withError('We could not find this policy number in our system, please try again')->withInput();
}
return view('policy_wording', compact('order'), [
'title' => "Policy Wording Results",
]);
}
And this is the route:
Route::get('/policy-wording',
'PolicyWordingController#policyWordingPage');
Route::any('/search', 'PolicyWordingController#search');
First of all i suggest to use Vuejs for that purposes so u can not think about how to rebuild your table, etc.
On the serverside all you need to do is return search result if was ajax
if ($request->isXmlHttpRequest())
return $order->toArray();
before return view()
To do it with AJAX, you need a front end solution, like Axios or jQuery, in order to make the AJAX requests.
Once the request is sent, you can handle it like a regular POST request and then return a JSON or a html.
For JSON, it's pretty simple, every array or model you return will be converted to JSON by default.
To return a view however, you need to use the render method. This method will "render" the view and return you the corresponding HTML.
So, instead of :
return view('policy_wording', compact('order'), [
'title' => "Policy Wording Results",
]);
you should have something like :
return view('policy_wording', compact('order'), [
'title' => "Policy Wording Results",
])->render(); //notice the render method here
Then all you need to do is to handle the response in your front-end.
Edit about validation
If your validation fails, it'll return a 422 error (Unprocessable Entity), so you can handle it like any other ajax error.
Related
I'm very confused, I need your help, this is the error:
Missing required parameter for [Route: single.temp] [URI: singlepost/{name}] [Missing parameter: name]. (View: C:\Users\Toshiba\Desktop\working\mouhawla\resources\views\index.blade.php)
The search field:
<div class="search">
<form role="form" action="{{route('single.temp')}}">
<i class="fa fa-search"></i>
<div class="field-toggle">
<input type="text" name="name" class="search-form" autocomplete="off" placeholder="Search">
</div>
</form>
</div>
The method:
public function getPostByName($name) {
$products = DB::table('templates')
->where('name', $name)
->first();
return view('singlepost', compact('products'));
}
The route:
Route::get('/singlepost/{name}', 'App\http\controllers\TemplatesController#getPostByName')->name('single.temp');
The final view:
<h1 style="text-align: center;">ACH-template</h1>
<table>
<tr>
<td><img src="/storage/{{$products->image_path}}"></td>
<td><img src="/storage/{{$products->image_path2}}"></td>
<td><img src="/storage/{{$products->image_path3}}"></td>
<td>
<p>
<h2 style="text-align:center;">{{$products->name}}</h2>
</br>
<p>{{$products->description}}</p>
</p>
</td>
</tr>
</table>
<a href="/storage/{{$products->file_path}}" class="btn btn-primary">
<button class="btn" style="width:100%">
<i class="fa fa-download"></i> Download
</button>
</a>
The error is very explanatory. You are trying to use /singlepost/{name} route, but on your blade file, you are doing route('single.temp'), it is telling you that it needs the parameter name, else it cannot create the URL as it is a missing parameter.
You should have something like:
<form role="form" action="{{route('single.temp', ['name' => VALUE'])}}">
But that will not solve your problem, as you are trying to do a search, so you want something like /singlepost/John, and John is going to be input by the user on the input field. So you have to do an AJAX call because {{ route('single.temp') }} is going to be rendered by PHP and served to the user, so it is always going to miss the needed parameter.
What you can also do is get that value from the Request instead of a URL parameter.
You have defined a route which requires a parameter: {$name}. You have also used the route helper to generate a URL which takes the name of a route as the first argument and an array of parameters as an optional second argument.
When you have used route('single.temp') in your form action, you have not specified any parameters and so Laravel is throwing the error you're seeing. To resolve this error, you would need to specify a $name parameter as the second argument (i.e. route('single.temp', ['name' => 'something'])). This is not ideal though as if you're using $name as a search term, you don't know the value when the page is first rendered and so can't provide that value.
There are a few ways you could achieve your goal of searching records, a basic example of how you could do this follows.
web.php
Define two routes, the first to return a view with a form and another to process the form submission and show the results.
Route::get('/templates', [TemplateController::class, 'index'])
->name('templates.index');
Route::get('/templates/search', [TemplateController::class, 'search')
->name('templates.search');
TemplateController.php
Define the two functions which will be used when one of the routes defined above is requested.
class TemplateController extends Controller
{
// return a view
public function index()
{
return view('templates.search', ['templates' => []]);
}
// process the form submission
// perform a search for the $request search term
// return a view with the results
public function search(Request $request)
{
$request->validate([
'term' => ['required', 'string']
]);
$templates = Template::where('name', $request->term)->get();
return view('templates.search', ['templates' => $templates]);
}
}
templates/search.blade.php
{{-- create a form which will submit to the search route --}}
{{-- note I use GET rather than POST here, explained later --}}
<form action="{{ route('templates.search') }}" method="GET">
#csrf
<input type="text" id="term" name="term" />
<button type="submit">
{{ __('Search') }}
</button>
{{-- loop over and show results if there are any --}}
#forelse ($templates as $template)
{{ $template->name }}
#empty
{{ __('Empty') }}
#endforelse
</form>
The above should be self explanatory. My reason for using GET rather than POST in the search is because the value will be added to the URL as a query string parameter meaning it can be bookmarked or shared with ease.
i have a question about the Laravel search function, i had follow the guildeline online and i still fail to search the category, can someone guide me and tell me where i did wrongly ? Much appreciated
My category Controller php code:
public function search(Request $request)
{
$search = $request->get('search');
$posts = DB::table('bit_app_policy_category')->where('id','like','%' .$search. '%')->paginate(5);
return view('category.index',['posts' => $posts]);
}
My index.blade code
<div align="left">
<div class="col-md-4">
<h1>Policy</h1>
</div>
<div class="col-md-4">
<form action="/search" method="get" role="search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="_method" placeholder="Search ID / Code"> <span class="input-group-btn">
<button type="submit" class="btn btn-primary">Search</button></span>
</div>
</form>
</div>
</div>
web.php
Route::get('/search','categoryController#search');
What error i get is here
Error image
interface
Database
You are sending $posts variable to your view. But the error says you are referencing a $category variable.
return view('category.index',['posts' => $posts]);
Maybe you might want to update view to use $posts. If you could post your full code (category/index.blade.php) we might be able to help you better.
__
Here is how I would do:
$categories= DB::table('bit_app_policy_category')->where('id','like','%' .$search. '%')->paginate(5);
return view('category.index',['categories' => $categories]); //you can also use compact return view('category.index', compact('categories') );
And to display:
#foreach( $categories as $category )
<div>{{ $category->id }}</div>
#endforeach
Another tip: you can name your routes like so
Route::get('search','categoryController#search')->name('search');
Then you can reference this route (in form or anywhere else you want) like so:
<form action="{{ route('search') }}" ..>
good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
I know that this is generally frowned upon, but for my specific reasons which I'll state below, I need this functionality:
So what we're doing on this website is that we are allowing users to buy "stores" on which they can sell products, and now those users want to add stuff like "Facebook Pixel" to their stores to allow them to track different activities.
Here's my form responsible for the code
<form action="{{ url('vendor/store/settings/analytics/update') }}" method="POST" style="margin-top: 30px;">
{{ csrf_field() }}
<div class="analytics-form">
<div class="col-md-8 col-md-offset-2 analytics-box">
<div class="form-group">
<label for="">Please pick a type of analytics to install:</label>
<select name="analytic_type[]" id="" class="form-control">
#foreach($analytic_types as $type)
<option value="{{ $type }}">{{ ucwords(str_replace('_', ' ', $type)) }}</option>
#endforeach
</select>
<br>
</div>
<div class="form-group">
<label for="">Please type/paste the code for this analytic:</label>
<textarea class="form-control" cols="5" rows="5" name="analytic_code[]" required></textarea>
<br>
</div>
</div>
</div>
<button class="btn btn-primary btn-block" id="applyAnalytics" type="submit" {{ $store->vendor->hasAnalytics() ? '' : 'disabled'}}>Apply Changes</button>
</form>
And here's the controller method I want to "hit":
public function updateAnalytics(Request $request)
{
try {
$store = auth()->user()->store;
auth()->user()->analytics()->delete();
if($request->has('analytic_type')) {
foreach($request->analytic_type as $index => $value) {
Analytics::create([
'user_id' => auth()->user()->id,
'analyticable_id' => $store->id,
'analyticable_type' => get_class($store),
'method_type' => $request->analytic_type[$index],
'method_code' => $request->analytic_code[$index],
]);
}
}
flash(__("Common.Saved_Successfully"));
} catch (\Exception $e) {
session()->flash('title', __("Common.Error"));
session()->flash('message', __("Common.An_Error_Happened"));
session()->flash('message-class', "error");
}
return redirect()->back();
}
This method works fine locally if I enter either normal text or code into the textarea, but if I tried to enter & submit the below block of code everything blows up, this block of code is the one provided by Facebook Pixel to its users, which I want to save in my database:
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '339673053324500');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=339673053324500&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->
If I put the above code into the text area and submit the data to the server, I get this error below:
Forbidden
You don't have permission to access /app/public/vendor/store/settings/analytics/update on this server.
Additionally, a 403 Forbidden error was encountered while trying to
use an ErrorDocument to handle the request.
The server isn't even allowing me to hit the route in question, or any other route from this form as long as I am submitting code.
Note:
This is probably not an actual permission issue but a security related thing, because I've tried changing permissions on the server for all of the involved files from 0644 to 0755 and nothing changed, of course I might have done something wrong along the way, all suggestions are welcome.
I am using Laravel 5.3.18 to build a form that allows the user to enter one or more dates. I am also using the HTML/Form library from the Laravel Collective along with a FormRequest object to validate the fields. My problem is when the user dynamically adds in more date inputs (via JavaScript) and submits the form, if it doesn't pass validation, the "dynamically" added data (and inputs) are not redisplayed on the form.
My question is: Does Laravel handle this use case? And if so, how can I make this work (or what am I doing wrong)? Your insights and help are much appreciated!
Here is the actual snippet of code that initially generates the date inputs:
#foreach ($eventDates as $index=>$eventDate)
<div class="form-group{{ $errors->has('eventDates.'.$index.'.start_datetime') ? ' has-error' : '' }}" id="{{ 'event_date_group_'.$index }}">
{!! Form::label('eventDates['.$index.'][start_datetime]', 'Event Dates (Day '.($index + 1).')', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-3">
{!! Form::text('eventDates['.$index.'][start_datetime]', $eventDate['start_datetime'], ['id' => 'start_datetime_'.$index, 'class' => 'datetimepicker form-control']) !!}
#if ($errors->has('eventDates.'.$index.'.start_datetime'))
<span class="help-block"><strong>{{ $errors->first('eventDates.'.$index.'.start_datetime') }}</strong></span>
#endif
</div>
</div>
#endforeach
which generates this:
<div class="form-group" id="event_date_group_0">
<label for="eventDates[0][start_datetime]" class="col-md-4 control-label">Event Dates (Day 1)</label>
<div class="col-md-3">
<input id="start_datetime_0" class="datetimepicker form-control" name="eventDates[0][start_datetime]" type="text">
</div>
</div>
So, if the user dynamically creates another date input, it will look as follows:
<div class="form-group" id="event_date_group_0">
<label for="eventDates[0][start_datetime]" class="col-md-4 control-label">Event Dates (Day 1)</label>
<div class="col-md-3">
<input id="start_datetime_0" class="datetimepicker form-control" name="eventDates[0][start_datetime]" type="text">
</div>
</div>
<div class="form-group" id="event_date_group_1">
<label for="eventDates[1][start_datetime]" class="col-md-4 control-label">Event Dates (Day 2)</label>
<div class="col-md-3">
<input id="start_datetime_1" class="datetimepicker form-control" name="eventDates[1][start_datetime]" type="text">
</div>
</div>
And here is part of my FormRequest object:
public function rules() {
return [
'name' => 'required|max:100',
'eventDates.*.start_datetime' => 'required',
'eventDates.*.end_datetime' => 'required',
...
];
}
public function messages() {
return [
'eventDates.*.start_datetime.required' => 'Start date/time is required.',
'eventDates.*.end_datetime.required' => 'End time is required.',
...
];
}
Lastly, the validation works. The error messages show up for the dates input. In fact, if I dynamically create the extra date inputs. Fill everything out but leave just the dynamic date inputs blank, the validation will fail and the form will redisplay but the dynamic inputs and data don't show up. I also put in the following debug statement in the template to see how many elements come back in the array and it always show just 1.
<p>Number of Dates: {{ count($eventDates) }}</p>