spatie / laravel-permission

Associate users with roles and permissions
https://spatie.be/docs/laravel-permission
MIT License
12.04k stars 1.76k forks source link

Call to a member function `prepare()` on null when using the database `cache` store #2704

Closed abbasmashaddy72 closed 2 weeks ago

abbasmashaddy72 commented 4 weeks ago

Description

When using the database cache store in Laravel, the following error occurs during migration and seeding operations related to the Spatie Laravel Permission package:

Call to a member function prepare() on null

This error occurs specifically at the following lines in the code:

Line From Database Migration:

app('cache')
    ->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
    ->forget(config('permission.cache.key'));

and

Line from Custom Seeder:

app()[PermissionRegistrar::class]->forgetCachedPermissions();

Additional Context

This issue does not occur when the cache store is set to file. Changing the cache store to file and re-running the migrations and seeding works flawlessly.

Steps To Reproduce

  1. Set the default cache store to database:

    • In config/cache.php, set:
      'default' => env('CACHE_DRIVER', 'database'),
  2. Set the permission cache store to default:

    • In config/permission.php, set:
      'cache' => [
       'store' => 'default',
      ],
  3. Run migrations and seeding:

    • Run the following Artisan commands:
      php artisan migrate --seed
  4. Observe the error:

    • The migration and seeding process fails with the following error:
      Call to a member function prepare() on null

Example Application

No response

Version of spatie/laravel-permission package:

6.9

Version of laravel/framework package:

11.9

PHP version:

8.3

Database engine and version:

mariadb from 11.4.2-MariaDB, client 15.2 for Linux (x86_64) using readline 5.1

OS: Windows/Mac/Linux version:

Linux

drbyte commented 3 weeks ago

The prepare() call is Eloquent trying to prepare a SQL query on a table that doesn't exist.

If you are going to use Database caching, you must first create a database-migration file for the database cache table. (And name its filename so that it runs before the permissions migration runs.)

That would fix the seeder issue too, because the cache table would exist then.

See the Laravel documentation on prerequisites for database caching: https://laravel.com/docs/master/cache#prerequisites-database and/or github source code: https://github.com/laravel/framework/blob/11.x/src/Illuminate/Cache/Console/stubs/cache.stub

abbasmashaddy72 commented 2 weeks ago

Hi, Got it working with some tweaks but don't remember the changes I made. But Now it is working fine. If someone is having the same issue, can tag me so that I can provide the correct process.