Thread Contributor: Baredee[TUT] 6 - Form->Database - Laravel Tutorial Series
#1
If you didn't catch the last tutorial, you can view it here

~~~~ Hey, everyone! ~~~~


This is now your 6th tutorial, we're going to be handling the form's request, and ultimately inserting a new record
into our database table. We'll utilise Laravel's Eloquent ORM and we'll see how all that magic works. Let's get into it.





From Form to Route


If you remember, I created a form.


[Image: 3867326eb2b14c108654f0e35af19843.png]


If we submit this form, guess what happens?


[Image: e5dc1db48a084048a5cf848cc4a144dc.png]


Remember, basic HTTP request concept:

A GET and a POST request are NOT THE SAME THING


[Image: 8d3a54e3868c41d9b4cc9f8ee0849b60.png]


Just because we've facilitated a GET request to the specified endpoint (people/) in our Routes,
doesn't mean we'll also be able to handle POST requests like the one our form is attempting to send through right now.

So what do we do?

We create a new endpoint for a POST request, and direct the request to a create() function in our PeopleController which
we will also create.

(vtech/routes/web.php)

[Image: b7d6b0c2cc2b4f44ac7cfecf7417d00a.png]


Create the function in the controller

(vtech/app/Http/Controllers/PeopleController.php)

[Image: f7d2ba741a9447b5b250d5a6489d7d9e.png]


Now try to submit the form.


I just realised that I set the "action" attribute of the form to an incorrect value. No worries, just change it:


[Image: 4bad0038c14045fcb47a0b457aba7721.png]


Now if you go back to http://localhost:8000/people, and hit the Create button...


[Image: 02e208aa552a4a4293a7f2bbe1c2459f.png]


It works!

Now we need to replace that announcement with the functionality to actually insert a new record.

Well firstly, let's tell it to dump the request() that's passed in, instead of the announcement;

(in the create() function)
"dd(request())"

dd - dump and die. (as in dump the information, then die (stop everything else))

Go back, fill in the form, and see what happens when you post it.


[Image: a96e6aef3b9c41cc98c86f0e67a9aab8.png]


...

You get exactly what you asked for, the request.

[Image: 8587ed7b4c9e4befae70d8397d3a7838.png]


If you expand the +request you can see the parameters passed in, along with the token we mentioned in previous tutorials.

How do we single out these details?

Try this:

[Image: 047e46eb645846e290fcf4658f8cdbe5.png]


Refresh the request result page:

[Image: e89459f53c4f44b9916f9178363ff963.png]


Brilliant.

I won't get into form validation etc. but you get the gist.





Inserting form data into database

So far, we've retrieved the data that has been inputted from the database, and we know how to separate the data from the rest
of the information such as headers, sessions, and cookies etc.

The question, now, is how do we actually insert those details into our database as a record of a particular table?

Well...

I'll just give it to you straight, to start with:

This is the code you will need in the create() function, to insert a record.

[Image: bcbbf24fef7b41f1a2375eaa3f4f285a.png]


What's Person? the model we created, remember?
Why does it have a create function though? Because that's part of the magic that laravel gives our models. Static functions that
allow us to directly communicate with our databases.

That's the structure to associate fields with values, in this case the name and email field to the name and email values that have been
sent in through the form.

If we now either refresh the page, or go back and re-submit the form, this happens:


[Image: f6b8afd61ae949418fddd726fa7522e0.png]


Because our PeopleController has no idea what a 'Person' is, heh. Let's import it at the top.


[Image: 14224d2ecb684bcf85eb39b4404d61b0.png]


Again, try to refresh or post the form once more:


[Image: 4d4236ff227547ba89d38b43d5e64630.png]


Another error, what now?

Mass Assignment is another issue of web security that laravel deals with, for you. It has to do with users basically being able to trick the
code into assigning information to fields that you didn't even want the form to have access to.

For example, suppose we had an 'is_admin' field in our database, and it was set to 0 by default.

A user could use Developer Tools in their browser to change the name of a field, perhaps "name", to "is_admin", and then set the value of that field to 1, and then post the form.

This will trick the code into setting the "is_admin" to a value of 1, basically
escalating the person's privileges, all because our system allows mass assignment like that.

To prevent this issue, Laravel has incorporated some mechanisms, like this exception. Alright, so how do we give it a green flag.

We have a couple of options...

We could either, in the Model itself (Person.php), specify an array of "fillable" fields

obviously excluding ID, we don't want the user to be able to edit their ID, hence why it's not included.
this will basically ignore anything other than these fields, so if the person renames something to "is_admin" - it won't assign it to
any value even if it DOES exist in the database as a field, why? because we're not accepting "is_admin" as part of what's fillable.

[Image: 18a9cc9f2aec478b9ece7560f9d00230.png]


alternatively, the opposite applies, we could use a "guarded" property, which basically lists the fields that the user is NOT allowed to fill,
implying that any field other than this is allowed.


[Image: c536fc2d2dca495f9df1b4f6fd587e07.png]

In this case, as long as what the user is trying to modify isn't "id", we will allow it.

Keep in mind, "fillable" and "guarded" are named so on purpose and are not random, don't mess with the names if you would like to utilise
these properties. You can't name it "$these_are_guarded = ['id'];" and expect it to work.

It's kinda like blacklisting and whitelisting, isn't it?

I'll be using the second method, you may do as you please.


Moving on from Mass Assignment Exceptions...





Continuing with insertion


Once you've retrieved the values and you've dealt with mass exception issues, try to refresh the page or re-post the form once more...


[Image: 5cad4e30638e4ea296ed6c8e9ec08c5c.png]

Blank page.

Check the database.


