【问题标题】:laravel controller function parameterslaravel 控制器功能参数
【发布时间】:2016-02-04 09:50:07
【问题描述】:

我正在尝试从 action() 辅助函数调用我的一个控制器内部的一个函数。我需要将一个参数传递给我的函数。

这是我要调用的函数:

public function my_function($clef = 'title')
{   
    $songs = Song::orderBy($clef)->get();
    return View::make('my_view', compact('songs'));
}

这是我的称呼:

<a href="{{ action('MyController@My_View', ['clef' => 'author']) }}">Author</a>

该函数始终以默认值运行,即使我在调用中添加了任何其他内容。从我在地址栏中看到的内容来看,该参数似乎与呼叫一起发送:

http://www.example.com/my_view?clef=author

据我所知,这对我来说似乎是正确的,但既然它不起作用,我必须找到它不是的证据。用正确的参数调用我的函数的最干净的方法是什么?

【问题讨论】:

  • 你确定使用MyController@My_View吗?看起来应该是MyController@my_function

标签: php laravel laravel-4


【解决方案1】:

Laravel 网址参数

我认为分配参数不必在键值对中。我让它在没有名字的情况下工作。

如果您的路线类似于/post/{param},您可以传递如下所示的参数。您的网址将替换为 /post/100

URL::action('PostsController@show', ['100'])

对于多个参数说/post/{param1}/attachment/{param2}参数可以如下所示传递。同样,您的网址将被替换为/post/100/attachment/10

URL::action('PostsController@show', ['100', '10'])

这里showPostsController

中的一个方法

在 PostsController 中

public function show($param1 = false, $param2 = false)
{   
    $returnData = Post::where(['column1' => $param1, 'column2' => $param2 ])->get();
    return View::make('posts.show', compact('returnData'));
}

可见

<a href="{{ action('PostsController@show', ['100', '10']) }}">Read More</a>

在路线中

Route::get('/post/{param1}/attachment/{param2}', [ 'as' => 'show', 'uses' => 'PostsController@show' ] );

网址应该是:http://www.example.com/post/100/attachment/10

希望这有帮助。

【讨论】:

    【解决方案2】:

    它不起作用的原因是查询字符串没有作为参数传递给您的控制器方法。相反,您需要像这样从请求中获取它们:

    public function my_function(Request $request)
    {   
        $songs = Song::orderBy($request->query('clef'))->get();
        return View::make('my_view', compact('songs'));
    }
    

    额外花絮:因为 Laravel 使用魔术方法,你实际上可以通过 $request-&gt;clef 获取查询参数。

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 2014-02-02
      • 1970-01-01
      • 2018-01-15
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      相关资源
      最近更新 更多