Crud In Laravel 4

CRUD In Laravel

So if you read Install Laravel on Windows (or a Mac, we like those too!), you’re probably wondering what comes next. We have this Laravel installation running and the friendly message letting us know we have arrived is on the screen. We have untold amounts of power at our fingertips, but it’s a bit confusing as to where to begin next. Well this post will start getting our hands dirty in putting Laravel to use as well as implementing Create, Retrieve, Update, and Delete!


Create a Database and Configure Database.php

At the mysql console we can run mysql> create database laravelblog; to create a sample database to work with.

Let’s also put some dummy data in there using this command mysql> insert into posts(title,body) values('A Cool Title', 'With a Nice Body');

Ok we have a database with one row of data in it. Before we can use Laravel to start operating on that data we need to tell it how to connect to the database and which database to use. Since this is just a tutorial on our localhost, we will go with the minimal security option:


Configure Our Routes.php File

Go ahead and open up the routes.php file and add this snippet of code to it:

Awesome! You can see we have retrieved the data which we had previously entered into the database at the command line. Let’s add some more data to the database with mysql> insert into posts(title,body) values('Our 2nd Title', 'Our Second Body'); then run that same query:

Oh yeah! We’re returning both rows with ease. Now the get() method is quite powerful and returns everything in that table. You will need to be much more granular in your select statements in the real world. Let’s find a post by id using the find() method:

Well that was really cool! Let’s get more granular and only access the title of the post that has id of 1:

How about using where clauses? We can do that quite easily like so using the where() method:


CRUD

Let’s check out another way to use the Database class to do our CRUD or Create, Retrieve, Update, and Deleting of data. We’ll be looking at the insert, select, update, and delete methods respectively.


Insert (Create)

Let’s go ahead and add a third row to our database but instead of using the mysql console, we will now use the DB class of Laravel with the insert method!


Retrieve (Select)

Let’s select that new record just to be sure it took!


Update (Update)

I think we’ll update the body of that same post now:


Delete (Delete)

Last up we have the delete method. I bet you can guess what it does 🙂

And just like that, we have deleted the given post. We haven’t even scratched the surface with Laravel and this is as they say only the tip of the iceberg. Coming soon will be a dive into Eloquent for which minds will be blown.