statamic / ideas

đŸ’¡Discussions on ideas and feature requests for Statamic
https://statamic.dev
31 stars 1 forks source link

Throw error when saving faulty Statamic objects programmatically #1150

Open samjurriaans opened 5 months ago

samjurriaans commented 5 months ago

Today I ran into a situation that the Statamic Control Panel was not working, due to a NavItem object not being able to successfully call the function resolveChildren(). The exact error was as follows:

Call to a member function url() on null (View: /var/www/xxx/vendor/statamic/cms/resources/views/layout.blade.php) (View: /var/www/xxx/vendor/statamic/cms/resources/views/layout.blade.php)

vendor/statamic/cms/src/CP/Navigation/CoreNav.php in Illuminate\View\Engines\CompilerEngine::handleViewException at line 274

The bug itself was in a way totally unrelated to the navigation, since it was caused by the following seeder of mine:

<?php

namespace Database\Seeders;

use App\Enums\Permissions\ApiUserPermissions;
use App\Enums\Roles;
use Illuminate\Database\Seeder;
use Statamic\Facades\Role;

class RoleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run(): void
    {
        $role = Role::make(Roles::ApiUser->value)->permissions(ApiUserPermissions::values());
        $role->save();
    }
}

Some of you may now already see what the cause of the problem is: The saved role was missing a filled in title property and the fix was as follows:

$role = Role::make(Roles::ApiUser->value)->title('Api User')->permissions(ApiUserPermissions::values());

It took me quite some time to figure out what the problem was. And I was thinking that it would have been very helpful to have either a more helpfull error in the control panel or that I would have wanted to see the error already during the saving of the role.

To me it seems like the best approach the have some kind of validation in place that throws an error the moment I try to save any Statamic Objects programmatically that is application breaking.

So my feature request would be to add error throwing validation when one tries to save Statamic objects like Entries and Roles e.g.

godismyjudge95 commented 5 months ago

Two more alternatives to automatically validating + throwing an exception:

Or just have all of the above :)