spatie / laravel-permission

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

ErrorException : Trying to access array offset on value of type null. On fresh laravel installation. #1370

Closed abdellahrk closed 4 years ago

abdellahrk commented 4 years ago

I can't install the package on my recent laravel project. It works fine on the previous ones. Here is the error I get

`composer require spatie/laravel-permission Using version ^3.6 for spatie/laravel-permission ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 1 removal

Installation failed, reverting ./composer.json to its original content.`

abdellahrk commented 4 years ago

@drbyte help.

drbyte commented 4 years ago

I can't replicate this situation.

  1. What Laravel version?
  2. What PHP version?
  3. You said it's a "fresh laravel installation", and yet it shows that you've had other packages installed which it is removing when you attempt to install this package. In what other ways is this "fresh laravel install" not "fresh"?

Complete details are needed in order to recreate the situation where this is happening, in order to fix it.

abdellahrk commented 4 years ago

Hi @drbyte I have laravel 6.3, php version 7.4 It is removing the previously installed spatie/permission which still was unsuccessful. Yes it is a fresh install and no other package has been installed only spatie/permission. That is the complete detail I have sent up. I posted all because you pointed out that this issue #1360 was not having enough information. Thanks.

drbyte commented 4 years ago
  • Removing spatie/laravel-view-components (1.2.0)

That's a completely different package. Were you getting similar errors with it too?

drbyte commented 4 years ago

Fresh install now:

> php -v
PHP 7.4.2 (cli) (built: Jan 22 2020 06:34:34) ( NTS )

> laravel new baz
Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 85 installs, 0 updates, 0 removals
...
  - Installing laravel/framework (v6.15.1): Loading from cache
  - Installing phar-io/version (2.0.1): Loading from cache
  - Installing phar-io/manifest (1.0.3): Loading from cache
  - Installing myclabs/deep-copy (1.9.5): Loading from cache
  - Installing phpunit/phpunit (8.5.2): Loading from cache
...
Generating optimized autoload files
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
> @php artisan key:generate --ansi
Application key set successfully.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
Application ready! Build something amazing.

> cd baz
> composer require spatie/laravel-permission
Using version ^3.6 for spatie/laravel-permission
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing spatie/laravel-permission (3.6.0): Loading from cache
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Discovered Package: spatie/laravel-permission
Package manifest generated successfully.

No errors with a purely fresh install of Laravel 6.15.1.

drbyte commented 4 years ago

I have laravel 6.3, php version 7.4

How/Why are you using 6.3 when 6.15.1 is the latest available at this moment?

(I'm not sure if there's a Laravel bug specific to that version, but I'm looking for any anomaly that would point to why you're having a problem but others are not.)

drbyte commented 4 years ago

It is removing the previously installed spatie/permission

Please clarify: how was there a previously installed spatie/permission if this was a "fresh laravel installation"?

Were you actually trying to upgrade from an older Laravel version which had an older spatie/permission installed?

drbyte commented 4 years ago

Found it: You have a pre-existing config/permission.php with very specific invalid data in it.

Specifically, your config/permission.php appears to contain a null value for the models key.

<?php
// NOTE: This is invalid!
return [
    'models' => null,
];

I have no idea how the file got there if this is a "fresh laravel installation".

Further, I have no idea why you would set that entry to null, when all versions of this package have always treated it as an array with specific entries in it to denote which models are used for roles and permissions in your app.

If the file is present but empty an array_merge error occurs. If the file is present and has models set to an empty array, then an Undefined index error occurs. If the file is present but has models set to a string, then an Illegal string offset 'permission' error occurs. If the file is present but specifically has models set to null then Trying to access array offset on value of type null occurs.

Solution

Simple solution: delete the config/permission.php file that you added prior to installing this package.

abdellahrk commented 4 years ago

It is removing the previously installed spatie/permission

Please clarify: how was there a previously installed spatie/permission if this was a "fresh laravel installation"?

Were you actually trying to upgrade from an older Laravel version which had an older spatie/permission installed?

No. In the same laravel installer, I had previously tried composer require spatie/laravel-permission and it gave the same error. When I am trying a reinstall, it removes the previous package I tried installing.

abdellahrk commented 4 years ago

Solution

Simple solution: delete the config/permission.php file that you added prior to installing this package.

I don't have the permission.php file in the config folder.

abdellahrk commented 4 years ago

I have laravel 6.3, php version 7.4

How/Why are you using 6.3 when 6.15.1 is the latest available at this moment?

