如何从视图中使用模型函数?- Laravel 5.4
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42357941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use model function from view ? - laravel 5.4
提问by Masum
i made a function into model class which is
我把一个函数变成了模型类
public function scopetest($query)
{
return $query->pluck('name');
}
}
and my controller code is
我的控制器代码是
public function index()
{
$books = Book::all();
return view('welcome',compact('books'));
}
to get the test() function result I wrote my view file
为了得到 test() 函数结果,我写了我的视图文件
@foreach($books as $book)
{{$book->test()}}
@endforeach
but problem is when i visit this page it will show 'name' field value 3 times. why it show 3 times? how to call model function from view? & what is the right process? kindly help please
但问题是当我访问此页面时,它会显示“名称”字段值 3 次。为什么显示3次?如何从视图中调用模型函数?& 正确的流程是什么?请帮助
回答by Sagar Arora
There are many ways to call a model function in the view.
有很多方法可以在视图中调用模型函数。
Method 1:
方法一:
Pass Some Modal to view in your controller like :
传递一些模态以在您的控制器中查看,例如:
$model = Model::find(1);
View::make('view')->withModel($model);
In modal create a some function:
在模态中创建一个函数:
public function someFunction() {
// do something
}
In view you can call this function directly as:
在视图中,您可以直接调用此函数:
{{$model->someFunction()}}
Method 2 or other way:
方法2或其他方式:
You can make a static function in the model like:
您可以在模型中创建一个静态函数,例如:
public static function someStaticFunction($par1, $par2) {
// do what you need
}
And in your view you can model function directly as:
在您看来,您可以直接将函数建模为:
{{App\Model::someStaticFunction($par1,$par2)}}
回答by Lucas Martins
The scope should be scopeTest()
(camelCase).
范围应该是scopeTest()
(camelCase)。