Câu hỏi phỏng vấn Laravel
Câu hỏi

Where can you inject authentic...

Câu trả lời

In Laravel, authentication checks on an API request can be injected at several points to ensure that only authenticated users can access certain routes or perform specific actions. Here are the primary methods to inject authentication checks:

1. Middleware

Middleware is the most common way to handle authentication in Laravel. You can attach middleware to your routes to ensure that only authenticated users can access them. For example, using the auth:api middleware:

php Copy
Route::middleware('auth:api')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
});

This middleware will check if the user is authenticated before allowing access to the routes within the group[1][3][5].

2. Controller Methods

You can also perform authentication checks directly within your controller methods using the Auth facade. For example:

php Copy
use Illuminate\Support\Facades\Auth;

public function index() {
    if (Auth::check()) {
        $user = Auth::user();
        return $user->products;
    } else {
        return response()->json(['message' => 'Unauthenticated.'], 401);
    }
}

This method checks if the user is authenticated before proceeding with the logic in the controller[4][5].

3. Request Validation

Laravel allows you to create custom request classes that can include authorization logic. For example, you can create a request class and override the authorize method to include your authentication logic:

php Copy
use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest {
    public function authorize() {
        return Auth::check();
    }

    public function rules() {
        return [
            'title' => 'required|string|max:255',
            'body' => 'required|string',
        ];
    }
}

You can then inject t...

senior

senior

Gợi ý câu hỏi phỏng vấn

middle

How do you mock a static facade methods?

senior

What is Autoloader in PHP?

junior

What is the purpose of the Eloquent cursor() method in Laravel ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào