gpt4 book ai didi

php - 如何从 View 中使用模型函数? - 拉维尔 5.4

转载 作者:可可西里 更新时间:2023-11-01 13:49:11 25 4
gpt4 key购买 nike

我在模型类中做了一个函数,它是

public function scopetest($query)
{
return $query->pluck('name');
}
}

我的 Controller 代码是

 public function index()
{
$books = Book::all();

return view('welcome',compact('books'));

}

为了获得 test() 函数的结果,我编写了我的 View 文件

@foreach($books as $book)

{{$book->test()}}

@endforeach

但问题是,当我访问此页面时,它会显示“名称”字段值 3 次。为什么显示3次?如何从 View 中调用模型函数?什么是正确的流程?请帮忙view result

最佳答案

有很多方法可以在 View 中调用模型函数。

方法一:

传递一些模态以在您的 Controller 中查看,例如:

$model = Model::find(1);
View::make('view')->withModel($model);

在模态中创建一些函数:

  public function someFunction() {
// do something
}

在 View 中你可以直接调用这个函数:

{{$model->someFunction()}}

方法二或其他方式:

您可以在模型中创建一个静态函数,例如:

public static function someStaticFunction($par1, $par2) {
// do what you need
}

在您看来,您可以直接将函数建模为:

{{App\Model::someStaticFunction($par1,$par2)}}

关于php - 如何从 View 中使用模型函数? - 拉维尔 5.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42357941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com