0

Hello im creating i comment system for my laravel app but i get this error when i try to comment.. basically when a user is not logged in and he tries to comment and submit it, it should redirect him to the login page, so my CreateRequest file is this

<?php

namespace App\Http\Requests\Comment;

use App\Http\Requests\Request;
use App\Repositories\Image\ImageRepository;

class CreateRequest extends Request {
    /**
     * Determine if the user is authorized to make this request.
     *
     * @param ImageRepository $image
     * @return bool
     */
    public function authorize(ImageRepository $image) {
        $image = $image->getById($this->route('id'))->first();
        if (!$image) {
            return false;
        }
        return auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() {
        return [
            'comment' => ['required', 'min:2'],
        ];
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function forbiddenResponse() {
        return redirect()->route('login');
    }
}

and my App\Http\Requests\Request file is this

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest {
    public function authorize() {
        return true;
    }
}

if i remove

public function authorize() {
    return true;
}

then comments works and if user is not logged in the user gets redirected to the login page but then my login is not working and i get Forbidden when i try to login

im developing my app on top of this project https://github.com/laravelish/EasyAdmin Hope someone can help me

Fatih Akgun
  • 479
  • 1
  • 6
  • 18

1 Answers1

2

You've defined an authorize method in your abstract Request class:

public function authorize() {
    return true;
}

Note it doesn't take any parameters. Now if you extend this abstract class (like you are doing with CreateRequest) and you write an authorize method, you must use the same signature. Specifically: authorize can't take any parameters, because it doesn't in the abstract class.


If you were to remove the authorize method from your abstract class, this specific error would go away. However I'm not sure that would solve your problem. I don't think Laravel provides dependency injection for the authorize method, you can't just inject your repository like that.

This is one way to fix both issues:

public function authorize() {
    $image = app(ImageRepository::class)->getById($this->route('id'))->first();
    ...
jszobody
  • 28,495
  • 6
  • 61
  • 72