When I try to login show me token error. I have checked token in view form it's right and when comment \App\Http\Middleware\VerifyCsrfToken::class,
in the Kernel.php it makes me login but after Redirect to my dashboard I'm not logged in. I am using MAMP on mac.
<div>
<h1>Login</h1>
<div>
{!! Form::open(['url'=>'user/login','class' => '']) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<ul>
<li><label>Customer Code</label>{!!Form::Text('customer_code',Input::old('customer_code'),['class'=>''])!!}</li>
<li><label>Password</label>{!!Form::Password('password','',['class'=>''])!!}</li>
<li>{!! Form::submit('Submit',array('class' => 'btn')) !!}</li>
</ul>
{!!Form::close()!!}
</div>
<div>Forget Password</div>
</div>
Meanwhile I use Sentry Package for login.
/**
* post_login
*/
public function post_login()
{
try
{
$rules = [
'customer_code' => 'required',
'password' => 'required',
] ;
$message = [
'customer_code.required' => 'erorrr1',
'password.required' =>'error2'
];
$validator = Validator::make(Input::all(), $rules,$message);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
} // if ($validator->fails())
else
{
$authUser = Sentry::authenticateAndRemember(array(
'customer_code' => Input::get('customer_code'),
'password' => Input::get('password')), false);
if($authUser)
{
//$login = Sentry::loginAndRemember($authUser);
return Redirect::to('user/panel/'.$authUser->id)->with('comment', 'Welcome');
}
else
{
return Redirect::back()->with('comment', 'Error for login');
}
}//validator
}
catch(\Exception $e)
{
return Redirect::back()->withInput(Input::except('password','file'))->withErrors(['ERROR!!!!!']);
}
}
Edited:
Since you are using Form builder remove this from your form. Laravel form builder automatically adds a hidden token field to your form when you do Form::open()
So remove this line:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Well I think all missed the CSRF Token creation while logout!
As I have solved out the problem.
Just add below code to the header.
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type=text/javascript>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
And if you use {!!Form::open()!!} it will automatically create the token. Otherwise you can use
<input type="hidden" name="_token" id="_token" value="{!! $csrf_token !!}}" />
or
{!! csrf_field() !!}
just immediate form open.
Most importantly use return Redirect::to(''); on controller function or a page reload or ajax reload that the token can be created!
Like:
public function logout() {
Session::flush();
Auth::logout();
return Redirect::to('/');
}
For ensure the token properly created or not check "view page source" on browser and it will shows like:
<meta name="csrf-token" content="TbgWTQZhTv0J4eFBQNU4rlM3jOlmBeYlTgf0waZB">
<script type=text/javascript>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<form method="POST" action="/login-process" accept-charset="UTF-8" class="form-inline"><input name="_token" type="hidden" value="TbgWTQZhTv0J4eFBQNU4rlM3jOlmBeYlTgf0waZB">
I think it might solve the problem as it worked for me!
With a fresh install of Laravel 5.1, without just a composer update from version 5.0 to 5.1 I see some differences and one in the Middleware folder.
EncryptCookies.php are a new Middleware, check if you have it.
So, I don't have tested again, I tranfert at the moment my files from my version 5.0 to a new installation of version 5.1 but im pretty sure that can be the solution for this problem, EncryptCookies.php was in the stack of the token mismatch error.
Adding {!! csrf_field() !!} solved my problem as shown below:
<form action="#" method="post" class="form-horizontal" role="form">
{!! csrf_field() !!}
</form>
If using Laravel Form helper such as below:
{!! Form::open(array('class' => 'form-horizontal', 'role' => 'form')) !!}
CSRF Code will be added automatically in your html script. Also make sure to view the source code in browser to be certain that a field such as below was indeed added.
<input type="hidden" name="_token" value="dHWBudjTyha9AMr0SuV2ABq5NNK6bTIDZDXRWCBA">
You did not post your sample code in your question.
Therefore check your code with the following options,
try with hidden input field value:
{!! csrf_token() !!} or {{ csrf_token() }}
You can also use form blade template:
{!! Form::open(array('method' => 'GET/POST','url' => 'YOUR_URL',)) !!}
This will automatically add CSRF Code in your html script
One more thing to include in <head> section is:
<meta name="csrf-token" content="{{ csrf_token() }}">
I was also having this problem when trying to upload a file. Turned out the max_post_size was being exceeded, in which case apparently all POST variables are cleared and therefore no token is being received.
Add <?php echo Form::token(); ?> in side the form.
This solution worked for me:
Add {{ csrf_field() }} anywhere in the form.
I used the following code. It is working perfectly.
<?php echo csrf_token(); ?>
I had the same problem. I am using Laravel 5.1.28, php 5.6.13
After seeing the TokenMismatchException in VerifyCsrfToken, I searched the web for answers but none solved my problem.
The page did send the token. The token values is also seen in the session file in the directory storage/framework/sessions (I disabled encryption to see it).
Exhausted, I re-install laravel and use simple form for testing - it worked without token mismatch error.
Moving my code to the newly installed laravel piece by piece, I finally found
that the problem was caused by doctrine/dbal (I still do not know why).
Removed it from composer.json and the problem disappeared.
In the composer.json, token mismatch error was seen with the following line:
"require": {
....
"doctrine/dbal": "^2.5"
...
},
Your case may be different, but you may want to see if you change anything in
composer.json that may be causing the problem.
I have same problem while using this code
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
by changing it to {!! csrf_field() !!} solve my problem
i'm on L5.1
It works for me.
<meta name="csrf-token" content="{{ csrf_token() }}" />
<script>
function getMessage(){
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type:'POST',
url:'/getmsg',
// data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
{{ Form::button('Replace Message',['onClick'=>'getMessage()']) }}
Remove App\Http\Middleware\VerifyCsrfToken::class from $middleware in Kernel.php.
Related
In a Laravel context, I've got this messages page, with all the messages belonging to a specific user. Initially all messages are not readed, so I put a button to change the boolean in DB (from 0 to 1) and finally show the message.
I'm doing this:
The view
#if ($message->readed != 0)
<p class="card-text message text-left">{{ $message->message }}</p>
#else
<form method="POST" action="/message/read">
#csrf
#method('PATCH')
<input type="hidden" name="message" value="{{ $message->id }}"/>
<button class="btn btn-info text-white" type="submit">
Leggi
</button>
</form>
#endif
The route in web.php
Route::patch('message/read', 'MusicianController#readMessage');
The function
public function readMessage(Request $request)
{
$message = Message::where('id', $request->id)->first();
$message->readed = 1;
$message->update();
return redirect()->back()->with('message', 'message updated');
}
But it's not working, as soon as I click the button to show the message (and even change the DB value) I've got this error: The PATCH method is not supported for this route. Supported methods: GET, HEAD.
Even if I had specified a patch method in routes and even in the form with #method('PATCH')
Could someone help me understand what's wrong please??
the main answer
your route is:
Route::patch('message/read', 'MusicianController#readMessage');
replace your route with following route that use for all CRUD opration:
Route::resource('message/read', 'MusicianController');
if you use ajax for submit data then replace your type and url with following:
type: "patch",
url: "{{url('message/read')}}",
if you don't use ajax than use following:
<form method="POST" action="{{url('message/read"')}}">
{{csrf_field()}}
{{ method_field('PATCH') }}
</form>
update: after version 5.6 you can use these syntax for above functions in any blade file:
<form method="POST" action="{{url('message/read"')}}">
#csrf
#method('PATCH')
</form>
I am learning Routing in Laravel 5.4 by viewing a tutorial created by DevDojo. Using the following codes in routes/web.php will emerge the TokenMismatchException error and my code does not work after I press the submit button:
Route::post('test', function () {
return 'Printed by the route responsible for test post action.';
});
Route::get('test', function () {
echo '<form method="post" action="test">';
echo '<input type="submit">';
echo '</form>';
});
I searched this same forum here and also the other places on the net like laravel.io or laracasts.com and everyone is talking about problems that occur when Laravel tries to detect the session of the request that is getting made.
I tried to fix the problem by adding the following lines to the Route::get rules but the issue does not get fixed:
echo '<input type="hidden" name="_method" value="post">';
echo '<input type="hidden" name="_token" value="csrf_field();">';
I hope you help me fix it by telling me how to properly use csrf_field(), csrf_token() or anything else needed here in the route file.
Thank you very much in advance.
csrf_token() just gives you the token.
csrf_field() builds the entire input field for you.
example:
{{ csrf_token() }} // Outputs: SomeRandomString
{{ csrf_field() }} // Outputs: <input type="hidden" name="_token" value="SomeRandomString">
in your question:
use
<input type="hidden" name="_token" value="csrf_token();">;
instead of
<input type="hidden" name="_token" value="csrf_field();">;
on the other hand
you could use
echo csrf_field();
OR
{{ csrf_field() }}
I think you're on the right track with the hidden inputs (if you've got a fresh Laravel install, otherwise make sure checking the token isn't disabled);
I recommend you use the (official) Form Builder for Laravel to handle forms (have a look here).
Afterwards, have a look here:
(1)
{{ Form::open(array('url' => 'profile')) }}
your form stuff goes here
{{ Form::close() }}
(2) Make sure to have this to output the token: echo Form::token(); (before you close the form)
(3) And finally, have a POST Route registered, that checks the token:
Route::post('profile', array('before' => 'csrf', function()
{
//
}));
Alternatively, you can specify form action directly to the function (my personal favorite):
echo Form::open(array('action' => 'Controller#method'))
I want to pass an input value from one blade file to another blade file.
I'm new to PHP Laravel, and I'm getting an error when attempting to use it.
I think my syntax is wrong here. Can somebody help?
channeling.blade:
<select class="form-control " name="fee" id ="fee"></select>
This is the link to the next page, where i want to send the value of "fee":
<input type="hidden" value="fee" name="fee" />
Click to Channel</p>
This is my web.php:
Route::post('pay', [
'as' => 'fee',
'uses' => 'channelController#displayForm'
]);
This my controller class:
public function displayForm()
{
$input = Input::get();
$fee = $input['fee'];
return view('pay', ['fee' => $fee]);
}
Error message:
Undefined variable: fee
(View: C:\xampp\htdocs\lara_test\resources\views\pay.blade.php)
pay.blade:
<h4>Your Channeling Fee Rs:"{{$fee}}"</h4>
You should use form to send post request, since a href will send get. So, remove the link and use form. If you use Laravel Collective, you can do this:
{!! Form::open(['url' => 'pay']) !!}
{!! Form::hidden('fee', 'fee') !!}
{!! Form::submit() !!}
{!! Form::close() !!}
You can value inside a controller or a view with request()->fee.
Or you can do this:
public function displayForm(Request $request)
{
return view('pay', ['fee' => $request->fee]);
}
I think you can try this, You mistaken url('pay ') with blank:
change your code:
Click to Channel</p>
to
Click to Channel</p>
Further your question require more correction so I think you need to review it first.
You can review about how to build a form with laravel 5.3. Hope this helps you.
You have to use form to post data and then you have to submit the form on click event
<form id="form" action="{{ url('pay') }}" method="POST" style="display: none;">
{{ csrf_field() }}
<input type="hidden" value="fee" name="fee" />
</form>
On the click event of <a>
<a href="{{ url('/pay') }}" onclick="event.preventDefault();
document.getElementById('form').submit();">
Logout
</a>
tl;dr: I believe #AlexeyMezenin's answer is the best help, so far.
Your current issues:
If you have decided to use Click to Channel, you should use Route::get(...). Use Route::post(...) for requests submitted by Forms.
There isn't an Input instance created. Input::get() needs a Form request to exist. Thus, the $fee an Undefined variable error message.
The value of <input type="hidden" value="fee" name="fee"/> is always going to be the string "fee". (Unless there's some magical spell casted by some JavaScript code).
The laravel docs suggest that you type-hint the Request class when accessing HTTP requests, so that the incoming request is automatically injected into your controller method. Now you can $request->fee. Awesome, right?
The way forward:
The BasicTaskList Laravel 5.2 tutorial kick-started my Laravel journey.
I changed the code like this and it worked..
echanneling.blade
<input type="hidden" value="fee" name="fee" />
<button type="submit" class="btn btn-submit">Submit</button>
channelController.php
public function about(Request $request)
{
$input = Input::get();
$fee = $input['fee'];
return view('pay')->with('fee',$fee);
}
Web.php
Route::post('/pay', 'channelController#about' );
I am setting up a simple form in laravel:
This is the route file:
Route::get('backoffice/upload', [ 'as' => 'backoffice/upload',
'uses' => 'UploadController#uploadForm']);
Route::post('backoffice/saveimage',[ 'as' => 'backoffice/saveimage',
'uses' => 'UploadController#saveImage']);
This is the controller:
class UploadController extends \BaseController
{
public function uploadForm()
{
return View::make("backoffice.upload.create");
}
public function saveImage()
{
return "Uploading...";
}
}
And this is the View file:
<h1>Upload Image</h1>
{{ Form::open(['action' => 'UploadController#saveImage']) }}
<div class='formfield'>
{{ Form::label('newfilename','New File Name (optional):') }}
{{ Form::input('text','newfilename') }}
{{ $errors->first('newfilename') }}
</div>
<div class='formfield'>
{{ Form::submit($action,['class'=>'button']) }}
{{ Form::btnLink('Cancel',URL::previous(),['class'=>'button']) }}
</div>
{{ Form::close() }}
// Generated HTML
<h1>Upload Image</h1>
<form method="POST" action="http://my.local/backoffice/saveimage" accept-charset="UTF-8"><input name="_token" type="hidden" value="x9g4SW2R7t9kia2B8HRJTm1jbLRl3BB8sPMwvgAM">
<div class='formfield'>
<label for="newfilename">New File Name (optional):</label>
<input name="newfilename" type="text" id="newfilename">
</div>
<div class='formfield'>
<input class="button" type="submit" value="Create">
</div>
</form>
So, if I go to: http://my.local/backoffice/upload I get the form with the HTML above.
However, if I type anything, then click SUBMIT, I return to the form but now have the following URL:
http://my.local/backoffice/upload?pz_session=x9g4SW2R7t9kia2B8HRJTm1jbLRl3BB8sPMwvgAM&_token=x9g4SW2R7t9kia2B8HRJTm1jbLRl3BB8sPMwvgAM&newfilename=ddd
This makes no sense to me. Up until now I have always used route::resource when dealing with forms, and had no problem. I am trying to do a simple form with GET and POST and am having no end of grief. What am I missing?
Furthermore, if I modify routes.php and change it from post to any, then open a browser window and type: http://my.local/backoffice/saveimage then I get the message "Uploading..." so that part is working ok.
Found the solution. In making the backoffice of the system, I had re-used the frontoffice template but removed all the excess. Or so I had thought. However, the front office header template had a form which I had only partially deleted.
So the problem was that there was an opening FORM tag I didn't know about. Consequently, when I clicked on submit to my form, it was actually submitting to this other form.
As the other form had no action it was default to itself.
Of course, had I just validated the HTML this would have shown up straight away. The lesson learned here is to validate my html before submitting questions!
Try this, and be sure to correctly configure your url at app/config/app.php
{{Form::open(['url'=>'backoffice/saveimage'])}}
//code
{{Form::close()}}
I know there's the usual way to render CSRF token hidden input with form_rest, but is there a way to render just CSRF input itself? I've overridden {% block field_widget %} in theme to render a piece of additional text. But as CSRF token is rendered in input field too and I got a piece of text I don't need next to a hidden field. So I'd like to render it separately with an argument that tells it not to render this text.
you can do it with {{ form_widget(formView._token) }}
If you have formView object, you can render it using Twig function:
{{ form_widget(formView._token) }}
If you haven't - you can render token without using form object directly:
<input type="hidden" name="token" value="{{ csrf_token('some-name') }}">
Works in Symfony 2.x and 3.x
To validate the token you can use the following code in your controller (Symfony 3.x):
$submittedToken = $request->request->get('token');
if ($this->isCsrfTokenValid('some-name', $submittedToken)) {
// ... do something,
}
Or you can just simply use this :
{{ form_row(form._token) }}
This will automatically generate the proper hidden HTML elements, ie the proper HTML structure and field names, according to the type of form you're using.
I needed to render the csrf input inside Twig so that I could use it for Delete operations.
Using {{ csrf_token('authenticate') }} as per #YuryPliashkou's answer gives me the incorrect token (one which is only valid for logins!)
What worked for me was this {{ csrf_token('form') }} which gives me the correct csrf token which I would then pass to my controller via ajax.
<span id="csrf_token" data-token="{{ csrf_token('form') }}"></span>
// my ajax call
$.ajax({
url: localhost/admin/product/4545, // 4545->id of the item to be deleted
type: 'POST',
data: {
"_method": "DELETE",
"form[_token]": $("#csrf_token").data("token") // passed csrf token here
},
success: function(result) {
// Do something
}
});
Verified its working on Symfony 3.x.
Reference
didn't find solution worked for me, finded and tested and worked for my Simfony3 value="{{ _token }}" in example
<form name="form" method="post" action="{{ path('blog_show', { 'id': blog.id }) }}">
<input name="_method" value="DELETE" type="hidden">
<input class="btn btn-danger" value="Delete" type="submit">
<input id="form__token" name="form[_token]" value="{{ _token }}" type="hidden">
</form>
more about scrf can be viewed here: Creating forms manually in Symfony2, but still use its CSRF and isValid() functionalily