Laravel+Vue项目创建Artisan时Auth::user()返回NULL问题求助
Let's break down why your user_id is being stored as NULL and how to fix it step by step:
1. You're Passing the User Object Instead of the ID
Looking at your code:
$artisan = Artisan::create($request->all() + ['user_id' => Auth::user()]);
Auth::user() returns the entire User model object, not just the numeric id that your user_id database column expects. You need to explicitly grab the user's ID:
Corrected Code:
public function store(Request $request) { // Option 1: Get ID from the user object $artisan = Artisan::create($request->all() + ['user_id' => Auth::user()->id]); // OR Option 2: Shorthand for getting the authenticated user's ID // $artisan = Artisan::create($request->all() + ['user_id' => Auth::id()]); return $artisan; }
2. Your Route Isn't Protected by the Authentication Middleware
If your store route isn't using the auth middleware, Laravel has no way of knowing which user is authenticated—so Auth::user() will return NULL.
Check your routes file (either routes/web.php or routes/api.php) and make sure the route is wrapped with the auth middleware:
// For web routes Route::post('/artisans', [ArtisanController::class, 'store'])->middleware('auth'); // For API routes (if using Sanctum/Passport) Route::post('/artisans', [ArtisanController::class, 'store'])->middleware('auth:sanctum');
3. API Requests Are Missing Authentication Credentials
If this is an API endpoint called from your Vue frontend, you need to send the user's authentication token with the request:
- In Vue, make sure you're including the
Authorizationheader with the Bearer token (usually stored in local storage after login):
axios.post('/api/artisans', formData, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } })
4. You're Using the Wrong Authentication Guard
If your app uses multiple guards (e.g., web for regular users and api for API users), double-check that you're using the correct guard to fetch the user:
// If using the API guard $userId = Auth::guard('api')->user()->id;
内容的提问来源于stack exchange,提问作者Chime Emmanuel

