Dpower
Dpower

Reputation: 21

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

Upvotes: 0

Views: 1766

Answers (2)

Maninderpreet Singh
Maninderpreet Singh

Reputation: 2587

@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

Upvotes: 0

Demonyowh
Demonyowh

Reputation: 1672

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 ..

Upvotes: 3

Related Questions