Resource validation & authorize best practices

Posted 3 years ago by dmitry.g.ivanov

Hi there!

I have typical simple resource controller - TasksController. Each Task is owned by a User. I want to protect Tasks from being updated or deleted NOT by their owner User. Also, there are some simple validations for tasks form.

So, here is my solution:

class TasksController extends Controller
{
    // ...
    public function store(TaskRequest $request)
    {
        $task = Auth::user()->tasks()->create($request->all());
        return Redirect::route('tasks.index');
    }

    public function update(TaskRequest $request, Task $task)
    {
        $task->update($request->all());
        return Redirect::route('tasks.index');
    }

    public function destroy(TaskRequest $request, Task $task)
    {
        $task->delete();
        return Redirect::route('tasks.index');
    }
    // ...
}

And my TaskRequest class:

class TaskRequest extends Request
{
    public function authorize()
    {
        if (empty($this->task)) {
            return true;
        }

        $user = Auth::user();
        return $this->task->isOwnedBy($user);
    }

    public function rules()
    {
        if (request()->isMethod('DELETE')) {
            return [];
        }

        return [
            'name' => 'required|min:10',
            'description' => 'required',
        ];
    }
}

So, I'm performing authorize checks by a common injected TaskRequest object, and I like it, BUT I'm not sure is that a best solution? I don't really like unused variable TaskRequest $request in TasksController@destroy. And I don't really like that mix of logic in my TaskRequest class.

Any ideas? Thanks and have a great day!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.