Delete a page from frontend

I am trying to delete pages from frontend. For that, I have set up a button that calls my controller and passes it the UID of the page I want to delete:

<form action="<?= $page->url() ?>" method="POST">
     <input type="text" id="link" name="link" value="<?= $link->uid() ?>" required>
     <input type="submit" name="delete" value="Delete Link">
</form>

In my controller, I have tried several ways to delete the page. However I either get an Array to String conversion error or a “Call to a member function find() on null” error.

if ($kirby->request()->is('POST') && get('delete')) {
			
	        $data = [
	            'link'  => get('link')
	        ];

			try {
				
				$page->find($data['link'])->delete();

// I have also tried the following obviously not at the same time

				$page($data['link'])->delete();
				
				
			} catch (Exception $error) {
                if(option('debug')):
                    $alert['error'] = 'The link could not be deleted: <strong>' . $error->getMessage() . '</strong>';
                else:
                    $alert['error'] = 'The link could not be deleted';
                endif;
            }

Is the page you want to delete a child of the current page?

In any case, you should never call a class method without prior checking if you have an object of that class, so instead of

$page->find($data['link'])->delete();

do

if ($pageToDelete = $page->find($data['link'])) {
    $pageToDelete->delete();
}

Also, destructive actions require an (impersonated) user.

I adapted my code with your suggestions. Also, the page I want to delete is not a child. So I changed my code to this:

if ($pageToDelete = $kirby->page($data['link'])) {
    $pagelink = $pageToDelete->delete();
}

I also tried:

if ($pageToDelete = $kirby->page()->find($data['link'])) {
    $pagelink = $pageToDelete->delete();
}

Both cases don’t return the page. The second case returns NULL. It is an unlisted page, does that make a difference?

None of this make sense, you cannot find a page anywhere in the page tree just by its slug. You have to either use the UUID or the complete path to the page.

E.g $site->find('photography/trees'))
Or page('photography/trees')
Or $kirby->page('photography/trees'))
Or $kirby->page('trees', page('photography'))

I thought that is what $link->uid() gives me. Thanks for pointing me in the right direction.