A
A
Alexey Sklyarov2021-03-01 16:18:11
Laravel
Alexey Sklyarov, 2021-03-01 16:18:11

Where is it better to start filtering the passed comment text for later saving?

Task : to implement the ability for some user groups to leave links in the comments, for the rest - to delete links.

Data from the user gets into the controller,

public function store(StoreReviewRequest $request) {}

where they are validated, then I get valid data: $validatedData = $request->validated();

Then I need to apply filters to the review/comment text, for this I wrote a filter:
filter

abstract class Filter
{
    protected $content;
    protected $filter;

    public function __construct($content,array $filters)
    {
        $this->content = $content;
        $this->filters = $filters;
    }

    public function apply()
    {
       // code
    }

}


TextFilter

class TextFilter extends Filter
{
    /**
     * Wrap links filter
     * 
     * @return void
     */
    public function wrapLinks()
    {
       // Code
    }
}


I wrote a gate with which I check the user's ability to leave links in the comments:

if(Gate::allows('useLinkInComments', $request->user()) {
  //code
}


And actually, before passing the data to the model, I need to apply these filters after checking the Gate. I do it like this:
new TextFilter($validatedData['message'],['wrap-links'])->apply();

Where is the best place to do it? In the controller? In this case (if the logic grows), the controller will grow to a large size. Use the afterValidation hook? But they seem to write that it is purely for customizing errors. What are the correct solutions to my problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Sarvarov, 2021-03-01
@0example

There are many ways to do this, but definitely not in the controller.
I would make CommentObserver:

php artisan make:observer CommentObserver --model=Comment

and there in the method saving(Comment $comment)I would check whether the user has the right (using a policy, not a gate, by the way) and filter it as it should.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question