Laravel 4 - Process via controller after validating in routes file - laravel

Im having a little trouble getting used to the whole routes and controllers in Laravel 4.
From my understanding, routes should only be used to decide where to point the URL so it shouldnt be used to process uploads or anything like that.
So basically what i have is my routes file which validates the user fields, then how do i point it to a controller to process teh uploads and everything like that.
I currently have the following code, but when the validation passes and it should go to the controller file, it just displays a blank screen.
Any help would be greatly appreciated.
Route::post('create-profile', function()
{
// Validation rules
$rules = array(
'username' => 'required|unique:users,username|min:4|alpha_dash',
'emailaddress' => 'required|email|unique:users,email',
'country' => 'required',
'state' => 'required',
'genre' => 'required',
'filename' => 'image',
'password' => 'required|min:5|confirmed',
'password_confirmation' => 'required'
);
// Validate the inputs
$v = Validator::make( Input::all(), $rules );
// Was the validation successful?
if ( $v->fails() )
{
// Something went wrong
return Redirect::to('create-profile')->withErrors( $v )->withInput(Input::except('password', 'password_confirmation'));
} else {
// Here is where it seems to all go wrong.
Route::get('create-profile', 'CreateProfileController#processSignup');
}
});

Assuming that your url will be:
http://site.com/create-profile
What I'm showing is not ideal, but I think that your code should look more like the one below:
routes.php
<?php
Route::post('create-profile', 'CreateProfileController#processSignup');
Route::get('create-profile', 'CreateProfileController#signup');
CreateProfileController.php
<?php
Class CreateProfileController extends Controller {
public function processSignup()
{
// Validation rules
$rules = array(
'username' => 'required|unique:users,username|min:4|alpha_dash',
'emailaddress' => 'required|email|unique:users,email',
'country' => 'required',
'state' => 'required',
'genre' => 'required',
'filename' => 'image',
'password' => 'required|min:5|confirmed',
'password_confirmation' => 'required'
);
// Validate the inputs
$v = Validator::make( Input::all(), $rules );
// Was the validation successful?
if ( $v->fails() )
{
// Something went wrong
return Redirect::to('create-profile')->withErrors( $v )->withInput(Input::except('password', 'password_confirmation'));
}
return View::make('success');
}
public function signup()
{
return View::make('signup');
}
}
It's better to have all your routes pointing to controllers actions and let them do the job and, also, it's a little more readable and easy to understand.
Using resource controllers, you can reduce your routes names:
Route::resource('profile', 'ProfileController', array('only' => array('create', 'store')));
Wich will give you those routes:
http://site.com/profile/create
http://site.com/profile/store

Related

I have a problem with laravel validation logic when im trying to update my data

Hello guys im beginner in laravel and i need some help.I have a problem with my validation.When i store data in my bootstrap modal everyting is fine but when i press edit button and want to update, the same validation logic applies like when i create.When I want to update, if i don't change the name it won't update because it must be unique.
This is my Department Controller
public function store(Request $request)
{
$this->validate($request,[
'name'=>"required|unique:departments|max:255"
]);
$departmentId = $request->department_id;
Department::updateOrCreate(
['id' => $departmentId],
['name' => $request->name, 'description' => $request->description]
);
return response()->json(['success'=>'Department saved successfully.']);
}
As previously mentioned it would be ideal to have this be 2 different methods, but if you want this in one method you can achieve that. You will need to check if that department id is being passed or not to see if this is an update or create, then adjust the rule based on this. You can try something like this:
public function store(Request $request)
{
$unique = \Illuminate\Validation\Rule::unique('deparments');
if ($request->has('deparment_id')) {
$unique->ignore($request->department_id);
}
$this->validate($request, [
'name' => [
'required', $unique, 'max:255',
],
]);
$departmentId = $request->department_id;
Department::updateOrCreate(
['id' => $departmentId],
['name' => $request->name, 'description' => $request->description]
);
return response()->json(['success'=>'Department saved successfully.']);
}
This assumes the deparment_id is only passed for updates.
you can do this :-
$this->validate($request,[
'name' => 'required|unique:departments|max:255,'. $request->department_id,
]);

Should I use prepareForValidation of FormRequest to passing params for validation request?

I want to pass user_id and post_id to formRequest. So I use prepareForValidation to merge to the request like that done in the code below. Is that way ok or I should be passing params on Controller?
public function rules()
{
return [
'content' => 'required',
'user_id' => 'required|exists:\App\Models\User,id',
'post_id' => 'required|exists:\App\Models\Post,id'
];
}
public function prepareForValidation()
{
$this->merge([
'user_id' => Auth::user()->id,
'post_id' => $this->post->id
]);
}
I think it's ok but remove unneeded checks like:
exists:\App\Models\User,id,
and
exists:\App\Models\Post,id
I think all you need to make it
public function rules()
{
return [
'content' => 'required',
'user_id' => 'required',
'post_id' => 'required'
];
}
To avoid hitting the database for no reason the user is the current user so no need to check and the post in the current request so it can not be deleted.
Note:
(The business may be different for the post based on your project. I mean may admin can delete it so the normal user can not do the action then keep this rule for post_id (exists:\App\Models\Post,id) )
If Route look like
Route::patch('posts/{post}', 'update');
public function rules()
{
return [
'content' => 'required'
];
}
public function prepareForValidation()
{
$this->merge([
'user_id' => auth()->id(),
'post_id' => $this->route('post')->id
]);
}
M too late but here is a smart way.
Before validation code in controller just use below 2 methods.
1: $request->request->remove('field_name');
2: $request->request->add(['field_name' => 'modified_value']);
Good to go.

