从视图如何使用模型功能? -laravel 5.4 [英] how to use model function from view ? - laravel 5.4

查看:67
本文介绍了从视图如何使用模型功能? -laravel 5.4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i made a function into model class which is

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

我的控制器代码是

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

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

       }

要获取我编写的视图文件的test()函数结果

to get the test() function result I wrote my view file

@foreach($books as $book)

 {{$book->test()}}

@endforeach

但是问题是,当我访问此页面时,它将显示名称"字段值3次.为什么显示3次?如何从视图调用模型函数? &正确的过程是什么?请帮助

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

推荐答案

有很多方法可以在视图中调用模型函数.

There are many ways to call a model function in the view.

方法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()}}

方法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)}}

这篇关于从视图如何使用模型功能? -laravel 5.4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