如何在Laravel 5中调用控制器内的模型函数

Sri*_*Rao 8 php laravel-5

我一直面临着在新的laravel框架版本5中无法在控制器内使用模型的问题.我使用artisan命令"php artisan make:model Authentication"创建了模型. 创建了模型,并在app文件夹中成功创建了模型之后我在其中创建了一个小函数测试,我的模型代码看起来像这样.

 <?php namespace App;

 use Illuminate\Database\Eloquent\Model;

 class Authentication extends Model {

   protected $table="canteens";

   public function test(){
    echo "This is a test function";
   }

}
Run Code Online (Sandbox Code Playgroud)

现在我不知道,如何将模型的函数test()调用到我的控制器,任何帮助将不胜感激,提前谢谢.

小智 11

运行该函数并查看输出的快速而脏的方法是编辑app\Http\routes.php和添加:

use App\Authentication;

Route::get('authentication/test', function(){
    $auth = new Authentication();
    return $auth->test();
});
Run Code Online (Sandbox Code Playgroud)

然后访问您的网站并转到此路径: /authentication/test

Route :: get()的第一个参数设置路径,第二个参数说明调用该路径时要执行的操作.

如果你想进一步,我建议创建一个控制器并用控制器上的方法替换该匿名函数.在这种情况下,您可以app\Http\Routes.php改为添加:

Route::get('authentication/test', 'AuthenticationController@test');
Run Code Online (Sandbox Code Playgroud)

然后使用artisan制作一个控制器,AuthenticationController或者app\Http\Controllers\AuthenticationController.php像这样创建和编辑它:

<?php namespace App\Http\Controllers;

use App\Authentication;

class AuthenticationController extends Controller {
    public function test()
    {
        $auth = new Authentication();
        return $auth->test();
    }
}
Run Code Online (Sandbox Code Playgroud)

再次,您可以通过/authentication/testLaravel网站查看结果.


MKJ*_*MKJ 6

<?php namespace App;

 use Illuminate\Database\Eloquent\Model;

 class Authentication extends Model {

   protected $table="canteens";

   public function scopeTest(){
    echo "This is a test function";
   }

}
Run Code Online (Sandbox Code Playgroud)

只是前缀test()scope。这将成为scopeTest().

现在你可以从任何地方调用它,比如Authentication::Test().


小智 5

方法名称前的使用范围

<?php

namespace App\Models;
use Illuminate\Support\Facades\DB;

use Illuminate\Database\Eloquent\Model;

class Mainmenu extends Model
{

  public function scopeLeftmenu() {

    return DB::table('mainmenus')->where(['menu_type'=>'leftmenu', menu_publish'=>1])->orderBy('menu_sort', 'ASC')->get();
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码,我试图访问某些目的来调用左侧菜单的数据库

比我们可以在Controller中轻松调用它

<?php 

 Mainmenu::Leftmenu();
Run Code Online (Sandbox Code Playgroud)