Validation : Laravel

In ContactsRequest.php
public function rules()
{
return [
'org_id' => 'required',
'name' => 'required',
'office' => 'required',
'mobile' => 'required_without:home',
'home' => 'required_without:mobile'
];
}
So basically what i want is , i have a form which will be taking the attributes specified in the code. But i want to modify code so that entering either one of 'home' or 'mobile' will allow me to create the new user.
What should be done.Any help would be appreciated

$this->validation custom redirect

I have a form with four tab so after validation it redirect me on first tab always, but i want it redirect me on that which have error message
Here is my code
$this->validate($request,
[
'name' => 'required|min:3|alpha_spaces',
'date_of_birth' => 'required|date|date_format:"Y-m-d"',
'place_of_birth' => 'required',
'nationality' => 'required',
'address' => 'required',
'port_name' => 'required',
'contact_number' => 'required|digits_between:8,15|numeric',
'religion' => 'required',
'education_level' => 'required',
'marital_status' => 'required',
'interview_method' => 'required',
'can_be_interviewed_via' => 'required',
'date_to' => 'required',
'date_from' => 'required',
'country' => 'required',
]);
and for redirect i m using on every tab i m using submit button with hidden filed selecttab
if ($data['selecttab'] == 'tab0') {
return redirect("fdws/".$id."/edit?tab=tab0");
}elseif($data['selecttab'] == 'tab1'){
return redirect("fdws/".$id."/edit?tab=tab1");
}elseif($data['selecttab'] == 'tab2'){
return redirect("fdws/".$id."/edit?tab=tab2");
}else{
return redirect("fdws/".$id."/edit?tab=tab3");
}
When no validation apply it work fine
Before you call your `$this->validate($request, ...` set `$redirect` to the result of your `if ($data['selecttab'] == 'tab0') { ...` statement. Therefore, I suggest first do your if statement and have a variable named `$redirect` that catches the result of the if statment
if ($data['selecttab'] == 'tab0') {
$redirect = "fdws/".$id."/edit?tab=tab0";
}elseif($data['selecttab'] == 'tab1'){
$redirect = "fdws/".$id."/edit?tab=tab1";
}elseif($data['selecttab'] == 'tab2'){
$redirect = "fdws/".$id."/edit?tab=tab2";
}else{
$redirect = "fdws/".$id."/edit?tab=tab3";
}
And then `$this->validate(...)`.
Scratch that! I made a big mistake. According to official Laravel 5.0 documentation, and also looking at the Illuminate\Foundation\ValidatesRequests trait, when using Controller Validation, it is NOT possible to just chose the redirect route without modification to the traits or other codes. I think using Form Request will give you the power you want with a lot less hassle.
Solution found,
I done like that and its working fine :)
$validator = Validator::make($request->all(), [
'can_be_interviewed_via' => 'required',
]);
if ($validator->fails()) {
return redirect("fdws/".$id."/edit?tab=tab3")
->withErrors($validator)
->withInput();
}
In Laravel 5 use Middleware as helpers for controllers and routes. This will help you a lot.

Validating boolean with Laravel Validation

I have a login form with
username, password and remember me
remember me is a checkbox (true or false).
How do I create the validation rule in Laravel?
http://laravel.com/docs/validation#basic-usage
The only relevant one it seems was in and you specify the values but the values in this case are booleans and using this method they would be specified as string?
in:true,false
There's a validator for boolean. Assuming you're using one of the packages that simplifies model validation, e.g. EsensiModel, it's as simple as adding the following to your Model:
protected $rules = [
'email' => 'required|email',
'password' => 'required',
'remember_me' => 'boolean',
];
You may try something like this:
$rules = array('email' => 'required|email', 'password' => 'required');
$inputs = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
$validator = Validator::make($inputs, $rules);
if($validator->fails()) {
return Redirect::back()->withInput()->withErrorts($validator);
}
else {
$remember = Input::get('remember', FALSE);
if(Auth::attempt($inputs, !!$remember)) {
// Log in successful
return Redirect::to('/'); // redirect to home or wherever you want
}
}
I've used email which is recommended but if you use username other than email then just change the email to username and in the rule for username use something like this:
'username' => 'required|alpha|min:6' // Accepts only a-z and minimum 6 letters

Resources