Pass old input after Form Request validation in laravel 5 - laravel

if the validation fails it's not clear to me how i could pass the old input to fill again the form.
I mean, I know how to pass the data when using the Validator class and redirecting after fail with the method withInput(), but I'm trying to learn how to use Form Requests provided in laravel 5. Thanks

$username = Request::old('username');
or in view:
{{ old('username') }}
Read more: http://laravel.com/docs/5.0/requests#old-input

You can redirect with old data like below with validation error
return redirect()->back()->withErrors($validator)->withInput();

<input type="text" name="username" value="{{ old('username') }}">
you must also define withInput() for the http route when redirecting to a page for example
return back()->withInput();

Related

update method issue(The POST method is not supported) in laravel

I want to create update method and this is the code:
Route::get("/allProducts/edit/{id}","AllproductController#edit")->name('Allproduct.edit');
Route::post("/allProducts/update/{id}","AllproductController#update")->name('Allproduct.update');
<form class="form-horizontal tasi-form" method="post" enctype="multipart/form-data"
action="{{ route('allProducts.update' , [ 'id'=>$allproduct->id ]) }}">
{{ csrf_field()}}
public function update(Request $request, $id)
{
$data = Allproduct::find($id);
$data->name = $request->name;
$data->save();
return redirect(route('allProducts.index'));
}
when I click on submit button it shows me :
"The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE" error!
what is the problem?
Your route names do not match.
in routes:
name('Allproduct.update');
in the form:
allProducts.update
Also, you can always check the name of the routes thanks to the console command:
php artisan route:list
if you want use method PUT:
you can change method in routes:
Route::post to Route::put
and add next in form:
<input type="hidden" name="_method" value="PUT">
OR
#method('PUT')
this is if your laravel version is 6 and if your version another, check correct way to use PUT method in forms at laravel.com/docs/6.x/routing with your version.
As said here
HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:
So your form should look like this:
<form class="form-horizontal tasi-form" method="post" enctype="multipart/form-data"
action="{{ route('Allproduct.update' , [ 'id'=>$allproduct->id ]) }}">
#csrf
#method('PUT')
You had a typo in your route name and it was missing the method field.
Change your route to this:
Route::put("/allProducts/update/{id}","AllproductController#update")->name('Allproduct.update');
This will work, but
i strongly recommend you read this laravel naming conventions, and then change the name of your controller and model to AppProductController, AppProduct.

Laravel old() directive with conditional default value

I'm using Laravel 5.8, and have several input fields which of course has an old() directive on every value="" tag.
This is my example right now:
<input class="form-control input-md" name="contact_name" type="text" value="#if($edit){{ $ad->contact_name }}#else{{ old('contact_name')}}#endif">
I now that if I use this: {{ old('contact_name', "John")}}
The default value will be "John"
But I want to do a check if there is a user logged in and prefill that input with the User contact name.
My idea is something like this:
value="#if($edit){{ $ad->contact_name }}#else{{ old('contact_name', Auth::user()->name)}}#endif
And it works! But of course, it throws: Trying to get property 'name' when I get an incognito window.
So, how do I evaluate logged in users and prefill this?
You can use the optional helper:
{{ old('contact_name', optional(Auth::user())->name) }}

my delete query is not working in laravel

I am trying delete database data in Laravel. but this is not working my way.
my view page is
{{url('/deleteReview/'.$Review->id)}}
my web is
Route::post('/deleteReview/{id}','adminController#deleteReview');
my controller delete function is
public function deleteReview($id){
$deleteReview = Review::find($id);
$deleteReview->delete();
return redirect('/manageReview');
}
Are you trying to delete the review by opening the page /deleteReview/<id> in your browser? If so, this would be a GET request, so change the route to a get route:
Route::get('/deleteReview/{id}','adminController#deleteReview');
Please note as per the comments that a GET request should never change data server side. If data is changed using a GET request then there is a risk that spiders or browser prefetch will delete the data.
The correct way to do this in Laravel is using a POST request and use Form Method Spoofing to simulate a DELETE request. Your route entry would then look like this:
Route::delete('/deleteReview/{id}','adminController#deleteReview');
And your form would look like this:
<form action="/deleteReview/{{ $Review->id }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
At Controller you should first set Validation for ID that you have to Delete. Create your own customize request handler such as DeleteRequest.
Once you get ID at Controller then used this code
public function deleteReview(DeleteRequest $id){
DB::table('reviews')->where('id', $id)->delete();
return redirect('/manageReview');
}
I hope it will work.

