Using repository in a FormRequest in Laravel for custom business rule validation

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
1
down vote

favorite












This is my app/Http/Requests/Organisation/CreateOrganisationRequest.php



<?php

namespace AppHttpRequestsOrganisation;

use AppContractsOrganisationInterface;
use IlluminateFoundationHttpFormRequest;
use AppHttpControllersApiBaseApiController;
use SymfonyComponentHttpKernelExceptionHttpException;

class CreateOrganisationRequest extends FormRequest

private $organisationRepository;

public function __construct(
array $query = array(),
array $request = array(),
array $attributes = array(),
array $cookies = array(),
array $files = array(),
array $server = array(),
$content = null,
OrganisationInterface $organisationRepository
)
parent::__construct($query, $request, $attributes, $cookies, $files, $server, $content);
$this->organisationRepository = $organisationRepository;


public function authorize()

return true;


public function rules()
unique:organisations,name'
];


public function withValidator($validator)

$validator->after(function()
$this->checkIfMaxOrganisationLimitReached();
);


private function checkIfMaxOrganisationLimitReached()

$currentOrganisationsCount = $this->organisationRepository->myOrganisationCount();
$maxOrganisationsLimit = auth()->user()->max_organisations;

if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit)
throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, $maxOrganisationsLimit.");





and it's used in the controller like this:



public function store(CreateOrganisationRequest $request)

$validatedData = array_merge(
$request->validated(),
['owner_id' => auth()->user()->id]
);

$organisation = $this->organisationRepository->create($validatedData);

return $this->success(
fractal($organisation, new OrganisationTransformer()),
$this::Created
);



This works and get's the job done, but I am unsure if this is a good approach in Laravel.



P.S. The HttpException that I throw is handled by appExceptionsHandler.php.




Another approach I've considered is to add a custom attribute to User model like this:



public function getOrganisationCountAttribute()

if ($this->account_owner)
return $this->organisations()->count();

return 0;



and update my CreateOrganisationRequest (i.e. the FormRequest) by removing the repository and do this instead in my business rule validation:



private function checkIfMaxOrganisationLimitReached()

$currentOrganisationsCount = auth()->user()->organisation_count;
$maxOrganisationsLimit = auth()->user()->max_organisations;

if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit)
throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, $maxOrganisationsLimit.");








