Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9703

Laravel nova action - get current model instance on fields()

Laravel 5.8 Nova 2.0

In nova action

public function fields()
{
    return [];
}

Is there any way to access currently selected rows here?

Upvotes: 7

Views: 8031

Answers (6)

simpsons3
simpsons3

Reputation: 991

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.

Upvotes: 3

prog_24
prog_24

Reputation: 799

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.

Upvotes: 0

Humphrey Mukwenga
Humphrey Mukwenga

Reputation: 11

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();

Upvotes: 1

SirPeace
SirPeace

Reputation: 109

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
   ];
}

Upvotes: 6

mcornille
mcornille

Reputation: 405

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);

Upvotes: 1

udog
udog

Reputation: 1536

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).

Upvotes: 1

Related Questions