Hanie Asemi
Hanie Asemi

Reputation: 1500

Call to a member function hasAccessOrFail() on null error when using backpack in Laravel

I've been using backpack in Laravel but I want to replace action-domain-responder architecture with MVC.So I've created an Action which my route refers like below:

Route::get('post',[
  'as' => 'post.index',
  'uses' => 'Core\Post\Actions\ApiGetListOfPostsAction',
  'operation' => 'list'
]);

class ApiGetListOfPostsAction extends BaseAction implements IAction
 {
   private $service;

   public function __construct(ApiGetListOfPostsService $service)
     {
        $this->service = $service;
     }

   public function __invoke(Request $request): mixed
     {
       $data =  $this->service->process();
       return response()->json($data);
     }
  }

and my service has this code:

class ApiGetListOfPostsService extends CrudController
  {
     use ListOperation, CreateOperation, DeleteOperation, UpdateOperation;

     public function setup()
       {
         CRUD::setModel(\App\Models\Post::class);
         CRUD::setRoute(config('backpack.base.route_prefix') . '/post');
         CRUD::setEntityNameStrings('post', 'posts');
       }

    protected function setupListOperation()
       {
         CRUD::column('title');
         CRUD::column('content');
       }

    public function process()
      {
        return $this->index();
      }
  }

I've extended CrudController in my service class but I've got this error:

Call to a member function hasAccessOrFail() on null

which related to the ListOperation Trait and this code:

public function index()
 {
    $this->crud->hasAccessOrFail('list');
 }

I need to send all requests to the Service class. How can I pass requests to the service class? When I deleted middleware from CrudController I have no problem.

$this->middleware(function ($request, $next) {
    $this->crud = app()->make('crud');
    $this->crud->setRequest($request);

    $this->setupDefaults();
    $this->setup();
    $this->setupConfigurationForCurrentOperation();

     return $next($request);
  });

Upvotes: 0

Views: 342

Answers (1)

z5ottu
z5ottu

Reputation: 107

I think your Action is missing something.

When using inheritance from a parent class, it might help to put this line in your constructor.

 public function __construct(ApiGetListOfPostsService $service)
 {
    parent::__construct();   // <- Subclass constructor
    $this->service = $service;
 }

Doc: https://www.php.net/manual/en/language.oop5.decon.php

Upvotes: 0

Related Questions