Laravel function that can handle a request or strings

Viewed 56

I have a function:

public static function linkClient(Request $request){

//do things
}

This function is called by 2 different things. 1 is a post request with post data. In that case, this works fine:

public static function linkClient(Request $request){
   $data = $request->all();
    // do things with data
}

The second call to this function passes 2 strings. how can i make it so this function can handle either the Request or the strings?

In laymen's terms I would write:

 public static function linkClient(Request $request or $string1,$string2){
   if ($request){
      $data = $request->all();
      //do things to request
   }
   if($string1 or $string2){
     //do string things
   }
 }
3 Answers

What you are looking for is function overloading, which php does not support. You can try to hack it together using a something like this:

https://stackoverflow.com/a/4697712/3150636

Where you detect the arguments passed in using func_num_args and branch from there.

Since PHP 8.0 there has been support for Union types in PHP:

 public static function linkClient(Request|string $request, $string2){
   if ($request instanceof Request){
      $data = $request->all();
      //do things to request
   } else {
     //do string things to $request
   }
 }

The downside is that there's no built-in mechanism to ensure that you either call the function with a single Request parameter or two string parameters as the check is only on the first parameter.

Related