Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save calebporzio/58777177fd9a59fd29666b9105e1a218 to your computer and use it in GitHub Desktop.
Save calebporzio/58777177fd9a59fd29666b9105e1a218 to your computer and use it in GitHub Desktop.
Laracasts: Refactoring To Lookup Tables
<?php
/**
* Refactor #1:
*/
// Before
if ($user->type === 'admin' || $user->type === 'mod' || $user->type === 'author') {
// Do something.
}
// After
if (collect(['admin', 'mod', 'author'])->contains($user->type)) {
// Do something.
}
/**
* Refactor #2:
*/
// Before
public function update(User $user)
{
if ($user->type === 'admin') {
return redirect('/admin');
} elseif ($user->type === 'mod') {
return redirect('/company');
} elseif ($user->type === 'author') {
return redirect('/home');
}
}
// After
public function update(User $user)
{
$destinations = [
'admin' => '/admin',
'mod' => '/company',
'author' => '/home',
];
return redirect($destinations[$user->type]);
}
/**
* Refactor #3
*/
// Route
Route::get('/', function () {
$amounts = range(1000, 10000, 500);
$prices = array_map(function ($amount) {
return auth()->user()->calulateLoanPrices($amount);
}, $amounts);
return view('loan-price', [
'loanPricesByAmount' => array_combine($amounts, $prices),
]);
});
// View ?>
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { display: flex; justify-content: center; padding-top: 3rem; }
div { width: 25%; }
input { width: 100%; }
h1 { font-size: 1.875rem !important; }
</style>
<!-- Tailwind -->
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
<!-- Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="range" min="1000" max="10000" step="500" v-model="amount">
<h1>Amount: <strong>$XXXX</strong></h1>
<h1>Price: <strong>$XXXX</strong></h1>
</div>
<script>
new Vue({
data: {
amount: 1000,
loanPricesByAmount: @json($loanPricesByAmount)
},
computed: {
price() {
return this.loanPricesByAmount[this.amount]
}
}
}).$mount('#app')
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment