laravel 5.1 auth csrf token mismatch - php

before make any judgment I read all the related questions related to my problem but none of them fixed it.
so here's my problem when I use the authentication facility of laravel 5.1 and want to register a user the csrf token generate twice one when I requesting to show my register form and one when I post the form data to auth/register post route and this cause my to receive a csrf token mismatch exception. here's my register form markup
<form method="POST" action="/auth/register" class="ui large form">
{!! csrf_field() !!}
<div class="two fields dirright alignright">
<div class="field" >
<div class="ui right icon input">
<i class="user icon"></i>
{!! Form::text(
'first_name',
Input::old('first_name'),
array(
'class' => 'dirright alignright fontfamily',
'placeholder' => 'نام'
)
) !!}
</div>
</div>
<div class="field" >
<div class="ui right icon input">
<i class="user icon"></i>
{!! Form::text(
'last_name',
Input::old('last_name'),
array(
'class' => 'dirright alignright fontfamily',
'placeholder' => 'نام خانوادگی'
)
) !!}
</div>
</div>
</div>
<div class="field">
<div class="ui left icon input latintext">
<i class="mail icon"></i>
{!! Form::email(
'email',
Input::old('email'),
array(
'class' => 'latintext',
'placeholder' => 'E-mail address'
)
) !!}
</div>
</div>
<div class="field">
<div class="ui left icon input latintext">
<i class="lock icon"></i>
{!! Form::password(
'password',
Input::old('password'),
array(
'class' => 'latintext',
'placeholder' => 'Password'
)
) !!}
</div>
</div>
<div class="ui fluid large primary submit button">ثبت نام</div>
<div class="ui error message alignright"></div>
</form>

Just add the csrf token as follows in the form :
<input type="hidden" name="_token" value="{{csrf_token()}}"/>
it worked for me.

