'laravel controller function parameters

I'm trying to call a function inside one of my controller from the action() helper function. I need to pass a paramter to my function.

Here is the funciton I'm trying to call :

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

Here is the way I call it :

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

The function is always running with the default value, even if I put anything else in my call. From what I can see in my address bar, the paramter seems to be sent along with the call :

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

From the little I know, it seems correct to me, but since it doesn't work, I must come to the evidence that it isn't. What would be the cleanest way to call my function with the right parameter?



Solution 1:[1]

The reason why it's not working is because query strings aren't passed as arguments to your controller method. Instead, you need to grab them from the request like this:

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

Extra tidbit: Because Laravel uses magic methods, you can actually grab the query parameter by just doing $request->clef.

Solution 2:[2]

Laravel URL Parameters

I think assigning parameters need not be in key value pair. I got it to work without names.

If your route is like /post/{param} you can pass parameter as shown below. Your URL will replace as /post/100

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

For multiple parameters say /post/{param1}/attachment/{param2} parameter can be passed as shown below. Similarly your url will be replaced as /post/100/attachment/10

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

Here show is a method in PostsController

In PostsController

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

In View

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

In Routes

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

URL Should be: http://www.example.com/post/100/attachment/10

Hope this is helpful.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thomas Kim
Solution 2