(I'm not sure if there's a Laravel bug specific to that version, but I'm looking for any anomaly that would point to why you're having a problem but others are not.)

I used laravel new and it came with laravel ^6.2 in composer.json file.

drbyte commented 4 years ago

Prior to v3.7.0 this package expected to be able to call isNotLumen() to detect Lumen vs Laravel. If you have a global function called isNotLumen() already defined then this package will defer to that, and if yours doesn't return a proper response then it won't register the configuration, thus resulting in a Trying to access array offset on value of type null error.

https://github.com/spatie/laravel-permission/blob/c9e297389c9473e0dafc48b41dfcce9bb16eb6e0/src/helpers.php#L28-L31

abdellahrk commented 4 years ago

@drbyte it is so embarrassing I installed on another new project and it was okay. I can't produce where the problem came from. I will just copy some work I did on the first to the new app. Thanks for the time and sorry for also disturbing you.

drbyte commented 4 years ago

Thanks for posting back. I'm glad you found where the problem was! 👍

AMAFsoft commented 4 years ago

In case some have the same issue. Just remove : vendor/composer/autoload_classmap.php and autoload_static.php and run composer dumpautoload This solved the problem form me. And for more information, i think this is because an unfinished instalation. I hope this help someone :)

petersowah commented 4 years ago

I am having this same issue.

`> @php artisan package:discover --ansi

ErrorException : Trying to access array offset on value of type null

at /Users/petersowah/dev/php/laravel/grow-web/vendor/spatie/laravel-permission/src/PermissionServiceProvider.php:60 56| protected function registerModelBindings() 57| { 58| $config = $this->app->config['permission.models']; 59|

60| $this->app->bind(PermissionContract::class, $config['permission']); 61| $this->app->bind(RoleContract::class, $config['role']); 62| } 63| 64| protected function registerBladeExtensions()

Exception trace:

1 Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Trying to access array offset on value of type null", "/Users/petersowah/dev/php/laravel/grow-web/vendor/spatie/laravel-permission/src/PermissionServiceProvider.php", []) /Users/petersowah/dev/php/laravel/grow-web/vendor/spatie/laravel-permission/src/PermissionServiceProvider.php:60

2 Spatie\Permission\PermissionServiceProvider::registerModelBindings() /Users/petersowah/dev/php/laravel/grow-web/vendor/spatie/laravel-permission/src/PermissionServiceProvider.php:36`

Any idea on how to proceed? @drbyte

PS: I don't have a permission.php file in config.

drbyte commented 4 years ago

Odd. What Laravel version? What PHP version? Do you have the same problem if you force the package version to 3.6.0 specifically?

petersowah commented 4 years ago

Laravel v6.17.1. When I use version 3.6.0 I do get same errors. I'm using PHP 7.4.2

SeanFacer commented 4 years ago

Same issue

drbyte commented 4 years ago

Strange.

What's different between your environment and mine? (I'm using Valet 2.8.1, with latest composer self-update, latest composer global update, and latest brew upgrade, all updated this morning)

php -v
PHP 7.4.3 (cli) (built: Feb 20 2020 12:23:37) ( NTS )

> laravel new baz2
Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 85 installs, 0 updates, 0 removals
...
  - Installing laravel/framework (v6.17.1): Loading from cache
  - Installing fideloper/proxy (4.3.0): Loading from cache
  - Installing jakub-onderka/php-console-color (v0.2): Loading from cache
  - Installing nikic/php-parser (v4.3.0): Loading from cache
  - Installing jakub-onderka/php-console-highlighter (v0.4): Loading from cache
  - Installing dnoegel/php-xdg-base-dir (v0.1.1): Loading from cache
  - Installing psy/psysh (v0.9.12): Loading from cache
  - Installing laravel/tinker (v2.2.0): Loading from cache
  - Installing scrivo/highlight.php (v9.18.1.1): Loading from cache
  - Installing filp/whoops (2.7.1): Loading from cache
...
Generating optimized autoload files
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
> @php artisan key:generate --ansi
Application key set successfully.
cd> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
 Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
Application ready! Build something amazing.

> cd baz2
baz2 > composer require spatie/laravel-permission
Using version ^3.9 for spatie/laravel-permission
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing spatie/laravel-permission (3.9.0): Loading from cache
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Discovered Package: spatie/laravel-permission
Package manifest generated successfully.
SeanFacer commented 4 years ago

We are running 7.4.2 on server. Not sure why its bombing atm. Works on 7.4.1 locally.

