Skip to content

Instantly share code, notes, and snippets.

@niraj-shah
Created March 8, 2016 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niraj-shah/de96f9ee394ea92b8f0d to your computer and use it in GitHub Desktop.
Save niraj-shah/de96f9ee394ea92b8f0d to your computer and use it in GitHub Desktop.
Putting Laravel Validation into a Controller
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Input;
use Auth;
use View;
use Session;
use Validator;
use Redirect;
use Hash;
use App\User;
class MyController extends Controller {
public function index()
{
return View::make( 'index' );
}
public function create()
{
return View::make( 'create' );
}
public function store()
{
// ...
}
public function edit( $id = null )
{
return View::make( 'edit', [ 'user' => Auth::user() ] );
}
public function update( $id = null )
{
// define validation rules, 'password' will be our custom rule
$rules = [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255',
'current_password' => 'required|password',
'password' => 'required|confirmed|min:6',
];
// custom rule for 'password'
Validator::extend('password', function( $attribute, $value, $parameters ) {
// compare the entered password with what the database has, e.g. validates the current password
return Hash::check( $value, Auth::user()->password );
});
// custom message if validation for password fails
$messages = [ 'password' => 'Your current password does not match our records.' ];
// validate input with rules, adding in custom messages
$validation = Validator::make( Input::all(), $rules, $messages );
// if validation fails, redirect back to previous page
if ( $validation->fails() ) {
return Redirect::back()->withInput()->withErrors( $validation->messages() );
}
// if we got to here, all is well
// save changes to database here, e.g.
User::find( Auth::user()->id )->update( Input::except(['current_password', 'password_confirmation']) );
// redirect with success message
return Redirect::back()->with( ['message' => 'Your account details were updated successfully.'] );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment