A
A
Alexey Sklyarov2020-12-17 12:17:06
Laravel
Alexey Sklyarov, 2020-12-17 12:17:06

Why nothing happens when using the custom Request class in the controller's store method?

There is a store method of the PostController controller:

PostController.php

public function store(StorePostRequest $request)
    {
        try {
            $validator = $request->validated();
            if ($validator->fails()) {
                return redirect()->route('dashboard.posts.create')
                            ->withErrors($validator)
                            ->withInput();
            }
            dd($validator);
            $post = new Post;
            $post->title = $validator->title;
            $post->slug = $validator->slug;
            $post->save();
            return redirect()->route('dashboard.posts.create')->with('success', 'Пост успешно добавлен.');
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }


There is a Request class in which the fields are validated:
StorePostRequest.php
<?php

namespace App\Http\Requests\Post;

use Illuminate\Foundation\Http\FormRequest;
use Rule;

class StorePostRequest extends FormRequest
{
    public function authorize()
    {
        return auth()->check() && $this->user()->hasRole('admin');
    }

    public function rules()
    {
        return [
            'slug' => 'required|string|unique:posts',
            'title' => 'required|string|max:255'
        ];
    }
}

I create a record (the number of fields is more than should be validated), but all the time there is a redirect back to the post creation form (and even if you do not specify route()), the method dd()does not work, I went through Stackoverflow, many who had a similar problem, it is usually solved by indicating in the controller, but everything is fine with me in this regard, I don’t know what to catch on to determine what the problem might be. In what all the same there can be a problem? use App\Http\Requests\Post\StorePostRequest;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JhaoDa, 2020-12-17
@0example

If you read the documentation, you would know that form request validation is applied automatically when a controller method is called, i.e. business does not even reach your strange code. But you do not read the documentation and give birth to crutches with splinters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question