SeanFacer commented 4 years ago

it's 7.4.2, runs on both 7.4.1 and 7.4.3

drbyte commented 4 years ago

I'm not convinced that it's just a 7.4.2 thing. See my post earlier in this issue: https://github.com/spatie/laravel-permission/issues/1370#issuecomment-586589236

I'm going to release 3.10.0 to "patch" this. But it'd be very valuable if you could provide steps to trigger this locally so we can provide a proper fix without this ugly patch.

petersowah commented 4 years ago

I run composer global update and I'm back in business. Thanks @drbyte

drbyte commented 4 years ago

3.10.1 was also released to handle weird edge cases with migrations as well. I can't replicate the problem without mangling the code in ways that are very unrealistic, but it should stop behaving in confusing ways if this odd condition is encountered elsewhere again.

doncadavona commented 4 years ago

composer update worked for me.

I had a Laravel 5.6 app, with Php 7.1.

Also, I had to change laracasts/generators in composer.json to ^1.0 from dev-master to get composer update going:

"laracasts/generators": "^1.0"

Started having this issue working back on some old projects, the issue occurs on php artisan migrate right after composer install.

oviniciusfeitosa commented 3 years ago

Solution:

php artisan config:clear

or

sail artisan config:clear

gitRup-ca commented 3 years ago

The suggestions above by AMAsoft remove/rename -> vendor/composer/autoload_classmap.php and autoload_static.php [files will be recreated] THEN composer dump-autoload THEN php artisan package:discover THEN php artisan config:cache [clears and recreates ] Using latest versions of Laravel, Fortify, Sanctum, Tailwind, and Spatie CSP; with substantial custom vanilla JS. Installed nicely into existing project. Hope this helps - Spatie is awesome.

mytrytest commented 6 months ago

I am also stuck. Please find below code in file(.ebextensions/cron.config)

files:
        "/etc/cron.d/schedule_run":
            mode: "000644"
            owner: root
            group: root
            content: |
                55 23 * * * root . /opt/elasticbeanstalk/deployment/env && /usr/bin/php /var/www/html/artisan schedule:run 1>> /var/www/html/storage/logs/laravel_cron.log 2>&1

    commands:
        remove_old_cron:
            command: "rm -f /etc/cron.d/*.bak"

I checked log in log file and I got below error.

**In BroadcastManager.php line 184:

  Trying to access array offset on value of type null**

I can see below method in BroadcastManager.php line 184

 protected function resolve($name)
        {
            $config = $this->getConfig($name);

            if (isset($this->customCreators[$config['driver']])) {
                return $this->callCustomCreator($config);
            }

            $driverMethod = 'create'.ucfirst($config['driver']).'Driver';

            if (! method_exists($this, $driverMethod)) {
                throw new InvalidArgumentException("Driver [{$config['driver']}] is not supported.");
            }

            return $this->{$driverMethod}($config);
        }

I checked it in local and I got 'pusher' value in $name variable. But I think it will not work at server.

I don't understand reason why it's not working. I think cron is working but error is coming from my command file.

namespace App\Console\Commands;

    use Illuminate\Console\Command;

    use App\Models\User;
    use Illuminate\Support\Facades\Log;
    use Carbon\Carbon;

    class RemiderEmailToUsers extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'RemiderEmailToUsers';

        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'Remider email to users';

        /**
         * Create a new command instance.
         *
         * @return void
         */
        public function __construct()
        {
            parent::__construct();
        }

        /**
         * Execute the console command.
         *
         * @return int
         */
        public function handle()
        {
            $users = User::whereDate('created_at', Carbon::today()->subDays(1))
             ->get()->toArray();

            $count = 0;

            if(!empty($users)) {

                echo "Total {$count} users added \n";
            }
            else {
                echo "No user available \n";
            }

        }
    }

I am calling this command from kernel file.

 namespace App\Console;

    use Illuminate\Console\Scheduling\Schedule;
    use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

    class Kernel extends ConsoleKernel
    {
        /**
         * Define the application's command schedule.
         *
         * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
         * @return void
         */

        protected $commands = [
            // Add your command here
            //'App\Console\Commands\RemiderEmailToTrialUsers',
            Commands\RemiderEmailToUsers::class,
        ];

        protected function schedule(Schedule $schedule)
        {
            $schedule->command('RemiderEmailToUsers')
                     ->dailyAt('23:55');

        }

I tried to fix it by changes lot of things but still I am getting same error.