laravel - make a search form and show result in same page - php

in my show method in laravel i have a form that i want to submit and show the result on the same page so here is my show method first of all :
public function show(Property $property)
{
$property = Property::with('propertycalendars')->where('id', $property->id)->first();
foreach ($property->propertycalendars as $prop) {
$end_reserve = $prop->reserve_end;
}
// HERE NEW RELATION
$pdate = Property::with('dates')->get();
return view('users.properties.show', compact('property','pdate','end_reserve'));
}
and in the view of my show which for example is the url of a uniq property like below just as an example :
http://localhost:8000/properties/1
now i have a form to submit to search the Date table and bring me the dates so here is what i have wrote for the search function :
public function search (Request $request,$property_id){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the search has something in it.
if (!empty($request->property_id)) {
$start_date = $request->start_date;
$search_date = Date::all()->where('date',$start_date);
}
return view('admin.properties.show')->with('search_date', $search_date);
}
and
thats my route :
Route::get('/properties/{{property_id}}','PropertyController#search');
and finally my form to submit the search :
<form action="/properties/search" method="get">
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<input type="hidden" value="{{$property->id}}" name="property_id">
<input name="start_date" class="form-control m-input start_date" autocomplete="off"> </div>
<div class="col-lg-5">
<input name="finish_date" class="form-control m-input start_date" autocomplete="off"> </div>
<div class="col-lg-2">
<input type="submit" value="seach" class="btn btn-primary btn-block" autocomplete="off">
</div>
</div>
</form>
but now when i submit the form it returns a 404 not found with a link like below :
http://localhost:8000/properties/search?_token=R8ncSBjeZANMHlWMcbC6o5mYJZfwWgdfTwuviFo1&property_id=1&start_date=1398%2F1%2F12&title=

In your controller, change to the following:
public function search (Request $request){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the search has something in it.
if (!empty($request->title)) {
$results = Property::all()->where('some search here')->get();
}
return view('admin.article.index')->with('results', $results);
}
This will send any (and all) results that your query finds to the view. Now in your view, you'll need to ensure there are actual results, or you'll get an error, so for example:
#if ($results)
//There are results, loop through them
#foeach($results as $item)
{{$item->title}}
#endforeach
#else
//There are no results, show the form maybe?
#endif
Without knowing your table structure, I can't give the exact way to loop through your results, but this should get you started.
Edit: Since OP's question nature changed a fair bit from the original question:
In order to achieve the new flow, you'd need to pass in a URL param in the route, and change it to be a get, since you're no longer posting it from a form:
Route::get('/properties/{search}','PropertyController#search');
This tells Laravel you've got something coming from a website.com/properties/xxxxx request - the xxxxx would contain the search key you'd then pass to your controller to lookup. The {search} portion in the route can be whatever name you want, just ensure the controller's second param matches it.
If you wanted to allow for a posting from your search form, you can (in addition) add the following to your routes:
Route::post('/properties','PropertyController#search');
Then in your controller, fetch whatever came from the form via the Request facade.
Then in your controller, you'd check if this is valid:
public function search (Request $request, $search){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the second URL param has a value
if (!empty($search)) {
$results = Property::all()->where('some search here')->get();
}
return view('admin.article.index')->with('results', $results);
}

Related

How to display multiple data from a checkbox when checked?

I have multiple checkboxes, I want to display an array of data when multiple checkboxes are clicked, but only one value is displayed, how to display an array ?What is the problem?
<div class="form-group" >
<h5>Your languages</h5>
<div class="col-md-12">
#foreach($langs as $key => $lang)
<input type="checkbox" name="foo[]" value="{{$key}}">
<label>{{ $lang }}</label>,
#endforeach
</div>
</div>
To controller
public function Method(Request $request)
{
foreach((array)$request->input('foo') as $value){
$file = 'la.txt';
file_put_contents($file,$value );
}
return redirect()->route('profile');
}
I want to display the value of all these three checkboxes, but only the data of one of them is displayed
enter image description here
Hmm - let me guess the issue, I think that you should return the values while you return back to the profile view. I think also the problem is not in the first load of the profile view, because you have to pass the langs array, but the issue happens when you click the checkboxes to store the data in the controller's method, so your code must be like so
public function storeData(Request $request)
{
foreach($request->input('foo') as $value){
$file = 'la.txt';
file_put_contents($file, $value);
}
$yourLangsArray = ["English", "Arabic"];
return redirect()->route('profile')->with('langs', $yourLangsArray);
}

