类型错误:参数2传递给控制器:: show()必须是模态,字符串的实例



将投票函数添加到分类页面。使用Laravel和Vue。

我遇到的错误是:

(1/1)致命性 类型错误:参数2传递给Hustla http Controllers ListingVoteController :: show()必须是Hustla listing的实例,字符串给定

我包括VUE文件,投票控制器,清单模型和路线。我希望有人可以帮助我。

列表模型

 public function votesAllowed()
 {
     return (bool) $this->allow_votes;
 }
 public function commentsAllowed()
 {
     return (bool) $this->allow_comments;
 }
 public function votes()
 {
  return $this->morphMany(Vote::class, 'voteable');
 }
 public function upVotes()
 {
     return $this->votes()->where('type', 'up');
 }
 public function downVotes()
 {
     return $this->votes()->where('type', 'down');
 }
 public function voteFromUser(User $user)
 {
     return $this->votes()->where('user_id', $user->id);
 }

投票控制器

  public function show(Request $request, Listing $listing)
  {
    $response = [
        'up' => null,
        'down' => null,
        'can_vote' => $listing->votesAllowed(),
        'user_vote' => null,
    ];
    if ($listing->votesAllowed()) {
        $response['up'] = $listing->upVotes()->count();
        $response['down'] = $listing->downVotes()->count();
    }

    if ($request->user()) {
        $voteFromUser = $listing->voteFromUser($request->user())->first();
        $response['user_vote'] = $voteFromUser ? $voteFromUser->type : null;
    }
    return response()->json([
        'data' => $response
    ], 200);
}

投票

<template>
<div class="listing__voting">
    <a href="#" class="listing__voting-button">
        <span class="glyphicon glyphicon-thumbs-up"></span>
    </a> 1 &nbsp;
    <a href="#" class="listing__voting-button">
        <span class="glyphicon glyphicon-thumbs-down"></span>
    </a> 2 
</div>
</template>
<script>
    export default {
    data () {
        return {
            up: null,
            down: null,
            userVote: null,
            canVote: false
        }
    },
    props:{
        listingId: null
    }
}
</script>

路由

Route::get('/{location}/{listing}/votes',[
'uses' => 'HustlaHttpControllersListingVoteController@show'
]);

您的路由定义定义了两个参数:{location}{listing}。参数按定义的顺序传递给控制器方法。

但是,您的控制器方法仅被定义为接受一个路由参数。第一个路由参数将传递给该方法,在此路由定义中,即{location}参数。由于{location}$listing不匹配,因此字符串值将通过,您将收到您看到的错误。

您需要将第二个路由参数添加到控制器操作中:

public function show(Request $request, $location, Listing $listing)
{
    // code
}

如果$location也是一个模型,您可以继续添加类型提示以启用隐式路由模型绑定。

最新更新