Im trying to make a gate so only some users are authorized to make certain api calls, but before that I have to atleast set up a gate properly which i cant seem to do.
Here I Set up the Gate
AppServiceProvider.php
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Gate::define('alwaysTrue', function () {
return true;
});
}
}
Here is the controller where I use the gate
public function materiales_pedido($pedido_id)
{
if (! Gate::allows('alwaysTrue')) {
return response()->json(['message' => 'Unauthorized'], 401);
}
$results = [];
return $results;
}
The actual function of the controller is longer but I think its irrelevant as its just some sql queries and it works when I remove the gate part
Here is my api.php route
Route::get('/materiales_pedido/{pedido_id}', [PedidosConsultas::class, 'materiales_pedido']);
Im using sanctum SPA session bassed authentication for my web app.
Even if I add ->middleware(‘auth:sanctum’); to the route the error continues
This is my axios call
const fetchMateriales = async () => {
try {
await axios.get('/sanctum/csrf-cookie');
console.log(pedidoId);
const response = await axios.get(`http://127.0.0.1:8000/api/materiales_pedido/${pedidoId}`, {
headers: {
'content-type': 'application/json'
}
});
piezas.value = response.data;
piezas.value.forEach(pieza => {
pieza.cantidad_state = 'max';
});
console.log(piezas.value);
} catch (error) {
console.error('There was an error fetching the materialesPedidos:', error);
}
};
This is my logging in authentication function
public function authenticate(Request $request){
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::attempt($credentials)) {
$user = auth()->user();
$emailVerified = !is_null($user->email_verified_at);
$request->session()->regenerate();
return response()->json([
'success' => true,
'email_verified' => $emailVerified,
],200); }
return response()->json([
'message' => 'The provided credentials do not match our records.',
], 401);
}
Not really sure what it could be I also tried deleting all caches and chatgpt didnt help much with this. I havent changed any middleware that comes with laravel 11 and cant even see them because they are hidden now in Larav11.
–IMPORTANT —
When I change the route from api.php to web.php It works IF i access that web.php route DIRECTLY trough my browser but if i acces that web.php route TROUGH AXIOS I still get the same 401 error.
But im not that experienced to know what would cause this as im a student trying to learn fullstack.
I would very much appreaciate your help
I tried chaning the route from api.php to web.php but it gives mixed results depending if i access it directly or trough axios.
Juan Moreno is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.