laravel pagination returns different page

I am working on a laravel project, where I get data from an API then I want to display it on pages. I want the return to be spread out across 4 pages, each page with 10 results each. What I have so far, seems like it should work, but I am missing one piece, so any advice and help would be appreciated. So this is how it is suppose to work with code:
1) The users types in a book title in a search box.
<form method=POST action='/search'>
#csrf
<input type="text" name="search_term"/>
<input type="submit" value="Search"/>
</form>
2) there input is then sent to my controller, which queries the google books api.
class search extends Controller {
public function search(){
$current_page = LengthAwarePaginator::resolveCurrentPage();
echo $current_page;
$term = request('search_term');
$term = str_replace(' ', '_', $term);
$client = new \Google_Client();
$service = new \Google_Service_Books($client);
$params = array('maxResults'=>40);
$results = $service->volumes->listVolumes($term,$params);
$book_collection = collect($results);
$current_book_page = $book_collection->slice(($current_page-1)*10,10)->all();
$books_to_show = new LengthAwarePaginator($current_book_page,count($book_collection),10,$current_page);
return view('library.search')->with(compact('books_to_show'));
}
}
3) the results are then displayed on my blade
#extends('home')
#section('content')
#foreach($books_to_show as $entries)
<div class="row">
<div class="col-sm-auto">
<img class="w-50 img-thumbnail" src={{$entries['volumeInfo']['imageLinks']['smallThumbnail']}}/>
</div>
<div class="col-sm">
{{$entries['volumeInfo']['title']}}<br/>
#if($entries['volumeInfo']['authors']!=null)
by:
#foreach($entries['volumeInfo']['authors'] as $authors)
{{$authors}}
#endforeach
#endif
</div>
</div>
#endforeach
{{$books_to_show->links()}}
#endsection
This all works fine and as expected. I get 10 results on the view, and then I have a bar at the bottom which give shows me 4 different pages to choose from.
When I first type in a search term such as "William Shakespeare" My page url is:
localhost:8000/search
But, when I click on any of the pages my url becomes:
http://localhost:8000/?page=2
I understand that the ?page=* is how the pagination determines which page you are viewing, and that should be sent back to the controller. But, I am missing something on sending it back to the controller I think.
Still kind of fresh to this, so any advice is more then greatly appreciated.
LengthAwarePaginator accepts a 5th parameter in its constructor: an array of options.
the path option
$books_to_show = new LengthAwarePaginator($current_book_page, count($book_collection), 10, $current_page, [
// This will fix the path of the pagination links
'path' => LengthAwarePaginator::resolveCurrentPath()
]);
By the way, on a totally different matter, Laravel makes your life easier by slicing the collection for you, check it out:
$current_book_page = $book_collection->forPage($current_page, 10);
Hope it helps :)

How to populate view with database information after AJAX request

