I'm trying to get a gate in Laravel 11 to show only the income for the particular user. I am not sure what condition to pass to the gate. I am using the example from Laravel docs for update, but this is still passing all the data to the vue page.
This is in AppServiceProvider.php:
public function boot(): void
{
Gate::define('view-income', function (User $user, Income $income) {
return $user->id === $income->user_id;
});
}
And this is FinancesController.php:
class FinancesController extends Controller
{
public function index(User $user, Income $income)
{
if(!Gate::allows('view-income', $income)) {
return inertia(
'Finances/FinancesMain',
[
'incomes' => Income::all(),
]
);
}
}
}
If I toggle between "!" and removing "!", it will either pass all the data or none of the data. I'm trying to get it only to pass data for a certain userid. I'm not sure what condition to pass to the gate. If I use
'incomes' => Income::all()->where('user_id', $id),
there's not much point in having a gate.
Any help would be appreciated.
It may be a misunderstanding about Gates.
In general, it's supposed to control who is allowed to access something.
Gates can be used to return data, but usually, the answer will be only a bool to define whether someone can access something.
The way to implement it will depend on your logic. let's imagine you have 2 levels of users: admin
and normal
, admin users can see all data but normal users can only see itself data. The code can be something like that:
if (Gate::allows('admin')) {
$data = Income::all();
} else {
$data = Income::all()->where('user_id', $id);
}
return inertia(
'Finances/FinancesMain',
[
'incomes' => $data,
]
);
PS.
As you're using ===
please ensure both data types are equal.