dongyingdao8867
2015-08-03 20:23
浏览 658
已采纳

Laravel 5中一条路由的GET和POST方法的共享数据

My projects POST routes usually makes the same view on its GET version routes.

So POST route (controller) must pass the same data to the same view.

Is there any way to tell Laravel in POST route add some data to the same data which GET route passes?

I think it's me that is on the wrong way and there must be a better way.

For example see the following common data that both GET and POST methods pass to the view. In this example there is no much data but usually there are.

/**
 * @Route('/cp/users')
 *
 * @return \Response
 */
public function getUsers() {
    $users = User::all();
    $roles = ["admin", "personnel"];
    return view('cp.users', ['users' => $users, 'roles' => $roles]);
}

/**
 * @Route('/cp/users') POST
 * @param \Illuminate\Http\Request $request
 *
 * @return \Illuminate\Support\MessageBag
 */
public function postUsers(Request $request) {
    $users = User::all();
    $roles = ["admin", "personnel"];
    $rules = [
        'name'     => 'required',
        'surname'  => 'required',
        'email'    => 'required|email|unique:users',
        'password' => 'required|min:6',
        'role'     => 'required|in:admin,personnel'
    ];
    $validator = Validator::make((array)$request, $rules);
    if ($validator->fails()) {
        return view('cp.users', ['errors' => $validator->errors(), 'users' => $users, 'roles' => $roles]);
    }
    return view('cp.users', ['users' => $users, 'roles' => $roles]);
}

I do it this way:

/**
 * @Route('/cp/users') POST
 * @param \Illuminate\Http\Request $request
 *
 * @return \Illuminate\Support\MessageBag
 */
public function postUsers(Request $request) {
    $rules = [
        'name'     => 'required',
        'surname'  => 'required',
        'email'    => 'required|email|unique:users',
        'password' => 'required|min:6',
        'role'     => 'required|in:admin,personnel'
    ];
    $validator = Validator::make((array)$request, $rules);
    if ($validator->fails()) {
        View::share('errors', $validator->errors());
    }
    return $this->getUsers();
}

1条回答 默认 最新