AdamJones AdamJones - 1 month ago 11
PHP Question

Laravel form validation doesn't seem to work

I'm making my first form in Laravel and the generation of the form is all working. It's just that the store function seems to blindly return the user to my contact page irrelevant of the result of the form validation.

So if the email address posted isn't an email but a random string I still get returned to the /contact page with the thank you message being sent to the view.

My controller looks like this:

namespace App\Http\Controllers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;

use App\Http\Requests\ContactFormRequest;

class ContactController extends Controller {

public function create(){
return view('contact');
}

public function store(ContactFormRequest $request) {

return \Redirect::route('contact')
->with('message', 'Thanks for contacting us!');

}
}


And the form handler like this:

namespace App\Http\Requests;
use Illuminate\Http\Request;

class ContactFormRequest extends Request {
public function authorize() {
return true; // don't need to be registered to run form so true
}
public function rules() {
return [
'email' => 'required|email',
];
}
}


This is controlled by the following routes

if (config('app.tan_site_page_contact')===true){
Route::get('/contact', ['as' => 'contact', 'uses' => 'ContactController@create']);
Route::post('/contact', ['as' => 'contact_store', 'uses' => 'ContactController@store']);
});


And the form like this:

<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@if(Session::has('message'))
<div class="alert alert-info">
{{Session::get('message')}}
</div>
@endif


{!! Form::open(array('route' => 'contact_store', 'id' => 'contactCallMeForm')) !!}
{!! Form::label('Your E-mail Address') !!}
{!! Form::text('email', null, array('required', 'class'=>'form-control', 'placeholder'=>'Your e-mail address')) !!}
{!! Form::submit('Contact Us!', array('class'=>'btn btn-primary')) !!}
{!! Form::close() !!}


The form html seems fine,with a token and valid url

<form method="POST" action="http://localhost/contact" accept-charset="UTF-8" id="contactCallMeForm" novalidate="">
<input name="_token" type="hidden" value="VNHchLZhfsXadVZXCZWHGdAuJ4zgmO6cDJIGhR59">
<label for="Your E-mail Address">Your E-mail Address</label>
<input required="required" class="form-control" placeholder="Your e-mail address" name="email" type="text">
<input class="btn btn-primary" type="submit" value="Contact Us!">
</form>

Answer

The problem here is your ContactFormRequest class.

You extends it from invalid Request class. You extend it from \Illuminate\Http\Request class but you should extend it from \Illuminate\Foundation\Http\FormRequest (or \App\Http\Requests\Request class)