我是新手学习laravel,我正在尝试上传图片,但我还需要上传图片的用户。 这是我的照片表
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->unsignedinteger('user_id')->index();
$table->string('title');
$table->string('image');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('photos');
}
这是我的照片模型:
protected $fillable = [
'user_id','title','image'
];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
这是我的控制者:
public function upload(Request $request)// store the image
{
$user=Auth::user()->id;
$this->validate($request, [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $input['image']);
$input['title'] = $request->title;
Photos::create($input);
return back()
->with('success','Image Uploaded successfully.')
->with($user);
}
我得到的错误是:SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into 'photos' ('image', 'title', 'updated_at', 'created_at')
上传工作没有user_id行。
你能帮我解决一下我做错了什么吗?
答案 0 :(得分:0)
您正在创建仅包含标题和图片的照片。需要一个user_id参数。
$input['title'] = $request->title;
$input['user_id'] = $user;
Photos::create($input);
或者
Auth::user()->photos()->create($input);