You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel+Vue项目创建Artisan时Auth::user()返回NULL问题求助

Fixing NULL user_id When Creating an Artisan in Laravel/Vue

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 Authorization header 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:45:37