Laravel 5.8 Nova 2.0
In nova action
public function fields()
{
return [];
}
Is there any way to access currently selected rows here?
Laravel 5.8 Nova 2.0
In nova action
public function fields()
{
return [];
}
Is there any way to access currently selected rows here?
You can get current model instance from NovaRequest. And you may create NovaRequest from \Illuminate\Http\Request that is passed to the method:
use Laravel\Nova\Http\Requests\NovaRequest;
use Illuminate\Http\Request;
/**
* Get the fields displayed by the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function fields(Request $request)
{
// Model instance or null
$model = NovaRequest::createFrom($request)
->findModelQuery()
->first();
return [
// Your fields here
];
}
Don't know if anyone solved this but I got the same issue and found an article.
According to this article, you can create a public method setResource
in action class and when registering action in nova resource, set the current resource of each row: $action->setResource($this->resource)
. Then, in fields
method, you can add your logic with resource by using $this ->resource
.
A note for this method is $this->resource
can be null
or an null
model (a model class but no attribute). Thus, you must check the resource property if it is null
before adding any logic.
No, for two reasons:
1) fields
is called when the resource loads, not when the action dialog is displayed
2) The concept of "currently selected" really only exists on the client (browser) side
You can only access the selected rows in the handle
PHP method (i.e., after submit, you have $models
).
Sometimes when I'm on the details view and want to perform an action on that record, but also want the current records data in the fields (maybe for help text), I grab it from the URL.
//Get the URL
$explodeUrl = explode('/', strrev($_SERVER['HTTP_REFERER']), 2);
I run the action only on the detail page then get the single model data like so:
$model = DB::table('something')->where('id', request()->resourceId)->first();
Model::find(request()->resourceId)
. do not have Nova now, so can not confirm though. –
Alfieri You can define a handleRequest
function and retrieve the model that way. For instance
public function handleRequest(ActionRequest $request)
{
$this->model = $request->targetModel(); //I am setting a custom variable here.
parent::handleRequest($request);
}
You can then use the $this->model()
in your handle()
method.
Very useful for standalone actions.
© 2022 - 2025 — McMap. All rights reserved.