在同一控制器层中创建编辑功能

时间:2015-10-31 12:25:07

标签: laravel laravel-5.1

所以我在我的控制器中有一个创建函数,如下所示,我的路由就是这样,我的问题是我有一种方法可以将条件设​​置为不同的创建和编辑功能,因为两者都有相似的编码。有人可以开导我吗?

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');

2 个答案:

答案 0 :(得分:1)

更新或创建

尝试使用Eloquent中的 updateOrCreate() 来创建或更新与属性匹配的记录。

阅读API文档udateOrCreate()

您的代码将如下:

Model::updateOrCreate( ['id' => $id], ['firstField' => 'value', 'secondField' => 'value'] );

注意:第一个参数是要找到的匹配项,第二个是要保存的数据。

希望这有用。

答案 1 :(得分:0)

为什么不尝试将某些代码移出控制器。如果您使用存储库,那么您将能够封装一些逻辑,以便将它用于两个函数。

此外,您无需将所有额外代码写入控制器即可处理所有此类验证 - 请参阅http://laravel.com/docs/5.0/validation#form-request-validation

起初这可能看起来有些过分,但是一旦掌握了它,你的代码将更易于管理和扩展。

(有关这些内容的更多内容,我会彻底推荐Jeffery Way的Laracasts https://laracasts.com/ - 这对我学习Laravel时帮助很多)

//  routes.php

// http://laravel.com/docs/5.0/controllers#restful-resource-controllers
Route::resource('manage_accounts', 'ManageAccountsController');


// ManageAccountsController.php

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class ManageAccountsController extends Controller
{

    public $userRepository;


    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function index() {

        $users = User::orderBy('name')->get();
        $roles = Role::all();
        return view('manage_accounts', compact('users', 'roles'));
    }

    public function store(StoreUserRequest $request)
    {
      // validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
        $this->userRepository->upsert($request)

        Session::flash('flash_message', 'User successfully added!');

        return redirect()->back();

    }

    public function update(StoreUserRequest $request, $id)
    {
        // validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
        $this->userRepository->upsert($request, $id)

        Session::flash('flash_message', 'User successfully updated!');

        return redirect()->back();

    }
}


// UserRepository.php
class UserRepository {



    public function upsert($data, $id = null)
    {

            // You will also need something like this
            if(isset($data['id']))
            {
                $user = $this->user->find($data['id']);
            }
            else {
                $user = new User;
            }


            $user->name     = $data['name'];
            $user->email    = $data['email'];
            $user->password = Hash::make($data['password']);
            $user->mobile   = $data['mobile'];
            $user->role_id  = $data['role_id'];

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

            return $user;
        }
    }

}

请使用此处的代码作为指南(我已经写了这个匆忙,它肯定会包含错误)。快速阅读存储库,我认为它应该都有意义。

这里的基本前提是将您想要重用的代码分开,而不是将它们全部压缩到同一个函数中。

希望这有帮助!