Skip to content

Latest commit

 

History

History
244 lines (201 loc) · 5.98 KB

2.Request.md

File metadata and controls

244 lines (201 loc) · 5.98 KB

2. Request

You can either follow the pattern documented by Laravel to handle requests, or the MVC pattern mentioned below.

Important : Read about Request Lifecycle.

2.1 Handling

Using the Request class or the request() function (that returns the same class) are the two ways of handling requests. Laravel uses it service containers to pass the Request class as a parameter to controller functions.

2.1.1 Authorization & Validation (Form Requests)

Please read more about this here.

The below class is an example containing all functions related to user authorization & validation.

<?php

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;

class StoreBlogPost extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // If you plan to have authorization logic in another part of your application
        return true;

        // else
        $user = User::find($this->route('user'));

        return $user && $this->user()->can('update', $comment);      //    <----- Take note of $this->user() for getting logged in user value
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
      return [
          'title' => 'required|unique:posts|max:255',
          'body' => 'required',
      ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'title' => 'post title',
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required' => 'A title is required',
            'body.required'  => 'A message is required',
        ];
    }

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid($validator)) {
                $validator->errors()->add('field', 'Something is wrong with this field!');
            }
        });
    }

    /**
     * Validate something else.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return bool
     */
    protected function validateSomethingElse($validator)
    {
        // ...
    }
}

2.1.2 Authorization & Validation (MVC)

This is an example of how to validate requests using MVC pattern.

Controller

<?php

namespace App\Http\Controllers;

use App\Services\UserService;

class UserController extends Controller
{
    /**
     * User Service
     *
     * @var \App\Services\UserService
     */
    protected $userService;

    /**
     * Constructor
     *
     * @param \App\Services\UserService    $userService
     *
     * @return void
     */
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    /**
     * Update User
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($user)
    {
        $this->authorize('update', $user);        // Using Policies

        $inputs = request()->all();

        $user = app()->call([$this->userService, 'update'], compact('user', 'inputs'));

        // ... Redirect with Flash Message or JsonResponse for API etc.
    }
}

Service

<?php

namespace App\Services;

use App\Repositories\Contract\UserRepositoryInterface;

class UserService
{
    /**
     * User Repository
     *
     * @var \App\Repositories\Contract\UserRepositoryInterface
     */
    protected $userRepository;

    /**
     * UserService Constructor
     *
     * @param \App\Repositories\Contract\UserRepositoryInterface $userRepo
     */
    public function __construct(UserRepositoryInterface $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    /**
     * Update User
     *
     * @param \App\Validators\UserValidator $validator
     * @param \App\Models\User $user
     * @param array $inputs
     * @param bool $isAdminRequest
     * @return \App\Models\User
     *
     * @throws \App\Exceptions\ValidationException
     */
    public function update(UserValidator $validator, $user, array $inputs, $isAdminRequest = false)
    {
        $inputs = $this->transformInputsForValidation($inputs);               // <----- If required...

        $validator->fire($inputs, 'update', compact('user', 'isAdminRequest'));     // <----- Custom Validator

        $inputs = $this->transformInputs($inputs);                            // <----- Required almost always...

        $this->userRepository->update($user, $inputs);

        return $user->refresh();
    }

    /**
     * Transform Inputs - This is required
     * when you want to transform inputs like
     * "password" and convert it into a hash string.
     *
     * @param  array  $inputs
     *
     * @return array
     */
    protected function transformInputs(array $inputs)
    {
        // You can also use array_map()
        // But it isn't preferred especially
        // because sometimes you want to unset
        // some input fields and not return them.
        foreach ($inputs as $key => $input) {
            switch ($key) {
                case 'password':
                    // $inputs['key'] = encrypt($input);
                    break;
                case 'fieldName':
                    // $inputs[$key] = ....
                    break;
                default:
                    break;
            }
        }

        return $inputs;
    }
}