Hi there once again SO community. I've been developing a site and so far it's going pretty well. But today after a long day searching for a solution I can't understand nor find what the right path is...
I want to click on a button and a profile page where you can edit the fields appear. I can redirect to the page I want but I don't know how to send the user data so I can populate the fields.
Here is my button code on my view
<button class="btn btn-xs btn-warning dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false" style="border-color: black" id="dados_{{ $user->username }}"> Alterar Dados Pessoais
<i class="glyphicon glyphicon-cog"></i>
</button>
Here is the button AJAX request handler
if((this.id).indexOf("dados") != -1){
var content = this.id.replace("dados_", "");
$.get('callPermissions', {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
And here is my callPermission Controller
public function callPermissions(Request $request)
{
if($request->ajax()){
$usernames = Input::get('usernameSend');
if(isset($usernames)){
$user = User::Where('username', '=', $usernames)->first();
$returnHTML = view('userOptions.settings')->render();
return view('userOptions.settings');
}else{
Log::warning("Username não existe na base de dados.");
}
}
}
and here my Settings Controller
public function settings(Request $request)
{
return view('userOptions.settings');
}
And here is the route
Route::get('/callPermissions', 'SidebarController#callPermissions');
I know the controller is wrong and from what I've read I should verify if the AJAX is successful and if it is handle i on the AJAX request. But from what I've understand I'm not using the Controller at all (even though it goes there). How should I send the user information (in this case the username, then I can get everything from the database) and then send it to the view? I've been searching and trying out stuff that doesn't work...since the return view("your_view") on the Controller doesn't work.
Sorry if I've been confusing and if you need additional information feel free to ask!
Thanks for your help!!
Edit: If I return this on the controller
return view('userOptions.settings', compact('user'));
and do a replace with the Ajax request as show above and add this to the settings view
<p> {{ $user->name }} </p>
I get the following error Undefined variable: user (View: C:\wamp64\www\siteXL\ideiasxl\resources\views\userOptions\settings.blade.php)
Is there anyway to send the parameters with a compact alike or I need to send it through the link? Was avoiding to show the username on the url.
Edit2: For further clarification, this works as intended
<button onclick="window.location='{{url('/settings/' . $user->username)}}'" type="button" id="dadosPessoais" class="btn btn-default">Alterar Dados Pessoais
<i class="glyphicon glyphicon-wrench"></i>
</button>
but I was trying not to send id's and usernames through the URL.
If this is not achievable it's ok, but if there's a way I can't find it, that's why I'm asking
I think you have to add a parameter in the Route and receive the data in the controller function. I'd do something like this:
Route:
Route::get('/callPermissions/{user}', 'SidebarController#callPermissions');
Controller:
public function callPermissions(Request $request, $user)
{
//get data related to $user
}
Ajax call:
$.get('callPermissions/'+userIdVariable, {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
This would send the user id through the route.
To get the user id with JavaScript, you can make a hidden field in the Blade file and set the user id as the value. For example, if you using Form helper:
{{ Form::hidden('user_id', $user->id, array('id' => 'js-user-id')) }}
And then, in the JavaScript, you can get the value using something like this:
var userIdVariable = $('#js-user-id')->val();

Getting value of a submit button in Laravel 5.3

I have a form on my page
<form method="post" action="{{url('/vpage')}}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="w100">
<button name="hostel1" class="submitBTN addnowBtn" type="submit" value="The Venetian"> Add Now</button>
</div><!--w100-->
</form>
I getting the request printed in my controller like
public function vegaspage(Request $request){
dd($request);
die;
}
I have also have many fields on my page , when the request params comes to browser the submit button value is not coming in request
Any ideas ?
Inside your controller function try this:
Input::get('hostel1', 'NA');
// It will return its value ie `The Venetian` otherwise `NA`
Note: The second parameter of Input::get() is the default value.
This Follow link
only one input value get following
$name = $request->input('name');
Retrieving All Input Data
$input = $request->all();
Note: The easiest way to debug this, is via the Network tab in google chrome. You can see the header response data.
But the reason this is not working is probably because you are doing a POST Request . If you do a GET request you will get the value of the button.
An other reason could be that you are doing the submit trough javascript and doing an e.preventDefault() in that case you are not really sending the request. so PHP doesn't get the value.
Do
$request->hostel1
When you want to dd() your input params, do
dd($request->all());
I realized that anytime I try to set a name and value to a "submit" button, laravel doesn't retrieve the values in the request. So you might want to use a hidden field like this:
<input type="hidden" name="hostel1" value="hostel1">
and retrieve it on the server side like this:
$request->hostel1;
Change button code to:
<input name="hostel1" value="The Venetian" type="hidden">
<button class="submitBTN addnowBtn" type="submit"> Add Now</button>
In the controller, use this to get the value:
$request->hostel1
By using request namespace you can get value of any input parameters and also same for the submit button.
For this you have to include Request in controller like:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Store a new user.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$name = $request->input('name');
//IN your problem you can submit button value as
$submit_button = $request->input('hostel1');
}
}
For more details about the request you can follow:
https://laravel.com/docs/5.3/requests
Thanks

Can't query JSON (Laravel + VueJS)

my problem exactly smiliar with this one cant't query json data in laravel 5.2
Already try to implement the right answer from it but still, no luck.
I don't know why....
Previous, i found this Laravel 5.2 Codeception functional test issue with PUT / PATCH requests too, already try to use suggestion from him, but no luck too.
Here's my Laravel Controller
public function update(Request $request, $id)
{
$phonebook = Phonebook::findOrFail($id);
$phonebook->update($request->all());
// even i try this
// Phonebook::findOrFail($id)->update($request->all());
// return Response::json() or return response()->json();
// No luck
}
My function in vue script for update data
editContact: function(id)
{
this.edit = true
var contactid = this.newContact.ID
this.$http.patch('/api/contact/' + contactid, this.newContact, function (data) {
console.log(data)
})
},
Change my vue script to be like the right answer from question above, same result. No effect.
And my button to do edit like this
<form action="#" #submit.prevent="addNewContact">
<div class="form-group">
<label for="contactName">Name : </label>
<input type="text" v-model="newContact.CONTACTNAME" class="form-control" id="contactName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone number : </label>
<input type="text" v-model="newContact.PHONENUMBER" class="form-control" id="phoneNumber">
</div>
<div class="form-group">
<button class="btn btn-primary btn-sm" type="submit" v-if="!edit">Add new Contact</button>
<button class="btn btn-primary btn-sm" type="submit" v-if="edit" #click="editContact(newContact.ID)">Edit Contact</button>
</div>
</form>
Note :
My route file using resource or manual route always same
Route::resource('/api/contact/', 'PhonebookController');
or
patch('/api/contact/{id}', ['uses' => 'PhoneboookController#update']);
And then, there something strange.
(Maybe i am wrong) there no issue or error if we look the detail. But, if we change to response tab the result was empty
After all that process, nothing happen with the data.
CONTACTNAME should be "Mizukiaaaaaaaa" like first screenshot instead of "Mizuki"
Am I missing something??
Any advise?
Thanks
As I suggested to you, try to invert the params in your update method in your controller.
And to get a response, you have to send it back (with code 200, 400, 401, whatever you want).
public function update($id, Request $request)
{
$phonebook = Phonebook::findOrFail($id);
$phonebook->update($request->all());
// your treatment
return Response::json([
'param' => 'value'
], 200);
}
If you want to debug and see it in you response, you can make a dd('debug')in your method, you'll see it in the Ajax request response.
That should work for you !
After browsing and ask so much people about this, finally found it! There's nothing wrong with the request or response. My mistakes are mutator update that i used and my model.
Updated answer
Reason answered here and then I just changed update function on controller. Here the result
public function update(Phonebook $phonebook, Request $request, $id)
{
// You can add any fields that you won't updated, usually primary key
$input = $request->except(['ID']);
// Update query
$saveToDatabase = $phonebook->where('ID', '=', $id)->update($input);
return $saveToDatabase;
}
My previous answer updated all fields including the primary key, somehow it successful update data, but it leave error for sure (duplicate primary key). The query looks like UPDATE SET field = 'value' without condition.
This case is for model that doesn't have any relation with other models (tables), or the model act as master.

Categories