Created
July 7, 2022 06:38
-
-
Save DarkGhostHunter/c4f2fa03009bd16570ebd1848e64ecb3 to your computer and use it in GitHub Desktop.
Inertia Controller for slimming controller code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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