【问题标题】:I want to pass variable in different function from same controller - Laravel我想从同一个控制器传递不同函数中的变量 - Laravel
【发布时间】:2017-10-19 00:08:03
【问题描述】:
public function chat($id,$team1,$team2){

    $relation=Crelation::where('match_id',$id)->where('first_team_id',$team1)->where('second_team_id',$team2)->first();

    if($relation == null){

        $data=[
            'match_id'=>$id,
            'first_team_id'=>$team1,
            'second_team_id'=>$team2
        ];

        $rel=  Crelation::create($data);
       $whatRelation=$rel->id;
        $this->sendMessage($whatRelation);

    }else{

    $whatRelation=$relation->id;
        $this->sendMessage($whatRelation);
    }

    return view('chat',compact('whatRelation'));
}


public function sendMessage(Request $request,$whatRelation)
{

    $id=(int)$whatRelation;

$user = Auth::user();

$message = $user->messages()->create([
    'message' => $request->input('message'),
    'crelation_id'=>$id


]);

broadcast(new MessageSent($user, $message))->toOthers();

return ['status' => 'Message Sent!'];
}

我收到此错误:

参数 1 传递给 App\Http\Controllers\ChatsController::sendMessage() 必须是 Illuminate\Http\Request 的实例,给定整数,调用 C:\xampp\htdocs\ScrimWithMe\app\Http\Controllers\ChatsController.php 在第 77 行并定义

【问题讨论】:

  • public function sendMessage(Request $request,$whatRelation) 您正在为第一个参数传递整数,它应该是一个请求。
  • 嗯,你能解释一下我需要改变什么吗?我不明白......
  • 您只传递单个参数 $this->sendMessage($whatRelation);
  • 这样传递 $this->sendMessage(Request $request,$whatRelation);
  • 这样传递 $this->sendMessage(Request $request,$whatRelation);并像这样访问公共函数 sendMessage($request,$whatRelation)

标签: php laravel


【解决方案1】:

sendMessage 函数需要两个参数.. 但您只传递了一个参数..

您可以在chat 函数聊天中添加另一个参数,例如

public function chat(Request $request, $id,$team1,$team2){
    ....
    $this->sendMessage($request,$whatRelation);
}

然后在所述函数中添加一个参数,这应该可以做到..

【讨论】:

    【解决方案2】:

    @Demonyowh 解释为什么你会得到这个错误

    我认为是factory design 模式有两种方法可以解决您的问题

    • 如果您的方法没有在任何其他地方使用,则删除第一个参数并在下一行声明类

      METHOD(){
        $request = new Request();
        // your code;
      }
      
    • 在您的 __construct 方法中声明此类参数

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多