DEV Community 👩‍💻👨‍💻

Morcos Gad
Morcos Gad

Posted on • Updated on

If-Else or Switch or Match - Laravel

We have an example of entering data of different type and here we use if

if($request->type == 'users'){
   $users = User::all();
   dd($users)
}
if($request->type == 'projects'){
   $projects = Project::all();
   dd($projects)
}
Enter fullscreen mode Exit fullscreen mode

But we want to make the code easier and less, so here I want to use switch

switch ($request->type) {
  case 'users': $model = 'App\\Models\\User'; break;
  case 'projects': $model = 'App\\Models\\Project'; break;
}
$records = $model::all();
dd($records)
Enter fullscreen mode Exit fullscreen mode

But I want to covet more powerful code using php8 so I will use match

$model = match($request->type){
  'users' => 'App\\Models\\User',
  'projects' => 'App\\Models\\Project',
}
$records = $model::all();
dd($records)
Enter fullscreen mode Exit fullscreen mode

Source :- https://www.youtube.com/watch?v=sTm5P4IGD5g
Source :- https://stitcher.io/blog/php-8-match-or-switch
I hope you enjoyed the code.

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