Mick79's avatar

Posting to database (form validation 101 video)

Hi, in this video Jeffrey shows us various ways to post data from a form to the database. He finally lands on this way:

Post::create(request(['title','body']));

and here is the form

<form method='POST' action='/posts'>
                    {{csrf_field()}}
                    <div class="form-group">
                        <label for="exampleInputEmail1">Title</label>
                        <input type="text" class="form-control" name='title' placeholder="Title">
                    </div>
                    <div class="form-group">
                        <textarea class='form-control' title='body' placeholder='Body' name='body'></textarea>
                    </div>
                    <button type="submit"
                            class="btn btn-primary">
                        Publish
                    </button>
                </form>

I'm struggling to work out how the controller knows what to post where. I have come to the conclusion that for this way to work, you need the "name" fields in your form to match the column names in your database.

Would that be correct?

0 likes
2 replies
andonovn's avatar
andonovn
Best Answer
Level 22

@Mick79 yup, that's correct :)

Edit: Assuming the for this way to work statement. As pointed below, It's not mandatory to always match these.

Basically, only the inputs with the name attribute are being sent to the server. Inside the controllers, we can access the input via the Illuminate\Http\Request object. In your example, that's achieved via the request() helper.

1 like
Snapey's avatar

its not mandatory but it makes sense if you name your form elements the same as your model attributes.

if your form elements are different, you have to map them across like

Post::create([
    'title' => $request->post_title,
    ’body' => $request->post_body,
]);

as an example if your form fields were post_title and post_body

2 likes

Please or to participate in this conversation.