share|improve this question



























    up vote
    1
    down vote

    favorite












    This is my app/Http/Requests/Organisation/CreateOrganisationRequest.php



    <?php

    namespace AppHttpRequestsOrganisation;

    use AppContractsOrganisationInterface;
    use IlluminateFoundationHttpFormRequest;
    use AppHttpControllersApiBaseApiController;
    use SymfonyComponentHttpKernelExceptionHttpException;

    class CreateOrganisationRequest extends FormRequest

    private $organisationRepository;

    public function __construct(
    array $query = array(),
    array $request = array(),
    array $attributes = array(),
    array $cookies = array(),
    array $files = array(),
    array $server = array(),
    $content = null,
    OrganisationInterface $organisationRepository
    )
    parent::__construct($query, $request, $attributes, $cookies, $files, $server, $content);
    $this->organisationRepository = $organisationRepository;


    public function authorize()

    return true;


    public function rules()
    unique:organisations,name'
    ];


    public function withValidator($validator)

    $validator->after(function()
    $this->checkIfMaxOrganisationLimitReached();
    );


    private function checkIfMaxOrganisationLimitReached()

    $currentOrganisationsCount = $this->organisationRepository->myOrganisationCount();
    $maxOrganisationsLimit = auth()->user()->max_organisations;

    if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit)
    throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, $maxOrganisationsLimit.");





    and it's used in the controller like this:



    public function store(CreateOrganisationRequest $request)

    $validatedData = array_merge(
    $request->validated(),
    ['owner_id' => auth()->user()->id]
    );

    $organisation = $this->organisationRepository->create($validatedData);

    return $this->success(
    fractal($organisation, new OrganisationTransformer()),
    $this::Created
    );



    This works and get's the job done, but I am unsure if this is a good approach in Laravel.



    P.S. The HttpException that I throw is handled by appExceptionsHandler.php.




    Another approach I've considered is to add a custom attribute to User model like this:



    public function getOrganisationCountAttribute()

    if ($this->account_owner)
    return $this->organisations()->count();

    return 0;



    and update my CreateOrganisationRequest (i.e. the FormRequest) by removing the repository and do this instead in my business rule validation:



    private function checkIfMaxOrganisationLimitReached()

    $currentOrganisationsCount = auth()->user()->organisation_count;
    $maxOrganisationsLimit = auth()->user()->max_organisations;

    if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit)
    throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, $maxOrganisationsLimit.");








    share|improve this question























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      This is my app/Http/Requests/Organisation/CreateOrganisationRequest.php



      <?php

      namespace AppHttpRequestsOrganisation;

      use AppContractsOrganisationInterface;
      use IlluminateFoundationHttpFormRequest;
      use AppHttpControllersApiBaseApiController;
      use SymfonyComponentHttpKernelExceptionHttpException;

      class CreateOrganisationRequest extends FormRequest

      private $organisationRepository;

      public function __construct(
      array $query = array(),
      array $request = array(),
      array $attributes = array(),
      array $cookies = array(),
      array $files = array(),
      array $server = array(),
      $content = null,
      OrganisationInterface $organisationRepository
      )
      parent::__construct($query, $request, $attributes, $cookies, $files, $server, $content);
      $this->organisationRepository = $organisationRepository;


      public function authorize()

      return true;


      public function rules()
      unique:organisations,name'
      ];


      public function withValidator($validator)

      $validator->after(function()
      $this->checkIfMaxOrganisationLimitReached();
      );


      private function checkIfMaxOrganisationLimitReached()

      $currentOrganisationsCount = $this->organisationRepository->myOrganisationCount();
      $maxOrganisationsLimit = auth()->user()->max_organisations;

      if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit)
      throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, $maxOrganisationsLimit.");





      and it's used in the controller like this:



      public function store(CreateOrganisationRequest $request)

      $validatedData = array_merge(
      $request->validated(),
      ['owner_id' => auth()->user()->id]
      );

      $organisation = $this->organisationRepository->create($validatedData);

      return $this->success(
      fractal($organisation, new OrganisationTransformer()),
      $this::Created
      );



      This works and get's the job done, but I am unsure if this is a good approach in Laravel.



      P.S. The HttpException that I throw is handled by appExceptionsHandler.php.




      Another approach I've considered is to add a custom attribute to User model like this:



      public function getOrganisationCountAttribute()

      if ($this->account_owner)
      return $this->organisations()->count();

      return 0;



      and update my CreateOrganisationRequest (i.e. the FormRequest) by removing the repository and do this instead in my business rule validation:



      private function checkIfMaxOrganisationLimitReached()

      $currentOrganisationsCount = auth()->user()->organisation_count;
      $maxOrganisationsLimit = auth()->user()->max_organisations;

      if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit)
      throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, $maxOrganisationsLimit.");








      share|improve this question













      This is my app/Http/Requests/Organisation/CreateOrganisationRequest.php



      <?php

      namespace AppHttpRequestsOrganisation;

      use AppContractsOrganisationInterface;
      use IlluminateFoundationHttpFormRequest;
      use AppHttpControllersApiBaseApiController;
      use SymfonyComponentHttpKernelExceptionHttpException;

      class CreateOrganisationRequest extends FormRequest

      private $organisationRepository;

      public function __construct(
      array $query = array(),
      array $request = array(),
      array $attributes = array(),
      array $cookies = array(),
      array $files = array(),
      array $server = array(),
      $content = null,
      OrganisationInterface $organisationRepository
      )
      parent::__construct($query, $request, $attributes, $cookies, $files, $server, $content);
      $this->organisationRepository = $organisationRepository;


      public function authorize()

      return true;


      public function rules()
      unique:organisations,name'
      ];


      public function withValidator($validator)

      $validator->after(function()
      $this->checkIfMaxOrganisationLimitReached();
      );


      private function checkIfMaxOrganisationLimitReached()

      $currentOrganisationsCount = $this->organisationRepository->myOrganisationCount();
      $maxOrganisationsLimit = auth()->user()->max_organisations;

      if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit)
      throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, $maxOrganisationsLimit.");





      and it's used in the controller like this:



      public function store(CreateOrganisationRequest $request)

      $validatedData = array_merge(
      $request->validated(),
      ['owner_id' => auth()->user()->id]
      );

      $organisation = $this->organisationRepository->create($validatedData);

      return $this->success(
      fractal($organisation, new OrganisationTransformer()),
      $this::Created
      );



      This works and get's the job done, but I am unsure if this is a good approach in Laravel.



      P.S. The HttpException that I throw is handled by appExceptionsHandler.php.




      Another approach I've considered is to add a custom attribute to User model like this:



      public function getOrganisationCountAttribute()

      if ($this->account_owner)
      return $this->organisations()->count();

      return 0;



      and update my CreateOrganisationRequest (i.e. the FormRequest) by removing the repository and do this instead in my business rule validation:



      private function checkIfMaxOrganisationLimitReached()

      $currentOrganisationsCount = auth()->user()->organisation_count;
      $maxOrganisationsLimit = auth()->user()->max_organisations;

      if (($currentOrganisationsCount + 1) > $maxOrganisationsLimit)
      throw new HttpException(BaseApiController::Bad_Request, "You have reached maximum organisations that can be created, $maxOrganisationsLimit.");










      share|improve this question












      share|improve this question




      share|improve this question








      edited Feb 25 at 0:11
























      asked Feb 25 at 0:01









      Latheesan

      1939




      1939

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f188299%2fusing-repository-in-a-formrequest-in-laravel-for-custom-business-rule-validation%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f188299%2fusing-repository-in-a-formrequest-in-laravel-for-custom-business-rule-validation%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Greedy Best First Search implementation in Rust

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          C++11 CLH Lock Implementation