I have link like this with token:
Submit New
which produce url:
http://example.com/users/submit/20?_token=fpf0LwHyf0JGBg0fnixjRFo1B5GgUM3RDp6dVgUU
Now in my controller I've added condition which check one column in database and based on this is returning different views.
public function wrongIdSubmit($Id) {
$submits = self::$user->where('submit_id', $Id)->first();
if (!$txid) {
App::abort(404);
}
if($submits->submit_id > 3) {
return View::make('fail',[
'submits' => $submits
]);
}
else {
return View::make('submit',[
'submits' => $submits
]);
}
}
My question is how to pass this token ?_token={{ csrf_token() }} to return View::make along with $submits variable? Because like is now I've got error
production.ERROR: Illuminate\Session\TokenMismatchException
You must add the token to the form itself. You cannot pass it in the URL. Add the following to your form:
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
Laravel provide function which returns you direct input hidden field with token.
csrf_field()
It will Generates an HTML hidden input field containing the value of the CSRF token.
so you can try like this:
return View::make('fail',[
'submits' => $submits,
'token' => csrf_field()
]);
and in view just print:
{!! $token !!}
or direct also like:
{!! csrf_field() !!}
out put will be like:
<input type="hidden" name="_token" value="*****" />
Best of luck..
Related
I am creating a simple blog site with CRUD functionality in Laravel 8. I have done this before using the deprecated Laravel forms, but am now trying to do it using HTML forms.
However, I am having some problem with the update part of the website. I have a controller called BlogsController with this function to be called to update the blog in the database which should be called when the user submits the form to update.
BlogsController update function
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'category' => 'required',
'description' => 'required',
'read_time' => 'required'
]);
$blog = Blog::find($id);
$blog->title = $request->input('title');
$blog->body = $request->input('body');
$blog->category = $request->input('category');
$blog->description = $request->input('description');
$blog->read_time = $request->input('read_time');
$blog->user_id = auth()->user()->id;
$blog->save();
return redirect('/dashboard')->with('success', 'Blog Updated');
}
What action does the form need to direct to? Top of update form
<form method="POST" action="update">
Route in web.php
Route::resource('blog', 'App\Http\Controllers\BlogsController');
Implementation in Laravel forms
{!! Form::open(['action' => ['App\Http\Controllers\BlogsController#update', $blog->id], 'method' => 'POST']) !!}
You can get a list of all your application routes and names by running
$ php artisan route:list
For your blog update route you should use
<form method="POST" action="{{ route('blog.update', ['blog' => $blog]) }}">
#method('PATCH')
</form>
in your template.
Make sure you have you have your csrf token set correctly at your form by using the #csrf, see Laravel docs.
One thing that's cool with Laravel is Route model binding. So what's that mean? We can do something like this in your update method
// BlogController.php
public function update(Request $request, Blog $blog) {
$request->validate([
'title' => 'required',
'body' => 'required',
'category' => 'required',
'description' => 'required',
'read_time' => 'required'
]);
$blog->title = $request->title;
$blog->body = $request->body;
$blog->category = $request->category;
$blog->description = $request->description;
$blog->read_time = $request->read_time;
if ($blog->save()) {
return redirect('/dashboard')->with('success', 'Blog Updated');
} else {
// handle error.
}
}
In your template, you'll want to make sure you're using a PATCH method:
<form method="POST" action="{{ route('blog.update', ['blog' => $blog]) }}">
#csrf
#method('PATCH')
...
</form>
I assume you are using Resource route for your CRUD functionality. In that case, Update method in resource controller called via PUT method and not POST. So, in your form, just add this to change the Form submission method to PUT:
<input name="_method" type="hidden" value="PUT">
Also, in your form declaration, you have to add the destination route like this:
<form method="POST" action="{{ route('blog.update', $blog->id) }}">
You also have the option of using the action to get a URL to the registered route:
action('App\Http\Controllers\BlogsController#update', ['blog' => $blog])
Check all route list:
$ php artisan route:list
your route should be like:
<form method="POST" action="{{ route('blog.update', ['blog' => $blog]) }}">
{{csrf_field()}}
{{ method_field('PATCH') }}
</form>
Hi I am working on the checkout page in laravel and sent some product data from the cart to checkout and trying to print all the details from an json object but i keep getting the error as Trying to get property 'id' of non-object
The controller function is
public function bill(Request $request){
$input = $request->all();
return view('demo')->with('product' , $request->product)
->with('subtotal' , round($request->subtotal));
}
the cart form is
<form method="post" action="{{ route('pay')}}">
{{ csrf_field() }}
#foreach($cart as $product)
<input type="hidden" name="product[]" value="{{ $product }}">
#endforeach
<input type="hidden" name="subtotal" value="{{$subtotal}}">
<button type="submit" class="gray_btn">Checkout</button>
</form>
the blade page is
#foreach($product as $input)
{{ $input }}
{{ $input->id }}
#endforeach
when i only print the input i am getting the result as
{"id":"10","name":"S007-4ft","price":40,"quantity":"102","attributes":{"image":"glassfilms\/December2019\/MyelERNBbAWhGRbKWiCK.jpg","crm":"PRO209"},"conditions":[]} {"id":"7","name":"Frosted 007-4ft","price":40,"quantity":"103","attributes":{"image":"glassfilms\/December2019\/ZJgWUNaYrPnvsoRfuagv.jpg","crm":"PRO105"},"conditions":[]}
but when i try to print the id only using {{input->id }} i am getting the error.
the route is
Route::post('pay', 'RazorpayController#bill')->name('pay');
You have to pass an array in order to have access by a key, i.e. call json_decode() when returning it:
public function bill(Request $request) {
$input = $request->all();
return view('demo')
->with('product', json_decode($request->product, true)) // <-- here
->with('subtotal', round($request->subtotal));
}
Otherwise the returned value is a just simple string in JSON "shape". Error say it clear ehough: non-object.
You are using json object as php object please decode your json object first than you can use it as php object:
$obj = json_decode($input);
$obj->id // Now you can use it like this
I am trying to send a route the old way, without using Blade's {{}} tags. I am encountering a problem, because the framework throws my route as not defined. Can someone help me?
This is my form tag:
<form method="POST" action="{{ route('companyStore') }}">
My route
Route::post('companyStore', 'CompanyController#store');
My controller (the function name might help you undertand)
public function store(Request $request){
$company_name = $request->input('companyname');
$company_sector = $request->input('companyname');
$company_address = $request->input('companyaddress');
$company_phone = $request->input('companyphone');
$company_website = $request->input('companywebsite');
$company_representative = Auth::user()->id;
Company::create([
'name' => $company_name,
'sector' => $company_sector,
'address' => $company_address,
'phone' => $company_phone,
'website' => $company_website,
'representative_id' => $company_representative
]);
$company = Company::where('representative_id', $company_representative)->first();
User::where('id', $company_representative)->update(array('company_id' => $company->id));
return redirect('/admin/home');
}
The error is always:
Route [companyStore] not defined. (View:
When you use the route helper, it expects a named route. So define your route as this:
Route::post('companyStore', 'CompanyController#store')->name('companyStore');
or use:
<form method="POST" action="{{ url('/companyStore') }}">
or use:
<form method="POST" {{ action('CompanyController#store') }}>
You can define a route.
Route::post('companyStore', 'CompanyController#store')->name('companyStore');
and use this one:
<form method="POST" action="{{ route('companyStore') }}">
I don't know why #nakov has propsed {{ url('/companyStore') }}
Just Change
FORM
Route::post('companyStore', 'CompanyController#store');
TO
Route::post('companyStore', 'CompanyController#store')->name('companyStore');
Will just work
I have a form which can be saved as draft. The initial route will not have the parameter with the submitted id -- since it has not been submitted. Once it's saved, the route will contain the submitted id to retrieve the data and show it to the user.
I am currently creating multiple routes to accommodate this, which is very messy and can see how this will be an issue to maintain.
How can I account for the absence of parameters in routes, especially the form routes or controllers which throw an error with missing variables?
Routes:
Route::get('/request/{unit}/{id}',
'RequestsController#showNewRequest')->name('request.show-new-request');
Route::get('/request/{unit}/{id}/{rid}',
'RequestsController#showRequest')->name('request.show-request');
Route::post('/request/{unit}/{id}',
'RequestsController#storeNew')->name('request.store-new');
Route::post('/request/{unit}/{id}/{rid}',
'RequestsController#store')->name('request.store');
Controllers
public function showNewRequest($unit, $id) { }
public function showRequest($unit, $id, $rid) { }
Form/Blade:
#if(isset($rid))
<form class="form-horizontal" method="POST" enctype="multipart/form-data"
action="{{ route('request.store', ['unit' => $unit, 'id' => $id, 'rid' => $rid]) }}">
#else
<form class="form-horizontal" method="POST" enctype="multipart/form-data"
action="{{ route('request.store-new', ['unit' => $unit, 'id' => $id]) }}">
#endif
You can use ? in the route parameters. This will let you ignore them. Then you can change the code to something like this:
Route::get('/request/{unit}/{id}/{rid?}',
'RequestsController#showRequest')->name('request.show-request');
Controller:
public function showRequest($unit, $id, $rid = null) {
if ($rid) {
//Do something with $rid
} else {
//Do something considering that this is a draft.
}
}
This also applies to post routes.
UsersController:
public function update($id)
{
if( ! $this->user->isValid(Input::all()))
{
return Redirect::back()->withInput()->withErrors($this->user->errors);
}
$user = $this->user->find($id);
$user->save();
return Redirect::route('users.index');
}
Route:
Route::resource('users','UsersController');
Model:
protected $table = 'users'
edit.blade.php:
{{ Form::model($user, array('route'=>array('users.update','$user'=>'id'))) }}
I notice that this does NOT generate a "PUT" action. The page source:
<form method="POST" action="https://zocios.com/users/id" accept-charset="UTF-8"><input name="_token" type="hidden" value="...">
Hitting the Update User button gets me:
Exception \ MethodNotAllowedHttpException
Is the problem "$user->save();"? Something else I'm doing wrong? Thanks!
You need to specify the method:
{{ Form::model($user, array('method' => 'put', 'route'=>array('users.update','$user'=>'id'))) }}
There is no other method than GET and POST that is accepted (despite the specs), so the framework does the job of identyfying hidden input in your form _method to make it work.