Laravel 4 - Showing edit form with OLD data input as well as DB information

Im making a edit form for my app and i was wondering if someone could tell me how to get the data from the database into my text field.
I can locate the record i need to edit based on the users click, and i can display the information if i do the following:
value="{{ $letter->subject }}"
BUT, the problem im having is that when i run it through the validation and there is an error, it comes back with the database information instead of the OLD data.
So my questions is. Is there a way to serve up the database information first and then when it goes through the validatior, validate the information the user has edited?
Currently to validate the text field and bring the data back incase of error, im using
Input::old('subject')
Is there a parameter for that old bit that allows me to put in the DB data?
Cheers,
Hey you could validate and return ->withInput() and then in your actual form, check if there is Input::old() and display it, otherwise display from the db.
example:
<input type="text" name="subject"
value="{{ (Input::old('subject')) ? Input::old('subject') : $letter->subject }}">
Or you could go the other way and define the variable and do a regular if statement, instead of the ternary one! Up to you to decide what you want to use!
All you need is form model binding http://laravel.com/docs/html#form-model-binding:
{{ Form::model($letter, ['route' => ['letters.update', $letter->id], 'method' => 'put']) }}
// your fields like:
{{ Form::text('someName', null, ['class' => 'someHTMLclass' ...]) }}
// no default values like Input::old or $letter->something!
{{ Form::close() }}
This way you form will be populated by the $letter data (passed from the controller for example).
Now, if you have on your countroller:
// in case of invalid data
return Redirect::back()->withInput();
then on the redirect your form will be repopulated with input values first, not the original model data.
Make it more simple and clean
<input type="text" name="subject" value="{{ (Input::old('subject')) ?: $letter->subject }}">
I'm not sure for Laravel 4 but in Laravel 5, function old takes second param, default value if no old data in session.
Please check this answer Best practice to show old value

How does Laravel handle PUT requests from browsers?

I know browsers only support POST and GET requests, and Laravel supports PUT requests using the following code:
<?= Form::open('/path/', 'PUT'); ?>
... form stuff ...
<?= Form::close(); ?>
This produces the following HTML
<form method="POST" action="http://example.com/home/" accept-charset="UTF-8">
<input type="hidden" name="_method" value="PUT" />
... form stuff ...
</form>
How does the framework handle this? Does it capture the POST request before deciding which route to send the request off to? Does it use ajax to send an actual PUT to the framework?
It inserts a hidden field, and that field mentions it is a PUT or DELETE request
See here:
echo Form::open('user/profile', 'PUT');
results in:
<input type="hidden" name="_method" value="PUT">
Then it looks for _method when routing in the request.php core file (look for 'spoofing' in the code) - and if it detects it - will use that value to route to the correct restful controller.
It is still using "POST" to achieve this. There is no ajax used.
Laravel uses the symfony Http Foundation which checks for this _method variable and changes the request to either PUT or DELETE based on its contents. Yes, this happens before routing takes place.
You can also use an array within your form open like so:
{{ Form::open( array('route' => array('equipment.update', $item->id ),
'role' => 'form',
'method' => 'put')) }}
Simply change the method to what you want.
While a late answer, I feel it is important to add this for anyone else who finds this and can't get their API to work.
When using Laravel's resource routes like this:
Route::resource('myRoute','MyController');
It will expect a PUT in order to call the update() method. For this to work normally (outside of a form submission), you need to make sure you pass the ContentType as x-www-form-urlencoded. This is default for forms, but making requests with cURL or using a tool like Postman will not work unless you set this.
PUT usually refers to update request.
When you open a form inside laravel blade template using,
{{ Form::open('/path/', 'PUT') }}
It would create a hidden field inside the form as follows,
<input type="hidden" name="_method" value="PUT" />
In order for you to process the PUT request inside your controller, you would need to create a method with a put prefix,
for example, putMethodName()
so if you specify,
{{ Form::open('controller/methodName/', 'PUT') }}
inside Form:open. Then you would need to create a controller method as follows,
class Controller extends BaseController {
public function putMethodName()
{
// put - usual update code logic goes here
}
}

Resources