In SLIM 2 I have a small form to display a username.
My index.php
$app = New \SlimController\Slim()
//Define routes
$app->addRoutes(array('/' => array('get' => 'Home:indexGet','post' => 'Home:indexPost'),
));
In postpage.php :
<form action="" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
Here is my Controller function :
public function indexPostAction()
{
$this->render('postpage');
}
And here is my postpage.html
var_dump($app->request->post("username"));
I get this error :
exception 'ErrorException' with message 'Undefined variable: app'
I tried also tried var_dump($this->app->request->post("username"));
and I get
exception 'ErrorException' with message 'Undefined variable: this'
Slim's (v 2.x) View class doesn't store app reference. The "shortest" way to getting the app (and then the request object) from inside view (except using the static Slim:getInstance method) is
$this->data->get('flash')->getApplication()->request()->post();
but this just looks like a workaround and not an official way.
If your view requires data, it should get it through the render method:
$app->render('template', array('postdata' => $app->request()->post()));
If this is not sufficient for you, create a View-subclass that holds reference to the app and set it as the default view.
//First of all you did not set the action="" of your form in postpage.php so make it correct give the full route path like action="http://localhost/slim/index.php/showpostdata" (like if you are using wamp server and you have index.php in slim folder and showpostdata is your post route identifier) now try the following code or copy it and try it..
//In postpage.php
<form action="http://localhost/slim/index.php/showpostdata" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
//In index.php which you will save in your slim folder
<?php
require 'vendor/autoload.php';
$app = new\Slim\Slim();
$app->post('/showpostdata', function () use ($app){
$us=json_decode($app->request()->getBody(), true);
//or
$us=$_POST;
//use one out of these above three or try all which gives you output..so In $us you will get an array of post data soo..
$unm=$us["username"];
$pwd=$us["password"];
//now you have your post form data user name and password in variable $unm and $pwd now echo it...
echo $unm."<br>";
echo $pwd;
});
$app->run();
?>
Related
I am working on a E-Prescription Application using Laravel 8. I have built a checkout page which will submit a form containing only 1 value "appointment_id" so that after submitting the form by clicking finish the corresponding appointment status will be changed to "Completed" by the controller using the appointment_id. But when Im clicking on the button to trigger the methods it giving me 404 error. I have used POST method. CSRF is also used. Here is my codes ,
checkout.blade.php
<form action="/doctor/appointments/checkout" method="POST">
#csrf
<div class="form-group row">
<div class="col-md-4">
<input type="hidden" name="appointment_id" value="{{$appointment->id}}">
<input type="submit" class="btn btn-primary btn-block" value="SAVE">
</div>
</div>
</form>
some of my routes:
web.php
Route::prefix('/doctor')->name('doctor.')->namespace('Doctor')->group(function(){
//Appointment Routes
Route::get('/appointments/all',[App\Http\Controllers\Doctor\Appointment\AppointmentController::class,'AllAppointments'])->name('Appointments')->middleware('doctor');
Route::get('/appointments/view',[App\Http\Controllers\Doctor\Appointment\AppointmentController::class,'ViewAppointment'])->name('Appointment')->middleware('doctor');
Route::post('/appointments/view',[App\Http\Controllers\Doctor\Appointment\AppointmentController::class,'DeleteAppointment'])->name('DeleteAppointment')->middleware('doctor');
Route::get('/appointments/conversation',[App\Http\Controllers\Doctor\Appointment\ConversationController::class,'ViewConversation'])->name('ViewConversation')->middleware('doctor');
Route::post('/appointments/conversation',[App\Http\Controllers\Doctor\Appointment\ConversationController::class,'SendMessage'])->name('SendMessage')->middleware('doctor');
Route::get('/appointments/requests',[App\Http\Controllers\Doctor\Appointment\AppointmentController::class,'ShowRequest'])->name('Requests')->middleware('doctor');
Route::post('/appointments/requests',[App\Http\Controllers\Doctor\Appointment\AppointmentController::class,'RequestHandel'])->name('Handel')->middleware('doctor');
Route::get('/appointments/prescription',[App\Http\Controllers\Doctor\Appointment\PrescriptionController::class,'CreatePrescription'])->middleware('doctor')->name('CreatePrescription');
Route::post('/appointments/prescription',[App\Http\Controllers\Doctor\Appointment\PrescriptionController::class,'AddMedicine'])->name('AddMedicine');
Route::get('/appointments/checkout',[App\Http\Controllers\Doctor\Appointment\CheckoutController::class,'ViewCheckout'])->middleware('doctor')->name('ViewCheckout');
Route::post('/appointments/checkout',[App\Http\Controllers\Doctor\Appointment\CheckoutController::class,'EndAppointment'])->name('EndAppointment')->middleware('doctor');
}
CheckoutController.php
<?php
namespace App\Http\Controllers\Doctor\Appointment;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Appointment;
class CheckoutController extends Controller
{
public function ViewCheckout(Request $request){
$id = $request->input('id');
$medicines = DB::table('medicines')->where('appointment_id', '=',$id)->get();
$appointments = DB::table('appointments')->where('id', '=',$id)->get();
return view('doctor.appointments.checkout',['medicines'=>$medicines,'appointments'=>$appointments]);
}
public function EndAppointment(Request $request){
$id = $request->input('id');
$appointment = Appointment::findOrFail($id);
$appointment->status = 'Completed';
$appointment->save();
return redirect()->to('/doctor/appointments/all')->with('status','Appointment has been completed');
}
}
I have checked my routes by
php artisan route:list
the route is existing there.
I have also cleared routes chaches by ,
php artisan route:clear
still facing the issue.
I have also updated my composer. But thats not solved my problem. All other routes are working fine. New routes are also working except the only one :
Route::post('/appointments/checkout',[App\Http\Controllers\Doctor\Appointment\CheckoutController::class,'EndAppointment'])->name('EndAppointment')->middleware('doctor');
**
Can anybody help me fixing this ?
**
The "id" field is not id it is appointment_id.
Model::findOrFail() will throw an exception if it can't find a record which will get converted to a 404 response.
$id = $request->input('appointment_id');
$appointment = Appointment::findOrFail($id);
The error occurs because of the findOrFail: you are giving it an incorrect id, since in the form you sent the appointment_id but you only try to retrieve id from the request. Change it to:
$id = $request->input('appointment_id');
$appointment = Appointment::findOrFail($id);
you can change the code
<input type="hidden" name="appointment_id" value="{{$appointment->id}}">
to
<input type="hidden" name="id" value="{{$appointment->id}}">
Because id not found in CheckoutController
$id = $request->input('id');
Model::findOrFail If not found id it will throw 404 response
I hope it will help you
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);
}
This is error says. Im inserting an static value for now in controller to check if the controller is okay. the code is below
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
//IM JUST inserting static value for now to be able to check if inserting
DataController
public function update(Request $request, $name=null)
{
$insert = new leave([
'bio_id' => '10258',
'vacation_balance' => '25',
'sick_balance' => '25'
]);
$insert->save();
return view('pages/admin/data');
}
Route web.php
Route::post('admin/pages/admin/data', 'Admin\DTRDataController#update');
data.blade.php
<form action="{{url('admin/pages/admin/dtrdata')}}" method="post">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH">
<input type='text' class='total_undertimes' name='total_undertimes' id='total_undertimes' style='width:70px' />
<input type="submit" class="btn btn-primary" value="Edit" />
</form
What is ther error in my code
Remove
<input type="hidden" name="_method" value="PATCH">
line from your view. This makes your FORM submitted as PATCH method.
FYI:
methodNotAllowed exception throws when request using wrong method.
Ex:) When u POST to URL that is configured as GET in your Route file. In your situation you are requesting POST url using PATCH method.
You are showing the route for the URI admin/pages/admin/data but your form is going to admin/pages/admin/dtrdata. I am not sure what that 'dtrdata' URI is but it doesn't accept the PATCH method.
admin/pages/admin/data != admin/pages/admin/dtrdata
Your Form Url and route are different :
route : admin/pages/admin/data
form : admin/pages/admin/dtrdata
you need to do two correction in your code.
your Form Url and route are different :
route url : admin/pages/admin/data
form_url : admin/pages/admin/dtrdata
methodNotAllowed this error you got because you have submit form using patch method and you define post method in route. so should be used
Route::patch('admin/pages/admin/data', 'Admin\DTRDataController#update');
instead of
Route::post('admin/pages/admin/data', 'Admin\DTRDataController#update');
Route::patch('admin/pages/admin/data', 'Admin\DTRDataController#update');
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
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.