I am trying to set up a contact form on a one page site using laravel, I can't seem to be able to get the form to validate the user input and show any errors that the form might have.
email.blade.php:
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
{!! Form::open(['route' => 'mail', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
{!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('first_name'))
{{ $errors->first('first_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('last_name'))
{{ $errors->first('last_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('email', null, ['class' => 'sr-only']) !!}
{!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
<i class="fa fa-envelope form-control-feedback"></i>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('textarea', null, ['class' => 'sr-only']) !!}
{!! Form::textarea('textarea', null, ['class' => 'form-control', 'rows' => 8, 'placeholder' => 'Message']) !!}
<i class="fa fa-pencil form-control-feedback"></i>
#if($errors->has('textarea'))
{{ $errors->first('textarea') }}
#endif
</div>
{!! Form::submit('Send', ['class' => 'btn btn-default']) !!}
{!! Form::close() !!}
Route: web.php:
Route::get('/ensignhospital', [
'as' => 'home',
'uses' => 'HomeController#home'
]);
Route::group(['before' => 'guest'], function () {
/*
* CSRF Protection
*
* */
Route::group(['before' => 'csrf'], function () {
Route::post('/ensignhospital', [
'as' => 'mail',
'uses' => 'HomeController#postSendMail'
]);
});
});
controller to handle for request:
class HomeController extends Controller {
public function home(){
return View('welcome');
}
public function postSendMail(ContactFormRequest $request){
if($request->fails()){
return Redirect::route('')
->withErrors()
->withInput();
}else{
return View('passed');
}
}
}
The form request validator class:
class ContactFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'message' => 'required'
];
}
}
Problem the form does not validate when I don't enter a valid input. I need the form to validate user input and remain at the form position on the web page.
please note:
I used a .htaccess file to get the site which is on my computer to display the site root as localhost/mylaravelproject rather than the usual localhost/mylaravelprojec/public that one will normally see on a fresh install of laravel.
From the documentation here: https://laravel.com/docs/5.3/validation#form-request-validation
So, how are the validation rules evaluated? All you need to do is type-hint
the request on your controller method. The incoming form request is validated
before the controller method is called, meaning you do not need to clutter
your controller with any validation logic.
Laravel will never actually remain on the form. It will instead redirect, validate and then redirect back, with the errors. You do not need the check in your code if($request->fails()).
Related
I'm new to laravel. When I try to generate a form, the problem occurred.
My route
Route::get('post/add', "Post1Controller#add");
Route::post('post/store', "Post1Controller#store");
My Post1Controller
function add()
{
return view('post/create');
}
function store(Request $request)
{
echo "Had file";}
My form
{!! Form::open(['url'=> 'post/store','method'=>'POST', 'files'=> true]) !!}
<div class="form-group">
{!! Form::file('image', ['class' => 'form-control'])!!}
</div>
<div class="form-group">
{!! Form::text('title', '', ['class' => 'form-control', 'placeholder' => 'Title in here'])!!}
</div>
<div class="form-group">
{!!form::textarea('content','',['class'=> 'form-control', 'placeholder'=> 'Text in here'])!!}
</div>
<div class="form-group">
{!! Form::submit('Add', ['name'=>'sm-add', 'class' => 'btn btn-danger'])!!}
</div>
{!! Form::close() !!}`enter code here`
My issue: The GET method is not supported for this route. Supported methods: POST. Thank you for your support.
I've got a form on a Laravel 5.2 application that uses form request validation. When I submit a request and the validator rejects it it goes back to the form and displays the validator's errors. All the user inputs are still there except for the fields that have multi-select, they are cleared. I don't want them cleared, I want them to display what the user had intended.
I'm having a hell of a time trouble shooting this because my localhost version works fine. This problem only occurs on the production version of the application.
Here is the issue request:
class IssueRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
'do' => 'required|date_format:"F d, Y"',
'issue_advocate' => 'required',
'issue_type_list' => 'required',
'file_stale_date' => 'date_format:"F d, Y"',
'level_of_service_list' => 'required_with:staff_hours',
'issue_outcome_list' => 'required_with:staff_hours',
'staff_hours' => 'numeric',
'date_closed' => 'date_format:"F d, Y"'
];
return $rules;
}
public function messages(){
return [
'issue_type_list.required' => 'Please select at least one issue type.',
'do.required' => 'The date opened field is required.',
'date_format' => 'The :attribute needs to be in the format "January 1, 2000".',
'issue_outcome_list.required_with' => 'Please select at least one outcome before entering staff hours (this marks the issue to be closed)',
'level_of_service_list.required_with' => 'Please select at least one level of service before entering staff hours (this marks the issue to be closed)',
];
}
}
Here is an excerpt of the form. The fields of concern are the issue_type_list, level_of_service_list and issue_outcome_list:
{!! Form::model($issue, array('method' => 'PATCH', 'url' => 'issues/'.$issue->id)) !!}
#include('issues.addIssueForm')
<div class="form-group">
{!! Form::label('issue_type_list[]', "Issue Type") !!}
{!! Form::select('issue_type_list[]', $issuetypes, null, ['multiple' => 'multiple', 'class' => 'form-control multi-select', 'id' => 'issue_type']) !!}
#if($errors->first('issue_type_list'))
<div class="error-item alert alert-danger">{{ $errors->first('issue_type_list') }}</div>
#endif
</div>
{!! Form::hidden('client_id',Input::get('client_id')) !!}
<div class="form-group">
{!! Form::label('level_of_service_list[]', "Level of Service") !!}
{!! Form::select('level_of_service_list[]', $level_of_service, null, ['multiple' => 'multiple', 'class' => 'form-control multi-select', 'id' => 'level_of_service']) !!}
</div>
#include('issues.referralForm')
<div class="form-group">
{!! Form::label('issue_outcome_list[]', "Outcome") !!}
{!! Form::select('issue_outcome_list[]', $outcome, null, ['multiple' => 'multiple', 'class' => 'form-control ']) !!}
</div>
<div class="form-group">
{!! Form::label('staff_hours', "Staff hours") !!}
{!! Form::input('number', 'staff_hours', null, ['class' => 'form-control', 'min'=>'0', 'step' => '0.1']) !!}
</div>
<div class="form-group">
{!! Form::submit('Edit Issue', ['class' => 'btn btn-primary form-control']) !!}
Cancel
</div>
{!! Form::close() !!}
I am in a bit of I a fix. I am trying to submit a form using Ajax. Now when I do this without creating the laravel default auth scaffold it works fine, but if add the auth scaffold it fails. I have tried all I can but can't seem to get it to submit.
Here is my code:
controller to send mail --
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class MailController extends Controller
{
//
public function index(Request $request)
{
if ($request->ajax()) {
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'mymessage' => 'required',
'g-recaptcha-response' => 'required|captcha',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
} else {
// get input fields values
$data = [
'firstName' => $request->input('first_name'),
'lastName' => $request->input('last_name'),
'email' => $request->input('email'),
'mymessage' => $request->input('mymessage'),
];
Mail::send('emails.email', $data, function ($message) {
official email
$message->to('xxxxxxxxx#gmail.com', 'My Name')->subject('Information');
});
return response()->json([
'responseText' => 'Mail was sent!'], 200);
}
} else {
return View('fail')->render();
}
}
}
The Route files:
Route::get('/', function () {
return view('welcome');
});
Route::post('/mail', [
'as' => 'mail',
'uses' => 'MailController#index'
]);
Auth::routes();
Route::get('/home', 'HomeController#index');
Ajax code:
$(document).ready(function() {
var options = {
beforeSubmit: validate,
url: '/mail',
data: $(this).serialize(),
type: 'POST',
dataType: 'json',
clearForm: true,
success: great,
error: lost
};
$('#footer-form').ajaxForm(options);
});
function validate(formData, jgForm, options) {
for (var i = 0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for all fields');
return false;
}
}
}
function great(responseText, statusText, formData) {
// prevent multiple form submission
$('#mail_btn').prop('disabled', true);
// show alert on success
$(".alert-success").prop("hidden", false);
// remove mail error information if displayed
$(".alert-info").prop("hidden", true);
// reset google recaptcha
grecaptcha.reset();
}
function lost(formData) {
// prevent multiple form submission
$('#mail_btn').prop('disabled', false);
$(".alert-info").prop("hidden", false);
}
My form code:
<div class="col-sm-6">
<div class="footer-content" id="myfooter">
{!! Form::open(['action' => 'MailController#index', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
{!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('first_name'))
{{ $errors->first('first_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('last_name'))
{{ $errors->first('last_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('email', null, ['class' => 'sr-only']) !!}
{!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
<i class="fa fa-envelope form-control-feedback"></i>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('mymessage', null, ['class' => 'sr-only']) !!}
{!! Form::textarea('mymessage', null, ['class' => 'form-control', 'rows' => 8, 'cols' => 3, 'placeholder' => 'Message']) !!}
<i class="fa fa-pencil form-control-feedback"></i>
#if($errors->has('mymessage'))
{{ $errors->first('mymessage') }}
#endif
</div>
<div class="form-group has-feedback">
{!! app('captcha')->display() !!}
</div>
{!! Form::submit('Send', ['class' => 'btn btn-default', 'id' => 'mail_btn']) !!}
{!! Form::close() !!}
<div class="alert alert-success" id="mail_alert" role="alert" hidden>
Mail Sent!
</div>
<div class="alert alert-info" id="mail_info" role="alert" hidden>
Mail Sending Error!
</div>
</div>
</div>
Error message:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
The problem was that I was using mailgun sandbox account hence I was only able to send mail when I use the laravel app with the auth scaffold include with the auth scaffold the app would allow as mailgun sandbox account don't send any reponse.
Solution was to use regular gmail send it and it responded as expected and the mail went through.
I'm trying to edit/update profile information into my Users table.
My idea is for the authenticated user to be able to edit his own profile in the Users table.
During the registration, you are only required to fill out a couple specific items (username, name, lastname, email, password) but I've also added a couple extra columns to the User table (city, country, phone, twitter, facebook).
I have a profile user page (route= '/profile') where all the information is shown. Of course all columns that aren't required during the registration are not filled in:
I also have an edit page where the columns that need info added are editable:
Here is the code for this editprofile.blade.php (where I try to send out a PATCH method):
...
{!! Form::model($user, ['route' => 'user/' . $user , 'method' => 'PATCH']) !!}
<div class="form-group form-horizontal">
<div class="form-group">
{!! Form::label('username', 'Username:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
<label class="align-left">{{ $user->username}}<label>
</div>
</div>
<div class="form-group">
{!! Form::label('email', 'E-mail:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
<label class="align-left">{{ $user->email}}<label>
</div>
</div>
<div class="form-group">
{!! Form::label('name', 'Name:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
<label class="align-left">{{ $user->name}} {{ $user->lastname}}<p>
</div>
</div>
<br />
<div class="form-group">
{!! Form::label('city', 'City:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('city', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('country', 'Country:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('country', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('phone', 'Phone:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('phone', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('twitter', 'Twitter link:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('twitter', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('facebook', 'Facebook link:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('facebook', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
{!! Form::submit('Save Profile', ['class' => 'btn btn-primary']) !!}
</div>
</div>
</div>
</div>
{!! Form::close() !!}
...
I have this is my Http/routes.php:
# Profile
Route::get('/profile', 'PagesController#profile');
Route::get('/profile/edit', 'ProfileController#edit');
Route::bind('user', function($id) {
$user = App\User::find($id)->first();
});
Route::patch('user/{user}', 'ProfileController#update');
I have an Http/Requests/UpdateUserRequest.php to validate the request:
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;
class UpdateUserRequest extends Request {
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'city' => 'max:30',
'country' => 'max:30',
'phone' => 'max:30',
'twitter' => 'max:30',
'facebook' => 'max:30'
];
}
}
And my Http/Controllers/ProfileController.php with the update fuction:
<?php namespace App\Http\Controllers;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ProfileController extends Controller {
public function edit()
{
$user = Auth::user();
return view('pages.editprofile')->withUser($user);
}
public function update(UpdateUserRequest $request, User $user)
{
$user->fill($request->all());
$user->save();
return redirect()->view('pages.editprofile')->withUser($user);
}
}
At the moment it seems I can't even open my 'editprofile.blade.php' page anymore, unless I remove the 'route' & 'methode' from my form.
I keep getting this error:
Could anyone guide me on how I should exactly trigger the PATCH methode?
change your form opening tag to
{!! Form::model($user, ['route' => 'user/' . $user->id , 'method' => 'PATCH']) !!}
you forgot '->id'
UPDATE
Change you Route
from
Route::patch('user/{user}', 'ProfileController#update');
to
Route::patch('user/{user}', 'as' => 'profile.patch', 'ProfileController#update');
and your form opening tag to
{!! Form::model($user, ['route' => array('profile.patch', $user->id), 'method' => 'PATCH']) !!}
You need to change:
{!! Form::model($user, ['route' => 'user/' . $user , 'method' => 'PATCH']) !!}
into:
{!! Form::model($user, ['route' => 'user/' . $user->id , 'method' => 'PATCH']) !!}
At the moment you create URL in your form with User object converted to Json - that's why it doesn't work.
So my create news form is very simple:
<div class="row padding-10">
{!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
<div class="form-group">
{!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="col-md-offset-5 col-md-3">
{!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control', 'onclick' => 'this.disabled=true;this.value="Sending, please wait...";this.form.submit();']) !!}
</div>
{!! Form::close() !!}
This is processed by NewsProvider:
public function store()
{
$validator = Validator::make($data = Input::all(), array(
'title' => 'required|min:8',
'body' => 'required|min:8',
));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
News::create($data);
return Redirect::to('/news');
}
But i have another field, not only title and text body in database, which is author_id and I have no idea how to add info, like the user id from currently authenticated user which wasnt supplied by form. I know how to add hidden input to form with user id, but then someone could change hidden field value. How do I do that correct way?
Maybe I have to edit my news eloquent model in some way, which is:
use Illuminate\Database\Eloquent\Model as Eloquent;
class News extends Eloquent {
// Add your validation rules here
public static $rules = [
'title' => 'required|min:8',
'body' => 'required|min:8',
];
// Don't forget to fill this array
protected $fillable = array('title', 'body');
}
You can always get the current authenticated user by Auth::user(). And you can also modify the $data array before passing it to create. Here's how you do it:
$data['author_id'] = Auth::user()->id;
News::create($data);
Also don't forget to add author_id to the fillable attributes
protected $fillable = array('title', 'body', 'author_id);