Assume that your web server has already write access to session directory, in my case 'app/storage/framework/sessions/'.
Execute:
$ rm -f {your_web_app}/storage/framework/sessions/*

There are several possibilities...
1) If you have any spaces at all in front of your opening <?php tag, it can cause this error (especially if you're using AJAX). So just double-check to make sure that there's nothing before <?php in your files.
2) If you're trying to submit this form data via AJAX, the docs suggest passing the CSRF token like so:
Add this meta tag to your <head>:
<meta name="csrf-token" content="{{ csrf_token() }}">
And then do this in the AJAX call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

If your using laravel 5.1 simply adding {{ csrf_field() }} would do the trick

The csrf token will be added automatically if you use the open and close tags for Form
{!! Form::open(['action' => '/auth/register', 'class' => 'ui large form']) !!}
-- Form stuff here --
{!! Form::close() !!}

i hope this will help
set meta-tag like follows
<meta name="csrf-token" content="{{ csrf_token() }}">
then request like follows
$.ajax({
data: {data1:'data1',data2:'data2'},
url: '/your/url/goes/here',
type: 'POST',
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function(response){
console.log(response);
}
})

Related

Laravel - The POST method is not supported for this route. Supported methods: GET, HEAD

I am trying to add an event on a calendar I have created, however I am getting the following error
The POST method is not supported for this route. Supported methods:
GET, HEAD
I have used the methods #csrf and {{ method_field('PUT') }} to no avail. I have also cleared route cache which did not help. Any help is much appreciated.
Routes:
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::namespace('Admin')->prefix('admin')->name('admin.')->group(function(){
Route::middleware('can:manage-users')->group(function(){
Route::resource('/users', 'UsersController', ['except' => ['show']]);
Route::resource('/courses', 'CoursesController', ['except' => ['show']]);
});
Route::middleware('can:manage-calendar')->group(function(){
Route::get('events', 'EventsController#index')->name('events.index');
Route::post('/addEvents', 'EventsController#addEvent')->name('events.add');
});
})
index.blade.php
#extends('layouts.app')
#section ('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-14">
<div class="card">
<div class="card-header">Calendar</div>
<div class="card-body">
{!! Form::open(array('route' => 'admin.events.index', 'method' => 'POST', 'files' => 'true'))!!}
{{-- {{method_field('PUT') }}
#csrf --}}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12"></div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
{!! Form::label('event_name', 'Event Name:') !!}
<div class="">
{!! Form::text('event_name', null, ['class' => 'form-control']) !!}
{!! $errors->first('event_name', '<p class="alert alert-danger">:message</p>') !!}
</div>
#Collin, I have added the image below in relation to your question
The error actually explains the problem. The method POST is not supported for the route you're using. You are trying to post to the route: admin.events.index but you actually want to post to the route events.add.
Route::post('/addEvents', 'EventsController#addEvent')->name('events.add');
{!! Form::open(array('route' => 'admin.events.add', 'method' => 'POST', 'files' => 'true'))!!}
{{-- #csrf --}}
Adding to this awnser is a possible solution for the validator exception the OP has mentioned in the comments.
The validator not found error can possibly come from the following:
When adding the the following code:
public function addEvent(Request $request)
{
$validator = Validator::make($request->all(),
[ 'event_name' => 'required',
'start_date' => 'required',
'end_date' => 'required' ]);
if ($validator->fails())
{ \Session::flash('warning', 'Please enter the valid details'); return Redirect::to('admin.events.index')->withInput()->withErrors($validator);
Try adding:
use Illuminate\Support\Facades\Validator;
Just check your form action url route. You have to pass 'route('admin.events.add)' rather than 'route('admin.events.index')' and also dont use 'PUT' it will accept 'POST' as well.

Image upload Laravel 5.3 using ajax

I have a problem here. I am developing my web application and I want it to connect to my API through ajax. I am trying to send an image to my api through ajax from my form in the client side, which is the web.
So, here's my form in the client side..
{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
{{ csrf_field() }}
<div class="row" style="margin-top:10%;">
<div class="col s12 center">
<img class="circle" id="image_url" src=""></a>
{!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
</div>
</div>
<div class="row">
<div class="input-field col s6">
{{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
{{ Form::label('herbal_name', 'Herbal Name') }}
</div>
<div class="input-field col s6">
{{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
{{ Form::label('scientific_name', 'Scientific Name') }}
</div>
</div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}
Here's my ajax, still in the client side
<script type="text/javascript">
$(".add").click(function() {
$.ajax({
url: 'http://127.0.0.1/identificare_api/public/api/plants',
data: new FormData($("#addplant")[0]),
type: "POST",
success: function( msg ) {
console.log(msg);
},
error: function(){
alert('pangit');
}
});
});
</script>
EDIT: and in my api, I just have this one
return json_encode($request->file('image_url'));
What am I missing here? Did I missed something?
UPDATE: I tried to apply the answer of #bfcior but when I try to console.log(base64img), it will return this very long string and it's longer than you expected.
click for image
I'm not entirely sure if this is the issue but aren't you supposed to be using a button instead of a submit? I'd imagine using a submit is preventing the ajax from working because the form is being submitted to the server for processing.
EDIT: What happens when you click the submit button? Telling us will help stackoverflow users diagnose the problem.
You handle the file by using:
$request->file('image_url');
https://laravel.com/docs/5.3/requests#files
Another approach is to convert img into base64 and pass it as a param. Then in your controller/route you can decode the base64 and save to a file (if is needed).
{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
<div class="row" style="margin-top:10%;">
<div class="col s12 center">
<img class="circle" id="image_url" src=""></a>
{!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
</div>
</div>
<div class="row">
<div class="input-field col s6">
{{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
{{ Form::label('herbal_name', 'Herbal Name') }}
</div>
<div class="input-field col s6">
{{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
{{ Form::label('scientific_name', 'Scientific Name') }}
</div>
</div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
var base64img = null;
$(document).ready(function() {
$('#image').change(function(){
var file = this.files[0];
var reader  = new FileReader();
reader.addEventListener("load", function () {
base64img = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
$(".add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'http://127.0.0.1:8000/identificare_api/public/api/plants',
data: $("#addplant").serialize() + '&image_url=' + base64img,
type: "POST",
success: function( msg ) {
console.log(msg);
},
error: function(){
alert('pangit');
}
});
});
});
</script>
and route
Route::post('identificare_api/public/api/plants', function (Request $request) {
return json_encode($request->all());
});

Laravel post form error

I'm having a problem for the first time when i submit a form.
When i submit the form it doesn't go to post route and i don't know why.
my post route is that:
Route::post('/app/add-new-db', function()
{
$rules = array(
'name' => 'required|min:4',
'file' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('app/add-new-db')
->withErrors($validator);
}
else
{
$name = Input::get('name');
$fname = pathinfo(Input::file('file')->getClientOriginalName(), PATHINFO_FILENAME);
$fext = Input::file('file')->getClientOriginalExtension();
echo $fname.$fext;
//Input::file('file')->move(base_path() . '/public/dbs/', $fname.$fext);
/*
DB::connection('mysql')->insert('insert into databases (name, logotipo) values (?, ?)',
[$name, $fname.$fext]);
*/
//return Redirect::to('app/settings/');
}
});
And my html:
<div class="mdl-cell mdl-cell--12-col content">
{!! Form::open(['url'=>'app/add-new-db', 'files'=>true]) !!}
<div class="mdl-grid no-verticall">
<div class="mdl-cell mdl-cell--12-col">
<h4>Adicionar Base de Dados</h4>
<div class="divider"></div>
</div>
<div class="mdl-cell mdl-cell--6-col">
<div class="form-group">
{!! Form::label('name', 'Nome: ') !!}
{!! Form::text('name', null, ['id'=> 'name', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('image', 'Logotipo:') !!}
{!! Form::file('image', ['class'=>'form-control']) !!}
#if ($errors->has('image'))
<span class="error">{{ $errors->first('image') }}</span>
#endIf
</div>
<div class="form-group">
{!! Form::submit('Adicionar', ['id'=>'add-new-db', 'class'=>'btn btn-default']) !!}
<p class="text-success"><?php echo Session::get('success'); ?></p>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
I'm loading this from from a jquery get:
function addDB()
{
$( "#settings-new-db" ).click(function(e)
{
$.get('/app/add-new-db', function(response)
{
$('.content-settings').html("");
$('.content-settings').html(response);
componentHandler.upgradeDom();
});
e.preventDefault();
});
}
When i try to submit the form i'm getting 302 found in network console from chrome.
I'm doing forms at this way and it is happens for the first time. Anyone can help me?
Thanks
Fix the name attribute for your image upload field. You refer it as image in the form but you are trying to fetch it as file in your controller.

Laravel form submit showing MethodNotAllowedHttpException in RouteCollection.php line 218:

This is my route
Route::resource('admin/reports', 'ReportController');
This is controller function
public function store(Request $request)
{
return "Thank you";
}
This is my html code
{!! Form::open([ 'url' => 'admin/reports/store', 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'reportfile' ]) !!}
{!! csrf_field() !!}
<div class="col-md-12">
<h3 style="text-align : center">Select File</h3>
</div>
<div class="col-md-12" style="text-align: center; padding: 10px">
<button type="submit" class="btn btn-primary">Upload Report</button>
</div>
{!! Form::close() !!}
When I submit the form, it show me MethodNotAllowedHttpException in RouteCollection.php line 218:
Any help is much appreciated. Thanks
Your form action should just be admin/reports.
Currently it will assume you are trying to post to the route admin/reports/{id}. That endpoint is used with GET, PUT and DELETE.
Check the docs including a table giving you routes https://laravel.com/docs/5.1/controllers#restful-resource-controllers if I were you I'd use the route helper to generate your urls for you

How do I provide inline error feedback with Laravel 4 and Twitter Bootstrap 3?

I'm building a form using Laravel 4 and Twitter Bootstrap 3 and I want to error messages to appear next to the field. This is the solution that I came up with but it ends up being 15 lines of code per field.
#section('content')
<div class="container">
<h1>Edit User</h1>
{{ Form::model($user, array('route' => array('users.update', $user->id), 'method' => 'PUT', 'class' => 'form-horizontal')) }}
{{-- First Name field --}}
{{-- Start a form group. If there any errors, then highlight the field red. --}}
<div class="form-group {{ $errors->has('first_name') ? 'has-error' : '' }}">
{{-- Display the label and the field. --}}
{{ Form::label('first_name', 'First Name', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-5">
{{ Form::text('first_name', NULL, array('class' => 'form-control', 'placeholder' => 'First Name')) }}
</div>
{{-- If there is an error, display any messages to the right of the field with a warning icon. --}}
#if($errors->has('first_name'))
<div class="col-sm-5">
#foreach ($errors->get('first_name') as $message)
<span class="help-block">
<span class="glyphicon glyphicon-warning-sign"></span>
{{ $message }}
</span>
#endforeach
</div>
#endif
</div>
{{-- Form buttons --}}
<div class="form-group">
{{-- Line up the buttons with the right edge of the fields. --}}
<div class="col-sm-offset-2 col-sm-5">
<div class="pull-right">
{{-- Cancel button takes user back to profile page. --}}
{{ HTML::linkRoute('users.show', 'Cancel', array($user->id), array('class' => 'btn btn-default')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
</div>
</div>
</div>
{{ Form::close() }}
</div>
#stop
This is how it appears:
I'm just starting out with both Laravel and Bootstap. I used Jeffery Way's tutorial on NetTuts to make the form and Coder's Guide's tutorial to apply the formatting.
Should I be using client-side validation or would this be considered an acceptable implementation of Laravel 4 and Bootstrap?
Thanks!
This may not be the coolest way to do this but I think it's pretty slick.
Laravel has a feature called Form::macro that allows you to sort of make reusable code snippets. You can define a macro all kinds of places but I just slapped mine in my routes.php file to get this going real quick.
Form::macro('errorMsg', function($field, $errors){
if($errors->has($field)){
$msg = $errors->first($field);
return "<span class=\"error\">$msg</span>";
}
return '';
});
Then to use in a form, pass the macro your error messages:
{{ Form::label('first_name', 'First Name:') }}
{{ Form::text('first_name') }}
{{ Form::errorMsg('first_name', $errors) }}
{{-- where $errors is your Illuminate\Support\MessageBag object --}}
To get even more tech, you can use Form::objects in a Form::macro like so:
Form::macro('textError', function($field, $label, $errors){
$label_html = Form::label($field, $label);
$text_html = Form::text($field);
$msg_html = '';
if($errors->has($field)){
$msg_html.= '<span class="error">';
$msg_html.= $errors->first($field);
$msg_html.= '</span>';
}
return $label_html.$text_html.$msg_html;
});
Then you're at 1 line per input:
{{ Form::textError('first_name', 'First Name:', $errors) }}
You'd need to make other macros for password, textarea, etc. (which is why I just use the first example; it's only a couple more lines of code per input and serves all input types.)
If you wanted to style your input on error, eg. a red border, you'd probably want the second example then wrap it in your div.form-group or whatevers. Anyway, options out the wazoo.
UPDATE: An even slicker way to get errors in macros is to access them via Session::get('errors'); like so:
Form::macro('errorMsg', function($field){//yay! we don't have to pass $errors anymore
$errors = Session::get('errors');
if($errors && $errors->has($field)){//make sure $errors is not null
$msg = $errors->first($field);
return "<span class=\"error\">$msg</span>";
}
return '';
});

Categories