在 Laravel 中从控制器调用模型函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21044730/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:51:22  来源:igfitidea点击:

Calling Model Function From Controller in Laravel

phpmysqllaravellaravel-4

提问by Selda Vural

I'm new on laravel.

我是 Laravel 的新手。

I have functions on my model php. I want to use them in controller and send to view.

我的模型 php 上有函数。我想在控制器中使用它们并发送查看。

This is my example function.

这是我的示例函数。

public function select()
    {
        $users = DB::table('garanti')->get();
    }

now I need to use this on controller and view.

现在我需要在控制器和视图上使用它。

In codeigniter I handle it like this:

在 codeigniter 中,我是这样处理的:

$data['kategori'] = $this->model->select_s();        
$this->load->view('admin/kategori', $data);

回答by Antonio Carlos Ribeiro

If you do

如果你这样做

class Post extends Eloquent {

    public function select()
    {
       return DB::table('garanti')->get();
    }

}

You can use it in your controller:

您可以在控制器中使用它:

$data['kategori'] = with(new Post)->select();        

return View::make('admin/kategori')->with('data', $data);

There are in fact other ways of doing this, but static functions are not really testable, so I wouldn't use them in this case.

实际上还有其他方法可以做到这一点,但静态函数并不是真正可测试的,所以在这种情况下我不会使用它们。

回答by Osama Al-Banna

This is a very good LIVE example about using MVC concept in Laravel. in this scenario the Controller is calling a function from the Model class then the Controller handle the view.Take a look.

这是一个关于在 Laravel 中使用 MVC 概念的非常好的现场示例。在这种情况下,控制器从模型类调用一个函数,然后控制器处理视图。看一看。

http://runnable.com/UnFiFHVGrQh1AAA_/mvc-in-laravel-for-php

http://runnable.com/UnFiFHVGrQh1AAA_/mvc-in-laravel-for-php