ideas icon indicating copy to clipboard operation
ideas copied to clipboard

Throw error when saving faulty Statamic objects programmatically

Open samjurriaans opened this issue 1 year ago • 1 comments

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.

samjurriaans avatar Apr 15 '24 15:04 samjurriaans

Two more alternatives to automatically validating + throwing an exception:

  • have Entry::make()->save() return false when the entry is invalid/cannot be saved
  • create a new function Entry::make()->validate()->save() that we can call manually to validate content before saving - this could throw an exception

Or just have all of the above :)

godismyjudge95 avatar Apr 15 '24 17:04 godismyjudge95