I want to save a post in my db with the logged user_id.
I have a column user_id in my post table.
When I want to create a new post with this logged user_id nothing happens
Here is my my Route in my web.php :
Route::post('posts.index','PostController@store')->middleware(['auth:sanctum']);
My model post :
protected $fillable = [
'title',
'content',
'year',
'label',
'number',
'featured_image',
'user_id',
];
protected $dates = [
'created_at',
'updated_at',
'date',
];
public function users(){
return $this->belongsTo(User::class, 'user_id');
}
}
My model user
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
public function Posts(): HasMany
{
return $this->hasMany(Post::class, 'user_id');
}
}
and my Postcontroller :
public function store(StoreRequest $request): RedirectResponse
{
$post = new Post();
$user = Auth::user();
$post->user()->associate($user);
$post->save();
$validated = $request->validated();
if ($request->hasFile('featured_image')) {
// put image in the public storage
$filePath = Storage::disk('public')->put('images/posts/featured-images', request()->file('featured_image'));
$validated['featured_image'] = $filePath;
}
I have test many things but I’m lost !
Thank you for your help
2
Answers
many thanks for your answer but when I wrote :
posts() is undefined method
here is the code from my store controller after:
have an idea ? many thanks
Welcome to laravel!
A simple way is to grab the authenticated user as you do and associate the post that you try to store:
Check out how the create method works in the official documentation for the eloquent relationships.
Also, double check that the form you have created is performing a POST request to the
route('posts.index')
.