[Image: 1e92adfc7e3543918a100e6f0db24170.png]


Neat.

That's CRUD done.

Let's also take CRUD down.





Reading & Retreiving Records


Remember our main page? The one that has our form on it? Yeah? Do you remember how we had that rendered?

We used the PeopleController to render that view, we can, in the same function, pass in a collection of all "People" ... like this:


[Image: 81fda20457de4de9b6ca32b79b8fd99e.png]


Again, we're able to do Person::all(); because of Eloquent ... it's an ORM, let's get used to it. Magic happens, okay?

This results in every record in the `people` to be saved as an object (with its columns as properties) in the variable we've declared.

Next, we pass it in as an argument, with our view. Using the compact() in that fashion is the same as doing this:


$people = Person::all();

return view('people.index', ["people" => $people]);



At the end of the day, it just associates that name with the actual variable that we have.

And I don't know if you worked this out yet, but we're now able to access "$people" in our ../people/index.blade.php file.


I'll replace

[Image: 3bdbdc8e674b41f9b32dffdd902fdeb2.png]


with

[Image: 7be1c73e25884177b36b686ad7992b63.png]


and check it out:

[Image: b9dcc7ed5f8c4c31967c42fdd11b72d1.png]



If you don't understand how this is happening, leave a comment and I'll try to get back to you.


That's CRUD done now.






Conclusion


In the next one, we'll tackle Updating and Deleting. :)





[Image: a701e0ca783f4720a2616a0d57f28e3b.png]
#2
Looks really good but you might wanna explain people that they first need to validate the post data Wink

Code:
$this->validate($request,[
   "field" => "rules"
]);

// Your code after validation
Reply
#3
[Image: 24a7088187164b22942ca0a2597edbd4.png]


Thanks for your post anyway.
Reply
#4
(03-25-2017, 06:36 PM)Baredee Wrote: [Image: 24a7088187164b22942ca0a2597edbd4.png]


Thanks for your post anyway.

Sorry I dont time to read the whole thing trough but my opinion is that if you do a tutorial on this Validation is a must else people may not or use it less cause they think it is the right way or how they should start. And that is not the case. Still a good tutorial that is nicely structured
Reply
#5
(03-29-2017, 11:10 AM)Coddr Wrote:
(03-25-2017, 06:36 PM)Baredee Wrote: [Image: 24a7088187164b22942ca0a2597edbd4.png]


Thanks for your post anyway.

Sorry I dont time to read the whole thing trough but my opinion is that if you do a tutorial on this Validation is a must else people may not or use it less cause they think it is the right way or how they should start. And that is not the case. Still a good tutorial that is nicely structured

Thanks for your compliment.

I've structured these tutorials in such a way that it aims to help readers understand the fundamentals of Laravel. I'm sure they know the necessity for validating their data, like you and me, they aren't complete blockheads, I hope.

For that reason, I skipped validation, and I just put a link to the docs somewhere, in hopes that they will go and read it themselves.

There are many other things that I skipped, too. But like I said, this isn't supposed to be a comprehensive Laravel Tut, just something that helps people get an understanding.
Reply
#6
(03-29-2017, 11:27 AM)Baredee Wrote:
(03-29-2017, 11:10 AM)Coddr Wrote: Sorry I dont time to read the whole thing trough but my opinion is that if you do a tutorial on this Validation is a must else people may not or use it less cause they think it is the right way or how they should start. And that is not the case. Still a good tutorial that is nicely structured

Thanks for your compliment.

I've structured these tutorials in such a way that it aims to help readers understand the fundamentals of Laravel. I'm sure they know the necessity for validating their data, like you and me, they aren't complete blockheads, I hope.

For that reason, I skipped validation, and I just put a link to the docs somewhere, in hopes that they will go and read it themselves.

There are many other things that I skipped, too. But like I said, this isn't supposed to be a comprehensive Laravel Tut, just something that helps people get an understanding.

Fair Enough, and about the blockheads topic I can open your eyes. You only need code from people that are in class with me followoing a education for Developer.
Reply
#7
(03-29-2017, 11:55 AM)Coddr Wrote:
(03-29-2017, 11:27 AM)Baredee Wrote: Thanks for your compliment.

I've structured these tutorials in such a way that it aims to help readers understand the fundamentals of Laravel. I'm sure they know the necessity for validating their data, like you and me, they aren't complete blockheads, I hope.

For that reason, I skipped validation, and I just put a link to the docs somewhere, in hopes that they will go and read it themselves.

There are many other things that I skipped, too. But like I said, this isn't supposed to be a comprehensive Laravel Tut, just something that helps people get an understanding.

Fair Enough, and about the blockheads topic I can open your eyes. You only need code from people that are in class with me followoing a education for Developer.

Lol, I've seen some really bad code, too.

But I was referring to our current members. Tongue Out
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
[TUT] 7 - Updating & Deleting / Wrapping up - Laravel Tutorial Series Baredee 6 5,397 05-12-2017, 10:59 AM
Last Post: Baredee
[TUT] 5 - Migrations & Schemas - Laravel Tutorial Series Baredee 0 1,396 03-01-2017, 06:46 PM
Last Post: Baredee
[TUT] 4 - Models & Controllers - Laravel Tutorial Series Baredee 0 1,450 02-28-2017, 06:28 PM
Last Post: Baredee
[TUT] 3 - Artisan / Routes / Blade - Laravel Tutorial Series Baredee 0 1,365 02-27-2017, 03:31 PM
Last Post: Baredee
[TUT] 2 - Installation - Laravel Tutorial Series Baredee 0 1,552 02-27-2017, 03:28 PM
Last Post: Baredee

Forum Jump:


Users browsing this thread: 1 Guest(s)