簡體   English   中英

我想在同一控制器的不同函數中傳遞變量-Laravel

[英]I want to pass variable in different function from same controller - Laravel

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!'];
}

我收到此錯誤:

傳遞給App \\ Http \\ Controllers \\ ChatsController :: sendMessage()的參數1必須是Illuminate \\ Http \\ Request的實例,給定整數,在C:\\ xampp \\ htdocs \\ ScrimWithMe \\ app \\ Http \\ Controllers \\ ChatsController.php中調用在第77行並定義

你有兩個sendMessage函數需要的參數..但是你只是傳遞了一個參數..

您可以做的是在chat功能chat中添加另一個參數,例如

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

然后在所述函數中添加一個參數,應該這樣做..

@Demonyowh解釋所有為什么出現此錯誤的原因

我認為這是工廠設計模式,有兩種方法可以解決您的問題

  • 如果您的方法未在其他任何地方使用,則刪除第一個參數並在下一行聲明類

     METHOD(){ $request = new Request(); // your code; } 
  • 在__construct方法中聲明此類參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM