Passing data from view to controller in Laravel 5.1

时间:2016-11-26 18:34:13

标签: php laravel parameter-passing laravel-5.1 blade

i want to pass arguments from a blade view to a function in the controller

index.blade.php

<a href="{{ route('like', [$post->id, 1])  ) }}" class="like">
    Like
</a>

<a href="{{ route('like', [$post->id, -1])  ) }}" class="like">
    Dislike
</a>

PostController.php

  public function getLikePost($post_id, $like_value)
    {
       $post = Post::find($post_id);
       ...
    }

routes.php

Route::get('like', [
        'uses' => 'PostController@getLikePost',
        'as'   => 'like'
      ]);

but i get an error message

ErrorException in PostController.php line 149:
Missing argument 2 for App\Http\Controllers\PostController::getLikePost()

could anyone help me with this issue?

3 个答案:

答案 0 :(得分:1)

Your route should be as:

Route::get('like/{psot_id}/{like_value}', [
        'uses' => 'PostController@getLikePost',
        'as'   => 'like'

And in your view:

<a href="{{ route('like', ['post_id' => $post->id, 'like_value' => 1]) }}" class="like">
    Like
</a>

<a href="{{ route('like', ['post_id' => $post->id, 'like_value' => -1]) }}" class="like">
    Dislike
</a>

答案 1 :(得分:0)

Try this:

Route.php

Route::get('like/{post_id}/{like_value}', [
        'uses' => 'PostController@getLikePost',
        'as'   => 'like'
      ]);

index.blade.php

<a href="{{ route('like', ['post_id' => $post->id, 'like_value' => 1]) }}" class="like">
    Like
</a>

<a href="{{ route('like', ['post_id' => $post->id, 'like_value' => -1]) }}" class="like">
    Dislike
</a>

Docs

答案 2 :(得分:0)

Initialize $post_id and $like_value by empty value as like below.

PostController.php

public function getLikePost($post_id = '', $like_value='')
    {
       $post = Post::find($post_id);
       ...
    }