samedi 31 octobre 2015

Creating edit function in the same controller laravel

So I have a create function in my controller as shown below and my routes is as such, my question is is there a way for me to put a condition to different create and edit in the same function as both have quite similar coding. Can someone enlighten me pls?

class ManageAccountsController extends Controller
{
    public function index() {
        $users = User::orderBy('name')->get();
        $roles = Role::all();

        return view('manage_accounts', compact('users', 'roles'));
    }

    public function update()
    {
            // process the form here

    // create the validation rules ------------------------
        $rules = array(
        'name'             => 'required',                        // just a normal required validation
        'email'            => 'required|email|unique:users',     // required and must be unique in the user table
        'password'         => 'required|min:8|alpha_num',
        'password_confirm' => 'required|same:password',           // required and has to match the password field
        'mobile'           => 'required', 
        'role_id'          => 'required'
        );

    // do the validation ----------------------------------
    // validate against the inputs from our form
        $validator = Validator::make(Input::all(), $rules);

    // check if the validator failed -----------------------
        if ($validator->fails()) {

        // redirect our user back to the form with the errors from the validator

            $input = Input::except('password', 'password_confirm');

            $input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
            return redirect()
            ->back()
            ->withInput($input)
            ->withErrors($validator);

        } else {
        // validation successful ---------------------------

        // user has passed all tests!
        // let user enter the database

        // create the data for our user
            $user = new User;
            $user->name     = Input::get('name');
            $user->email    = Input::get('email');
            $user->password = Hash::make(Input::get('password'));
            $user->mobile   = Input::get('mobile');
            $user->role_id  = Input::get('role_id');

        // save our user
            $user->save();

        // redirect ----------------------------------------
        // redirect our user back to the form so they can do it all over again
            Session::flash('flash_message', 'User successfully added!');

            return redirect()->back();

        }
    }
}

routes.php

Route::get('manage_accounts', 'ManageAccountsController@index');
Route::post('manage_accounts', 'ManageAccountsController@update');



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire