简体   繁体   中英

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

I get this error :

Argument 1 passed to App\\Http\\Controllers\\ChatsController::sendMessage() must be an instance of Illuminate\\Http\\Request, integer given, called in C:\\xampp\\htdocs\\ScrimWithMe\\app\\Http\\Controllers\\ChatsController.php on line 77 and defined

you have two parameters needed for the sendMessage function .. but you're just passing one parameter ..

what you can do is add another parameter in your chat function chat like

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

then add a parameter in said function and that should do it ..

@Demonyowh explain all that why you get this error

I think it's factory design pattern there are two ways to solve your problem

  • If your method not used on any other place then remove first parameter and declare class on next line

     METHOD(){ $request = new Request(); // your code; } 
  • Declare this class parameter in your __construct method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM