Replace DIY 403 code in SpendingsController with SpendingPolicy
MODIFY
app/Http/Controllers/SpendingsController.php
app/Http/Controllers/SpendingsController.php
@@ -35,20 +35,14 @@ class SpendingsController extends Controller {
return redirect()->route('dashboard');
}
- public function show($id) {
+ public function show(Spending $spending) {
$user = Auth::user();
$currency = $user->currency;
- $spending = Spending::find($id);
-
- if ($spending->user_id === $user->id) {
return view('spendings.show', compact('currency', 'spending'));
}
- return view('errors.404');
- }
-
public function destroy($id) {
$spending = Spending::find($id);

ADD
app/Policies/SpendingPolicy.php
+<?php
+
+namespace App\Policies;
+
+use App\User;
+use App\Spending;
+
+class SpendingPolicy {
+ public function view(User $user, Spending $spending) {
+ return $user->id === $spending->user_id;
+ }
+}

MODIFY
app/Providers/AuthServiceProvider.php
app/Providers/AuthServiceProvider.php
@@ -14,7 +14,8 @@ class AuthServiceProvider extends ServiceProvider
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
- 'App\Earning' => 'App\Policies\EarningPolicy'
+ 'App\Earning' => 'App\Policies\EarningPolicy',
+ 'App\Spending' => 'App\Policies\SpendingPolicy'
];
/**

MODIFY
routes/web.php
routes/web.php
@@ -19,7 +19,7 @@ Route::group(['middleware' => ['auth']], function () {
Route::get('/spendings/create', 'SpendingsController@create')->name('spendings.create');
Route::post('/spendings', 'SpendingsController@store');
- Route::get('/spendings/{id}', 'SpendingsController@show')->name('spendings.show');
+ Route::get('/spendings/{spending}', 'SpendingsController@show')->name('spendings.show')->middleware('can:view,spending');
Route::delete('/spendings/{id}', 'SpendingsController@destroy')->name('spendings.destroy');
Route::get('/budgets/create', 'BudgetsController@create')->name('budgets.create');

Replace DIY 403 code in SpendingsController with SpendingPolicy