Skip to content

Instantly share code, notes, and snippets.

@DarkGhostHunter
Created July 7, 2022 06:38
Show Gist options
  • Save DarkGhostHunter/c4f2fa03009bd16570ebd1848e64ecb3 to your computer and use it in GitHub Desktop.
Save DarkGhostHunter/c4f2fa03009bd16570ebd1848e64ecb3 to your computer and use it in GitHub Desktop.
Inertia Controller for slimming controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Str;
use Inertia\Inertia;
use function is_array;
use function ucfirst;
abstract class InertiaController extends Controller
{
/**
* Execute an action on the controller and returns an Inertia response if it's an array.
*
* @param string $method
* @param array $parameters
* @return \Symfony\Component\HttpFoundation\Response|\Inertia\Response|mixed
*/
public function callAction($method, $parameters): mixed
{
$result = parent::callAction($method, $parameters);
// If the controller doesn't return an array, we will understand is not using an Inertia
// response, so we'll return it as it is. Otherwise, we will try to guess the component
// that should be rendered by the response using this class namespace and method name.
if (!is_array($result) || ! $result instanceof Arrayable) {
return $result;
}
// This normalizes the class name:
// - from: "App\Http\Controllers\ArticleController" or "App\Http\Controllers\Article\DraftController"
// - to: "Article" or "Article/Draft"
$component = Str::of(static::class)
->after('App\Http\Controllers\\')
->beforeLast('Controller')
->replace('\\', '/');
// If its an invokable class, we will understand the class basename is the component
// name. Otherwise, we will use the method name as the last child of the component
// path. So "ArticleController@create" will become "Article/Create" at the end.
if ($method !== '__invoke') {
$component->append('/' . ucfirst($method));
}
return Inertia::render($component, $result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment