Pagination after search only works on the first page - php

The first page will be sorted correctly. However, the second page (and further) will go back to being as if no fields in the search were filled at all.
I am collecting the search fields in the form below:
{{ Form::open(['route' => 'admin.users.search', 'method' => 'get', 'class' => 'navbar-form navbar-left form-inline', 'role' => 'search']) }}
<div class="form-group">
{{ Form::text('user_id', request('user_id'), ['class' => 'form-control', 'size' => '8', 'placeholder' => 'ID']) }}
</div>
<div class="form-group">
{{ Form::email('email', request('email'), ['class' => 'form-control', 'size' => '20', 'placeholder' => 'Email']) }}
</div>
<div class="form-group">
{{ Form::text('first_name', request('first_name'), ['class' => 'form-control', 'size' => '20', 'placeholder' => 'First Name']) }}
</div>
<div class="form-group">
{{ Form::text('family_name', request('family_name'), ['class' => 'form-control', 'size' => '20', 'placeholder' => 'Family Name']) }}
</div>
<div class="form-group">
<div class="selectize-lg">
{{ Form::select('institution_id', $institutions, request('institution_id'), ['class' => 'form-control', 'size' => '200', 'data-selectize']) }}
</div>
</div>
<div class="form-group">
<div class="selectize-lg">
{{ Form::select('exam_id', $exams, request('exam_id'), ['class' => 'form-control', 'data-selectize']) }}
</div>
</div>
<div class="form-group ">
{{ Form::submit('Search', ['class' => 'btn btn-default']) }}
</div>
Clear
{{ Form::close() }}
Once the form has been submitted it will hit a GET route
Route::get('members/search', 'UsersController#search')->name('admin.users.search');
Then the users controller:
$users = User::with('exam', 'institution');
if ($request->has('user_id')) {
$users->whereId($request->user_id);
}
if ($request->has('email')) {
$users->whereEmail($request->email);
}
if ($request->has('first_name')) {
$users->where('first_name', 'LIKE', "%{$request->first_name}%");
}
if ($request->has('family_name')) {
$users->where('family_name', 'LIKE', "%{$request->family_name}%");
}
if ($request->has('institution_id')) {
$users->whereInstitutionId($request->institution_id);
}
if ($request->has('exam_id')) {
$users->whereExamId($request->exam_id);
}
$users = $users->latest()->paginate(48);
$usersTotal = $users->total();
$exams = ['' => 'Exam...'] + Exam::orderBy('title')
->pluck('title', 'id')
->all();
$institutions = ['' => 'University...'] + Institution::orderBy('name')
->pluck('name', 'id')
->all();
return view('admin.users.index', compact('users', 'usersTotal', 'exams', 'institutions'));
Then, in the view I am adding the pagination links like this:
{{ $users->appends(array_filter(request()->except('page')))->render() }}
However, the search results only work on the first page. for example, the route on the first page will look like this:
search?user_id=&email=hello%40world&first_name=John&family_name=Smith&institution_id=1&exam_id=1
But the second page will look like this:
search?page=2
I am finding this pretty puzzling and not too sure what is causing the search to fail on the second page.

From the docs:
Appending To Pagination Links
You may append to the query string of pagination links using the
appends method. For example, to append sort=votes to each pagination
link, you should make the following call to appends:
{{ $users->appends(['sort' => 'votes'])->links() }} If you wish to
append a "hash fragment" to the paginator's URLs, you may use the
fragment method. For example, to append #foo to the end of each
pagination link, make the following call to the fragment method:
{{ $users->fragment('foo')->links() }}
You are almost on the right track with this:
{{ $users->appends(array_filter(request()->except('page')))->render() }}
Wat this peace of code does is carry over the page-request when you switch pages, which is necessary since that is done for you. So you will need to specify the request data that you would like to keep. So for example:
{{ $users->appends(Request::except('page'))->links() }}
will add all request data to the next page, except the pagination links because that is added by default.
Note: i notice that you are sending id's with GET requests , please be carefull doing that. Users with bad intentions can see you database structure and possible take use of it.

Related

Routing correctly in Laravel

