【问题标题】:laravel 5.5: how can I call route in controller?laravel 5.5:如何在控制器中调用路由?
【发布时间】:2018-03-16 04:55:25
【问题描述】:

在 web.php 中,我有这条路线可以打开一个表单:

$this->namespace('Users')->prefix('users')->group(function (){
    $this->get('/create' , 'UserController@create');
});

这条路线会返回一系列国家/地区。我使用该数组通过表单中的 ajax 填充选择框。

Route::namespace('API')->prefix('api')->group(function () {
    $this->get('/get-country-list', 'LocationsController@index');
});

控制器:

应用\Http\Controllers\API\LocationsController

class LocationsController extends Controller
{
  public function index()
  {
      return DB::table('countries')->pluck("name","id")->all();
  }
  ...

app\Http\Controllers\Users\UserController

class UserController extends Controller
{
    public function create()
    {
        return view('panel.users.home.create.show');
    }
    ...

如何在create() 函数中调用LocationsController@index? 最好的方法是什么?

【问题讨论】:

  • 为什么不使用模型呢?

标签: php laravel laravel-5 eloquent laravel-5.5


【解决方案1】:

您可以在操作中尝试return redirect(route('...')); 而不是return view()

更新

因为您只想获取国家列表而不是重定向。所以做小调,把data manipulating functionaction function分开:

protected function getCountries() {
   return DB::table('countries')->pluck("name","id")->all();
}

function index(Request $request) {
  return $this->getCountries();
}

function create(Request $request) {
  $countries = $this->getCountries();
  return view('panel.users.home.create.show', compact('countries'));
}

【讨论】:

  • 那我怎样才能返回panel.users.home.create.show?我想要这样的东西: return view('panel.users.home.create.show' , compact('counteris'));
  • 哦,您实际上想获取国家/地区列表。因此,让我们将数据操作函数与action function 分开,然后在任何action function 中重复使用它
【解决方案2】:

我认为你应该尝试不同的方法。您似乎想要做的是重用这个繁琐的查询:

DB::table('countries')->pluck('name', 'id')->all();

这很好!但是,您的 index() 函数是一个控制器端点,它返回一个响应,并不适合在其他控制器端点中重用。当我处于类似情况时,我通常会做两件事中的一件,

1。将代码提取到受保护的方法并在两个控制器端点方法中使用它

class UserController extends Controller
{
    public function index()
    {
        return $this->countryNames();
    }

    public function create()
    {
        // $countryNames = $this->countryNames():

        return view('panel.users.home.create.show');
    }

    public function countryNames()
    {
        return DB::table('countries')->pluck('name', 'id')->all();
    }
}

2。在模型上创建一个方法,在您的情况下,这将涉及使用模型而不是 DB 外观。

class UserController extends Controller
{
    public function index()
    {
        return Country::names();
    }

    public function create()
    {
        // $countryNames = Country::names();

        return view('panel.users.home.create.show');
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-12
    • 2017-02-10
    • 2013-11-15
    • 2018-12-18
    • 2019-09-09
    • 2018-08-05
    • 2015-10-02
    • 2018-06-10
    相关资源
    最近更新 更多