Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 996
Prafulla Kumar Sahu Avatar asked Jul 04 '19 13:07

Prafulla Kumar Sahu


3 Answers

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
   ];
}
like image 68
Roman Khabibulin Avatar answered Nov 01 '22 14:11

Roman Khabibulin


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

like image 1
udog Avatar answered Nov 01 '22 15:11

udog


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);
like image 1
mcornille Avatar answered Nov 01 '22 14:11

mcornille