Last active
September 7, 2020 16:41
-
-
Save feldsam/dc379db2db3bd1f865efbe35a66f9ada to your computer and use it in GitHub Desktop.
Laravel Nova Manuall Action Dispatch
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 | |
| use Illuminate\Database\Eloquent\Collection; | |
| use Laravel\Nova\Actions\DispatchAction; | |
| use Laravel\Nova\Http\Requests\ActionRequest; | |
| class ModelObserver | |
| { | |
| public function created(Model $model) | |
| { | |
| $collection = Collection::wrap($model); | |
| $action = new JobClass; | |
| $request = app(ActionRequest::class); | |
| $request->action = $request->query->set('action', $action->uriKey()); | |
| $fields = $request->resolveFields(); | |
| DispatchAction::forModels($request, $action, 'handle', $collection, $fields); | |
| } | |
| } | |
| // calling outside of Nova | |
| // https://laracasts.com/discuss/channels/nova/dispatching-nova-actions-manually | |
| // Please note that $user has to be Laravel Nova User with sufficient privileges to run the action. | |
| private function postToActionsApi($actionClass, $resource, $model, $params, $user) { | |
| Nova::resourcesIn(app_path('Nova')); | |
| $collection = Collection::wrap($model); | |
| $action = new $actionClass; | |
| $actionRequest = app(ActionRequest::class); | |
| $actionRequest->user = $user; | |
| $actionRequest->setUserResolver(function () use ($user) { | |
| return $user; | |
| }); | |
| $actionRequest = $actionRequest->replace($params); | |
| $actionRequest->route()->setParameter('resource', $resource); | |
| $actionRequest->route()->pathInfo = '/nova-api/'.$resource.'/action'; | |
| $actionRequest->action = $actionRequest->query->set('action', $action->uriKey()); | |
| $actionRequest->action = $actionRequest->query->set('pivotAction', 'false'); | |
| $fields = $actionRequest->resolveFields(); | |
| return DispatchAction::forModels($actionRequest, $action, 'handle', $collection, $fields); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment