Laravel Nova - 如何确定资源计算字段所在的视图(索引、详细信息、表单)?

Mic*_*sky 6 computed-field laravel-nova

我希望在查看索引视图时与查看资源的详细视图时返回不同的计算字段结果。

基本上类似于下面的 viewIs() :

Text::make('Preview', function () {
    if($this->viewIs('index'){
        return \small_preview($this->image);
    }
    return \large_preview($this->image);
 })->asHtml(),
Run Code Online (Sandbox Code Playgroud)

Chi*_*ung 9

您可以检查请求的类别:

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

    return \small_preview($this->image);
});
Run Code Online (Sandbox Code Playgroud)

否则,您可以创建自己的 viewIs 函数:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

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

    return \small_preview($this->image);
});
Run Code Online (Sandbox Code Playgroud)


Dar*_*yev 5

不幸的是,@Chin 的答案对我不起作用,因为对于编辑视图,请求类只是一个基本Laravel\Nova\Http\Request类。

我检查这是否是索引视图的解决方法如下:

/**
 * Check if the current view is an index view.
 *
 * @param  \Laravel\Nova\Http\Requests\NovaRequest $request
 * @return bool
 */
public function isIndex($request)
{
    return $request->resourceId === null;
}
Run Code Online (Sandbox Code Playgroud)


Sau*_*nam 0

您可以为索引和详细信息页面创建两个单独的字段。

// ----- For Index page
Text::make('Preview', function () {
    return \small_preview($this->image);
})
->onlyOnIndex()
->asHtml(),

// ----- For Detail page
Text::make('Preview', function () {
    return \large_preview($this->image);
})
->onlyOnDetail()
->asHtml(),
Run Code Online (Sandbox Code Playgroud)