我正在尝试将图像上传到预先存在的表单,但是在提交表单时出现错误 SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value。我已经设法让表单上的实际按钮和文件选择器起作用,但是,在提交时它会引用上述错误。关于这个问题的任何帮助或资源都会很棒。后控制器<?phpnamespace App\Http\Controllers;use App\Post;use Illuminate\Http\Request;class PostController extends Controller{ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $posts = Post::all(); return view('post.index', compact('posts')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $post = new Post(); return view('post.create', compact ('post')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $data = request()->validate([ 'title' => 'required', 'body' => 'required', ]); $post = \App\Post::create($data); return redirect('/posts'); } /** * Display the specified resource. * * @param \App\Post $post * @return \Illuminate\Http\Response */ public function show(Post $post) { return view('post.show', compact('post')); } /** * Show the form for editing the specified resource. * * @param \App\Post $post * @return \Illuminate\Http\Response */ public function edit(Post $post) { return view('post.edit', compact('post')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Post $post * @return \Illuminate\Http\Response */
1 回答
MYYA
TA贡献1868条经验 获得超4个赞
我认为默认情况下 user_id 没有默认值。在您的帖子模型中,
protected $fillable = ['user_id', 'title', 'body', 'image'];
同样在您的商店功能中,您必须包括来自当前登录用户的用户。
use App\Post;
use Auth;
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
$post = new Post();
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect('/posts');
}
- 1 回答
- 0 关注
- 103 浏览
添加回答
举报
0/150
提交
取消