Skip to content
Advertisement

Cannot Create Post

I am unable to create a post, I am a beginner so apology in advance if my question sounds stupid

Heres The Picture Of My Form Before Hitting Submit:- enter image description here

Heres The Picture After Hitting Submit:- enter image description here

I cant seem to find any error

Here’s My Controller:-

  public function store(Request $request)
    {
      $data = request()->validate([
        'title' => 'required',
        'body' => 'required',
      ]);

       auth()->user()->profile()->post()->create($data
       );
       return redirect('/h');

And I do need to pass in “user_id” in it

Please Help and Thanks in advance

Advertisement

Answer

Your controller validation seems correct.

You are redirected back to your form since the request doesn’t contain the ‘title’ and ‘body’ values. These values are ‘required’ according to your validation array.

Add this line to your controller to debug and see what the request actually contains:

dd(request()->all());

In your view, make sure your html form inputs have their respective name attributes set correctly:

<form method="POST" action="/your-route">
  @csrf
  <input name="title" ...>
  <input name="body" ...>
</form>

And to answer your last question: No, you do not need to add the user_id to your $data array; Laravel will do it for you since you are chaining the create() method from the authenticated user instance with this line: auth()->user()->profile()->post()->create($data);

You could also call the create() method directly from the Post class, in which case the user_id should be specified:

Post::create([
    'user_id' => 1,
    'title' => 'My title',
    'body' => 'My body',
]);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement