类型错误:传递给Controller :: show()的参数2必须是modal的实例,给定字符串

问题描述 投票:1回答:1

将上下投票功能添加到分类页面。使用Laravel和Vue。

我得到的错误是:

(1/1)FatalThrowableError类型错误:参数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);
}

votingViewed

<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' => '\Hustla\Http\Controllers\ListingVoteController@show'
]);
php laravel vue.js
1个回答
3
投票

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.