Laravel Nova - How to determine the view (index, detail, form) you are in for a resource's computed field?

后端 未结 5 698
野的像风
野的像风 2021-01-19 07:21

I would like to return a different result for a computed field when viewing the index view than when viewing the detail view of a resource.

Basically something like

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 08:05

    You can check the class of the request:

    Text::make('Preview', function () use ($request) {
        if ($request instanceof \Laravel\Nova\Http\Requests\ResourceDetailRequest) {
            return \large_preview($this->image);
        }
    
        return \small_preview($this->image);
    });
    

    Otherwise, you can create your own viewIs function:

    // app/Nova/Resource.php
    
    /**
     * Check the current view.
     *
     * @param  string  $view
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @retrun bool
     */
    public function viewIs($view, $request)
    {
        $class = '\Laravel\Nova\Http\Requests\\Resource'.ucfirst($view).'Request';
    
        return $request instanceof $class;
    }
    

    Then you can do it like this:

    Text::make('Preview', function () use ($request) {
        if ($this->viewIs('detail', $request) {
            return \large_preview($this->image);
        }
    
        return \small_preview($this->image);
    });
    

提交回复
热议问题