I am learning Laravel 5.7.15.
I am trying to update data in Laravel. When I update client comment, I get MethodNotAllowedHttpException.
I have already looked at the other posts related to this error but still now get it fixed, please help me.
Laravel drives me crazy.
Here is my html
{!! Form::open(['url' => '/client_report/'.$id.'/edit', 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
{{ csrf_field() }}
<div class="form-group">
{{Form::text("Comment",$client->client_comments, array('id'=>'comment' 'class' => 'form-control', 'disabled' => 'disabled', 'placeholder'=>'Client Comments')) }}
<p>{{Form::submit('Submit',['class'=>'btn btn-space btn-success'}}</p>
</div>
and Route has
Route::get('/client_report/{id}/{edit}',function($id) {
return view('clientEdit')
->with('id',$id);
})->middleware('auth');
Route::post('/client/submit/{id}/edit', ['uses' => 'clientController#editClient']);
and Controller has
class clientController extends Controller {
function editClient(Request $request, $id) {
$client = Client::find($id);
$client->comment = $request->get('comment');
$client->save();
}
}
Any help will be greatly appreciated.
You are hitting the wrong url.
In your html you are using
Form::open(['url' => '/client_report/'.$id.'/edit' ...
But your update route is
Route::post('/client/submit/{id}/edit' ...
Change the URL in your form, also make sure to make a POST request instead of GET.
Updating a resource should have PUT/PATCH route according to restful convention.
PS: current laravel version is 7.x, I would recommend you learn laravel 6.x at least, and HTML From Collectives (as far as I remember that's what they are called) are deprecated. You should not use deprecated tech.
I think the url you're passing here is wrong.
{!! Form::open(['url' => '/client_report/'.$id.'/edit', 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
This above method is for edit, while you click on submit button it should redirect to /client/submit/{id}/edit this url.
Make you form url as below.
{!! Form::open(['url' => '/client/submit/'.$id.'/edit', 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
01. first change your router method to PUT
Route::put('/client/submit/update/{id}', ['uses' => 'clientController#editClient']);
02. change your form
{!! Form::open(['action' => ['clientController#editClient', $id ],'method' => 'POST', 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
{{Form::text("Comment",$client->client_comments, array('id'=>'comment' 'class' => 'form-control', 'disabled' => 'disabled', 'placeholder'=>'Client Comments')) }}
{{ Form::hidden('_method', 'PUT')}}
{{ Form::submit('submit', [ 'class' => 'btn btn-primary m-t-15 m-b-15'])}}
{!! Form::close() !!}
Change the route to:
Route::match(['put', 'patch'], '/client/submit/{id}', 'clientController#editClient');
And the form to:
{!! Form::open(['url' => '/client_report/'.$id, 'class' => 'form-horizontal group-border-dashed col-lg-6' ]) !!}
{{ csrf_field() }}
#method('PUT')
...
https://laravel.com/docs/master/routing#form-method-spoofing

localhost is currently unable to handle this request. HTTP ERROR 500 with Laravel

I am trying to edit a JSON formatted category with PUT method, so I am using guzzleHttp library to parse json requests and responses with laravel 5.5.
My POST, GET methods are working fine when I am trying to grab or insert data into my server, but I am getting error on PUT & DELETE method.
There are two types of errors I am getting :
localhost is currently unable to handle this request. HTTP ERROR 500
Out Of Memory - Fatal error: Out of memory (allocated 1472200704) (tried to allocate 176128 bytes)
Console Error :
These errors occurs not together just one after another if I request twice in row.
I have trying to change allocated memory, but it did not work !
Here are my procedures to handle a request :
My Controller :
public function update(Request $request, $id)
{
// get the inputs
$inputs = [
"cat_id" => $id,
"cat_name" => $request->input('cat_name'),
"cat_slug" => $request->input('cat_slug'),
"cat_description" => $request->input('cat_description'),
"cat_parent_id" => $request->input('cat_parent_id')
];
// post to the database
$response = $this->categories->update($id, $inputs);
if($response['success']){
$message = $response['message'];
Session::flash('success', 'Category is successfully saved !'.' Server Response Message : '.$message);
return redirect()->route('categories.index');
}else{
$message = $response['message'];
Session::flash('success', 'Category is not successfully saved !'.' Server Response Message : '.$message);
return redirect()->route('categories.index');
}
/////////////////////////////////////////////////
// If the edit page should be shown
//return redirect()->route('categories.edit', $id);
}
My Repository :
public function update($id, $category){
return $this->update("categories/{$id}", $category);
}
And My Custom GuzzleHttpRequest.php :
protected function update($url, $data){
$formatted_data = json_encode($data);
$request = $this->client->request('PUT', $url, [
'body' => $formatted_data
]);
$response = json_decode( $request->getBody()->getContents() , true );
return $response;
}
My Server Accepts JSON formatted inputs : https://rest-banai.herokuapp.com/
Edited :
And My Edit Form :
{!! Form::open(['route' => ['categories.update', $category['cat_id']], 'method' => 'PUT', 'data-parsley-validate' => '']) !!}
<div class="form-group">
{{ Form::label('cat_name', 'Name:') }}
{{ Form::text('cat_name', $category['cat_name'], ['class' => 'form-control', 'placeholder' => 'Enter category name ...', 'required' => '', 'maxlength' => '50']) }}
</div>
<div class="form-group">
{{ Form::label('cat_slug', 'Slug:') }}
{{ Form::text('cat_slug', $category['cat_slug'], ['class' => 'form-control', 'placeholder' => 'Enter a slug word ...', 'required' => '', 'maxlength' => '50', 'data-parsley-type' => 'alphanum']) }}
</div>
<div class="form-group">
{{ Form::label('cat_description', 'Description:') }}
{{ Form::textarea('cat_description', $category['cat_description'], ['class' => 'form-control', 'rows' => '3', 'placeholder' => 'Enter description of the category ...', 'maxlength' => '255']) }}
</div>
<div class="form-group">
{{ Form::label('cat_parent_id', 'Parent Category:') }}
<br />
{{ Form::select('cat_parent_id', $cat_array, null, ['placeholder' => $cat_parent_name]) }}
<br />
</div>
<div class="pull-right">
{{ Form::submit('SAVE', ['class' => 'btn btn-block btn-success btn-sm']) }}
</div>
{!! Form::close() !!}
I am not sure what is I am doing wrong here, any expert, please help me with the issue as I am new with Guzzle and JSON working with Laravel, it will be appreciated.
And If anythings unclear here, please suggest to edit.
Thanks In Advance !
Change your request to
$request = $this->client->request('PUT', $url,['json'=> $data]);
You are using resourceful routes, and yet you have a lot of complexity in your code. This quite frankly in my opinion is completely unnecessary. I will accomplish what you are doing in the following way:
Routes
Route::resource('category', 'CategoryController');
Controller
public function edit(Category $category)
{
return view('category.edit', compact('category'));
}
public function update(Request $request, Category $category)
{
try {
$category->update($request->all()->except(['_token']));
Session::flash('success', 'Category is successfully saved !');
} catch(\Exception $exception) {
Session::flash('error', 'Unable to update category!');
}
return redirect(route('category.index'));
}
HTML
category/edit.blade.php
{!! Form::open(['route' => route('categories.update', $category), 'method' => 'PUT', 'data-parsley-validate' => '']) !!}
<div class="form-group">
{{ Form::label('cat_name', 'Name:') }}
{{ Form::text('cat_name', $category->cat_name, ['class' => 'form-control', 'placeholder' => 'Enter category name ...', 'required' => '', 'maxlength' => '50']) }}
</div>
<div class="form-group">
{{ Form::label('cat_slug', 'Slug:') }}
{{ Form::text('cat_slug', $category->cat_slug, ['class' => 'form-control', 'placeholder' => 'Enter a slug word ...', 'required' => '', 'maxlength' => '50', 'data-parsley-type' => 'alphanum']) }}
</div>
<div class="form-group">
{{ Form::label('cat_description', 'Description:') }}
{{ Form::textarea('cat_description', $category->cat_description, ['class' => 'form-control', 'rows' => '3', 'placeholder' => 'Enter description of the category ...', 'maxlength' => '255']) }}
</div>
<div class="form-group">
{{ Form::label('cat_parent_id', 'Parent Category:') }}
<br />
{{ Form::select('cat_parent_id', $cat_array, null, ['placeholder' => $cat_parent_name]) }}
<br />
</div>
<div class="pull-right">
{{ Form::submit('SAVE', ['class' => 'btn btn-block btn-success btn-sm']) }}
</div>
{!! Form::close() !!}
```

phalcon form add options

I have a problem with phalcon form. I added a form but i can not add options like
[
'id' => 'login-form',
'class' => 'form form-x',
'data-form-style' => 'dynamic, rootable, hash',
'data-encrypt' => 'false'
]
I want to add all of them which called setuserOption in phalcon document but I can't do that.
//form add user options
$this->setuserOptions(
[
'id' => 'login-form',
'class' => 'form form-x',
'data-form-style' => 'dynamic, rootable, hash',
'data-encrypt' => 'false'
]
);
//my form
$this->setuserOptions([
'id' => 'login-form',
'class' => 'form form-x',
'data-form-style' => 'dynamic, rootable, hash',
'data-encrypt' => 'false'
]);
}
//this is volt ( form.options is written by me .how can i use this options )
{{ content() }}
{{ form('login/login', form.options) }}
<div class="form-group">
{{ form.label('username') }}
{{ form.render('username', ['class': 'form-control']) }}
</div>
<div class="form-group">
{{ form.label('password') }}
{{ form.render('password', ['class': 'form-control']) }}
</div>
<div class="form-group">
{{ form.render('submit', ['class': 'btn btn-primary btn-large']) }}
</div>
</form>
If you look at the documentation, you can add properties to your form tag like this:
<?php
echo Phalcon\Tag::form(array("posts/save", "method" => "post"));
or with the Volt syntax:
<?php
{{ form("posts/save", "method": "post") }}

How can I make a search that is filtered by multiple inputs in Laravel 4.2?

I want this form to search multiple fields. How can I aggregate these search terms and filter them by their appropriate fields?
For example, if the user types "Book" into the textsearch field, and then selects "Assigned" from the status dropdown, the page should return all requests containing 'book' in the subject or details field, and 'assigned' in the status field.
I have the following form in my Laravel 4.2 Application:
{{ Form::open(['route' => 'requests.search']) }}
<!-- Text Search Form Input -->
<div class="form-group">
{{ Form::label('textsearch', 'Text Search:') }}
{{ Form::text('textsearch', $query, ['class' => 'form-control']) }}
{{ Form::hidden('search', 'text') }}
</div>
<!-- Status Form Input -->
<div class="form-group">
{{ Form::label('status', 'Status:') }}
{{ Form::select('status', $statuses, null, ['class' => 'form-control']) }}
</div>
<!-- Category Form Input -->
<div class="form-group">
{{ Form::label('category', 'Category:') }}
{{ Form::select('category', $categories, null, ['class' => 'form-control']) }}
</div>
<!-- Teamleader Form Input -->
<div class="form-group">
{{ Form::label('teamleader', 'Team Leader:') }}
{{ Form::select('teamleader', $projectmembers, null, ['class' => 'form-control']) }}
</div>
<!-- Requestid Form Input -->
<div class="form-group">
{{ Form::label('requestid', 'Request ID:') }}<br/>
<span>Between:</span>
{{ Form::text('requestidstart', null, ['class' => 'form-control', 'style' => 'width:100%;']) }}
<span>And:</span>
{{ Form::text('requestidend', null, ['class' => 'form-control', 'style' => 'width:100%;'])}}
</div>
<!-- Requestdate Form Input -->
<div class="form-group">
{{ Form::label('requestdate', 'Request Date:') }}<br/>
<span>From:</span>
{{ Form::text('requestdatestart', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;']) }}
<span>To:</span>
{{ Form::text('requestdateend', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;'])}}
</div>
<!-- Requestduedate Form Input -->
<div class="form-group">
{{ Form::label('requestduedate', 'Due Date:') }}<br/>
<span>From:</span>
{{ Form::text('requestduedatestart', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;']) }}
<span>To:</span>
{{ Form::text('requestduedateend', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;'])}}
</div>
{{ Form::submit('Search') }}
{{ Form::close() }}<br/>
Controller:
$requestresponsetype = ['' => ''] + RequestResponseType::lists('description', 'description');
$projectmembers = ['' => ''] + RequestProjectMember::lists('first_name', 'first_name');
$statuses = ['' => ''] + RequestStatus::lists('description', 'description');
$categories = ['' => ''] + RequestCategory::lists('description', 'description');
$query = Input::get('textsearch');
$requests = DataRequest::where("subject", "LIKE", "%$query%")->orWhere("details", "LIKE", "%$query%")->orWhere("id","LIKE","%$query%")->paginate(10);
return View::make('requests.index', ['requests' => $requests, 'statuses' => $statuses, 'requestresponsetype' => $requestresponsetype, 'projectmembers' => $projectmembers, 'categories' => $categories, 'query' => $query]);
I don't understand your idea clearly, but I guess something like:
$requests = DataRequest::where(function($q) {
$q->where("subject", "LIKE", "%$query%")
->orWhere("details", "LIKE", "%$query%")
->orWhere("id","LIKE","%$query%");
})
->where('status', '=', $status)
->paginate(10);
In my project, I created a scope to search, it's reuseable and readable.
//BaseModel
public function scopeSearch($query, $search, $fields)
{
$query->where(function($q) use ($search, $fields) {
foreach ($fields as $field) {
$q->orWhere($field, "LIKE", "%$search%");
}
}
}
$requests = DataRequest::search($query, ["subject", "details", "id"])
->where('status', '=', $status)
->paginate(10);

updating of records in laravel 4.2

Hello im new in laravel 4.2 and i m making an application in the controllers, i made my own function called c_updateSystemUser($id) and here is the code
public function c_updateSystemUser($id)
{
//
session_start();
$getsCapt = $_SESSION["captcha"];
$rules = array(
'username' => 'required|min:2|max:50|regex:/^[a-zA-Z0-9\-\s]+$/|exists:dbo_systemusers,SystemUserName,$id',
'description' => 'required|min:1|max:100|regex:/^[a-zA-Z0-9\-\s]+$/',
'usertype' => 'required|numeric',
'capt' => 'required|numeric'
);
$validator = Validator::make(Input::all(), $rules);
// process the inputs given by the user
if ($validator->fails())
{
return Redirect::to('viewsu/' . $id)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
// store the values into the database
$su = SystUser::find($id);
$su->SystemUserTypeID = Input::get('usertype');
$su->SystemUserName = Input::get('username');
$su->SystemUserDescription = Input::get('description');
$su->timestamps = false;
$su->save();
Session::flash('message', 'Successfully created system user!');
return Redirect::to('viewsu');
}
}
}
i wanted this function to be called when the user clicked the update button on my view file but when the button is clicked, it is redirecting to some other page (my create user page) i don't know why
here is the code of my form in my blade
{{ Form::model($su, array('route' =>array('csu.update',$su->SystemUserID),'method'=>'PUT'))}}
<div class="form-group">
{{ Form::label('usertype', 'User Type') }}
{{ Form::select('usertype', [null=>'Please Select user type'] + $sTyp , array('class'=>'form-control'))}}
{{ Form::label('current' , 'Current Type: (unedited) '.$su->SystemType , array('class' => 'label label-primary')) }}
</div>
<div class="form-group">
{{ Form::label('username', 'Username') }}
{{ Form::text('username', $su->SystemUserName, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('description', 'Description') }}
{{ Form::textarea('description', $su->SystemUserDescription, array('class' => 'form-control','rows' => '3')) }}
</div>
<div class="form-group">
{{ Form::label('captcha', 'CAPTCHA image: ') }}
</br>
{{ HTML::image('http://localhost:8080/laravel3/app/captcha.php', 'alt' , array( 'width' => 200, 'height' => 35 )) }} </br></br>
{{ Form::text('capt', Input::old('capt'), array('class' => 'form-control','placeholder' => 'enter generated captcha')) }}
</div>
{{ Form::submit('Edit System User', array('class' => 'btn btn-primary')) }}
{{ Form::close()}}
i don't know how to make the form call the function public function c_updateSystemUser($id) in my controller
my controller file is called systemUsers.php
any ideas? any help would be appreciated
If your view name is update and its in views->csu folder you can do it like following
{{ Form::model($su, array('route' =>array('csu.update.c_updateSystemUser',$su->SystemUserID),'method'=>'PUT'))}}
#yourentry
{{Form::close()}}
Your route should be like following:
Route::resource('csu','systemUsers');
In systemUsers.php add c_updateSystemUser($id){} method.

Categories