None of your fields is nullable in the database, so try:
dd($request->all(), $user->id);
before you create the post and make sure that all the fields have value.
(Post Model)
class Post extends Model { protected $fillable = [ 'title', 'description', 'prize', 'location', 'image', 'user_id' ];
public function user()
{
return $this->belongsTo('App\User');
}
}
(Migration Schema)
public function up() { Schema::create('posts', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id'); $table->string('title'); $table->mediumtext('description'); $table->decimal('prize'); $table->string('location'); $table->string('image'); $table->timestamps(); }); }
(PostsController)
public function store(Request $request, User $user) { $this->validate($request, [ 'title' => 'required', 'description' => 'required', 'prize' => 'required', 'location' => 'required', 'image' => 'image|max:1999' ]);
if($request->hasFile('image'))
{
//Get file name with the extension
$fileNameExtension = $request->file('image')->getClientOriginalName();
//Get just filename
$fileName = pathinfo($fileNameExtension, PATHINFO_FILENAME);
//Get just extension
$extension = $request->file('image')->getClientOriginalExtension();
//File name to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//Upload image
$path = $request->file('image')->storeAs('public/posts_image', $fileNameToStore);
}
else
{
$fileNameToStore = 'default.jpg';
}
$post = new Post();
$post->user_id = $user->id;
$post->title = $request->input('title');
$post->description = $request->input('description');
$post->prize = $request->input('prize');
$post->location = $request->input('location');
$post->image = $fileNameToStore;
$post->save();
return redirect('/posts')->with('success', 'Post Created');
}
May I know what's the problem here? I assigned the associated user_id foreign key to the associated id of the user.
Sure, but why are you typehinting a User in thestore method; this is the source of your issues. As I mentioned earlier, you can get the authenticated user's id from the auth guard using auth()->id(), but this will not work if unauthenticated users can submit the form
Please or to participate in this conversation.