Click to share! ⬇️

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:


		'mysql' => array(
			'driver'    => 'mysql',
			'host'      => 'localhost',
			'database'  => 'laravelblog',
			'username'  => 'root',
			'password'  => '',
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
		),

Configure Our Routes.php File

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


Route::get('/', function()
{
    $posts = DB::table('posts')->get();
	dd($posts);
});

//array (size=1)
//  0 => 
//    object(stdClass)[130]
//      public 'id' => int 1
//      public 'title' => string 'A Cool Title' (length=12)
//      public 'body' => string 'With a Nice Body' (length=16)

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:


Route::get('/', function()
{
    $posts = DB::table('posts')->get();
	dd($posts);
});

//array (size=2)
//  0 => 
//    object(stdClass)[131]
//      public 'id' => int 1
//      public 'title' => string 'A Cool Title' (length=12)
//      public 'body' => string 'With a Nice Body' (length=16)
//  1 => 
//    object(stdClass)[132]
//      public 'id' => int 2
//      public 'title' => string 'Our 2nd Title' (length=13)
//      public 'body' => string 'Our Second Body' (length=15)

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:


Route::get('/', function()
{
    $posts = DB::table('posts')->find(1);
	dd($posts);
});

//  Note that this time, a single object is returned instead 
//  of an array of objects
//
//object(stdClass)[131]
//  public 'id' => int 1
//  public 'title' => string 'A Cool Title' (length=12)
//  public 'body' => string 'With a Nice Body' (length=16)

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


Route::get('/', function()
{
    $posts = DB::table('posts')->find(1);
	dd($posts->title);
});

//  Check it out, you have access to each field within the table 
//  simply by accessing the property of the object returned
//
//  string 'A Cool Title' (length=12)

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


Route::get('/', function()
{
    $posts = DB::table('posts')->where('id', '!=', '1')->get();
	dd($posts);
});

//  Here we get all posts that do not have an id of 1
//
//array (size=1)
//  0 => 
//    object(stdClass)[131]
//      public 'id' => int 2
//      public 'title' => string 'Our 2nd Title' (length=13)
//      public 'body' => string 'Our Second Body' (length=15)

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!


Route::get('/', function()
{
    $posts = DB::insert('insert into posts (title, body) values(?, ?)', array('Insert from DB class','How Ya Like Me Now?!'));
	dd($posts);
});

//  a dd of $posts shows true meaning our insert was successful
//
//  boolean true


Retrieve (Select)

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


Route::get('/', function()
{
    $posts = DB::select('select * from posts where id = ?', array(3));
	dd($posts);
});

//  Yep, working nice!

//array (size=1)
//  0 => 
//    object(stdClass)[130]
//      public 'id' => int 3
//      public 'title' => string 'Insert from DB class' (length=20)
//      public 'body' => string 'How Ya Like Me Now?!' (length=20)


Update (Update)

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


Route::get('/', function()
{
    $posts = DB::update('update posts set body = "I Like Ya!" where id = ?', array(3));
	dd($posts);
});

//  int 1 indicates how many rows were affected

//  int 1


Delete (Delete)

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


Route::get('/', function()
{
    $posts = DB::delete('delete from posts where id = ?', array(3));
	dd($posts);
});

//  int 1 indicates how many rows were affected

//  int 1

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.

Click to share! ⬇️