Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 viewIs() below:

Text::make('Preview', function () {
    if($this->viewIs('index'){
        return \small_preview($this->image);
    }
    return \large_preview($this->image);
 })->asHtml(),
like image 251
Michael Pawlowsky Avatar asked Dec 10 '18 10:12

Michael Pawlowsky


1 Answers

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);
});
like image 144
Chin Leung Avatar answered Oct 10 '22 09:10

Chin Leung