@pmall
I have a URL that looks like this: foo.bar/cp/board/{board}
{board} is a slug that accesses a unique board. In the controller, I can very easily access the board like this:
public function getIndex(Board $board)
{
dd($board);
}
This will have the model data that is associated with the board that is requested in the URL.
Now, I am building a config panel. These options are not directly related to the model, there is a many-to-many relationship between options and boards. The config form is very complicated, so I am building a FormRequest.
My problem is that the FormRequest has no idea what the Board is, unlike the controller. It also has no idea what the user is. It also has no idea what the controller is. It's like the Request object is completely and totally separated from the controller and there is nothing passed to it by default.
This is great for a complicated form with a fixed set of rules and expected input, but my form isn't that. A form will have different rules depending on what board it is associated to.and who is accessing it.
Because I do not have access to the user, the board, or the controller within my FormRequest, I cannot construct a fully dynamic set of rules as I require.
The only way I've found to get around this is to do this:
trait RequestAcceptsUserAndBoard {
/**
* Current Board set by controller.
*
* @var Board
*/
protected $board;
/**
* Current Board set by controller.
*
* @var PermissionUser
*/
protected $user;
/**
* Returns the request's current board.
*
* @return Board
*/
public function getBoard()
{
return $this->board;
}
/**
* Returns the request's current user.
*
* @return PermissionUser
*/
public function getUser()
{
return $this->user;
}
/**
* Sets the request's board.
*
* @param Board $board
* @return void
*/
public function setBoard(Board $board)
{
$this->board = $board;
}
/**
* Returns the request's user.
*
* @param PermissionUser $user
* @return void
*/
public function setUser(PermissionUser $user)
{
$this->user = $user;
}
}
class BoardConfigRequest extends Request {
use RequestAcceptsUserAndBoard;
}
and then in my controller
public function patchIndex(BoardConfigRequest $request, Board $board)
{
// Re-validate the request with new rules specific to the board.
$request->setBoard($board);
$request->setUser($this->user);
$request->validate();
}