Learning Laravel Models

Laravel models are based on the common MVC or Model-View-Controller principles. If you don’t know what MVC is at all, you can Learn More about MVC Here because I just want to get to the meat of learning how to use Laravel Models in this Laravel models tutorial.

Prerequisites

You may have learned from following my Laravel tutorials, that you often need parts of other Laravel tutorials to fully understand the current tutorial. Well guess what? this applies here as well. You should have an understanding of the following areas of Laravel before attempting to learn about models:

The User Model

Since the user model is necessary in almost any modern web application, Laravel has created a basic user model and provided it in  app/models/User.php  for you to manipulate and copy as needed.

Generally models will follow the same naming convention as the example User Model. So if you added a new model to your project called Cars that was a representation of cars owned by the site’s users then that model would also go in the app/models directory and would be named Cars.php so your complete path would of course be app/models/Cars.php.

Models and the Database

Each model in your project is directly related to a table in the database. By default that table will take the same name as the model, but  for the User model the table name is users, so for Cars, the table name would be cars. Follow that basic pattern and you should be okay. If you want to use a different name you can declare the table name for your model as you will see in the example code below.

Since every model interacts with a database table, the first thing we need to do is make our model class extend the Eloquent class. The Eloquent class is a database class Laravel uses with every model in order to interact with the database. So your first line of actual code should read:

class User extends Eloquent {}
Now we have started our class. Simply replace “User” with your class name if you are working on a different class.
To get an idea of how a model class should be written, you can follow the default User model that comes shipped with Laravel. Also while opening the class statement, the User model implements a couple interfaces:
implements UserInterface, RemindableInterface
so the complete first line of the User model looks like:
class User extends Eloquent implements UserInterface, RemindableInterface {

After that, as I mentioned above, is where you could change your table name, however since the User model doesn’t do so, the following line could have been left out. It was most likely left in as a way to demonstrate how to name a table other than the default one for those who have a need or desire to do so. Here is how the User model declares its table name:

protected $table = 'users';
As I mentioned, since the name is users and that would be automatically assumed since the name of the model is User, this line is not mandatory but does show you what to do if you wanted to use a table named something other than users which you could do if you wanted simply by replacing “users” with “table_name” for example.
The next line in Users.php looks like:
protected $hidden = array('password');
What the above line does is prevents the user’s password from being displayed when you might not want it to such as in a json API call. There are a couple of other measures that could be applied here to further protect your data such as the $fillable and the $guarded properties. $fillable tells Laravel which columns of your database table can be filled and guarded tells Laravel which ones cannot be filled basically. Here is an example of each:
protected $fillable = array('username', 'email');
protected $guarded = array('id', 'password');
The first line above tells us that username and email are allowed to be filled in the database by the user and the second line tells us that they cannot fill in the id and password fields.
Returning Data from a Model
The next practical thing the User.php Model allows us to do is return some data from the database with the following three functions:
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }
    public function getAuthPassword()
    {
        return $this->password;
    }
    public function getReminderEmail()
    {
        return $this->email;
    }
That is all for the User class actually, so lets explain the last three functions. The first is for returning a unique identifier of the user. The second returns the user’s password and the third returns that user’s reminder email address. Pretty simple really!

How to Use a Model

Everything you have learned so far is great, but how about seeing it in action? Yes, let’s do that! In order to use the model, we need to define a route in the app/routes.php file, so open that file and append the following code to the end:
If the code worked, you will see:
bool(true)
only in the resulting page that opens. If it fails you will probably see a big long error page. in which case you will have to go back and check each step of this tutorial to see what you missed or make sure you set up the database and users table properly. If you have not done, so first, you need to create the users table by following this tutorial about database tables and Laravel:
When you are done and have successfully added a user to the users table, comment out the code in routes.php so you don’t recreate the user every time you or someone else lands on that url.

Summary

To learn more about Laravel, follow more tutorials I have written by CLICKING HERE!

Creating Database Tables with Laravel

Okay, today we are going to cover how to get started with Laravel Database tables. You can create databases with Laravel, but for this tutorial on creating tables with Laravel, we are going to simply use phpmyadmin to make our database if you don’t already have one made for your Laravel project.

Prerequisites

If you have not yet even installed Laravel, see my first tutorial on Laravel, Installing Laravel on XAMPP at http://jafty.com/blog/installing-laravel-php-framework-on-xampp/

That’s really all you have to do before using this getting started tutorial, but you may need to reference other tutorials as you go depending on what you already know. I will try to reference the proper ones throughout this tutorial series to help you learn.

Selecting a Database for Laravel

As you probably are aware, most web sites need a database, so the first logical step to getting your Laravel project off the ground after installing the Laravel PHP framework itself, is to add a database. I am going to instruct you on how to install a MySQL database with Laravel. If you want to use a different database or storage option….. well, you are on your own. Sorry, but I don’t know why you would want to use anything other than the most popular free developer’s database available, MySQL. How do I know? You may have a legitimate reason, unfortunately, I just can’t help you, but Laravel can, they have an abstraction layer that makes the syntax for all database and storage methods the exact same. No matter what database you use, you will be okay, but some of the steps in this particular tutorial will be slightly different, but don’t worry too much about that, they should be obvious if you have enough experience with your database of choice which you should if you are ready to jump into learning a whole new PHP framework.

Configuring a Laravel Database

Now you are ready to make changes to the config files for Laravel to accommodate your database. Find the config file at app/config/database.php. If you are using a localhost install of Laravel for learning purposes, which is probably smart, then your config file changes will be minimal really. All you have to do is change the name of the database in the “database” variable at or about line number 57(depending on how many edits you made and what version of Laravel you are using). Change the default value of ‘database’ to the name of your database(unless you named your database, ‘database’). I named my database ‘laravel_test’ for this tutorial. The database will be the main database for your project and will hold all of the project’s tables.

Create a Laravel Database

Now you have to go to your PHPMyAdmin url and create the actual database. If you are developing on the localhost, you can go to localhost/phpmyadmin or wherever you installed phpmyadmin and create a database named after the same name you set in your config file for the ‘database’ option in the database.php config file. In my case, I named my database ‘laravel_test’ and created that same database from localhost/phpmyadmin.

Creating a Database Table in Laravel

Okay, now that you have created a database, it’s time to really get to the meat of this tutorial and execute some code in Laravel to make a table on your new database.

Okay, remember I promised to tell you if you might need another tutorial to understand a part of this one? Here is the first case this has come up. You may wish to take a break from this tutorial now and check out my tutorial on Laravel Routes at:

http://jafty.com/blog/laravel-routes/

…or you may want to assume you can figure them out from the example in this tutorial, but you won’t get the whole idea of routes from this tutorial as it only uses routes to make a database table and that is not what they are really all about. Routes are actual routes to your different parts of your Laravel project, hence the name, “routes”.

So, whether or not you decided to take my advice and visit my “routes” tutorial, we are moving on! Here is the code you need to add to routes.php in order to create a database table using Laravel. as you can see, it’s a lot simpler than creating a table in .sql and a bit faster than creating one in phpmyadmin if you use it correctly:

Route::get(‘make_table’, function()
{
Schema::create(‘users’, function($table)
{
$table->increments(‘id’);
$table->string(‘username’, 32);
$table->string(’email’, 320);
$table->string(‘password’, 60);
$table->timestamps();
});
});

If you have already learned about routes, you know from the above code to go to:

http://localhost/laravel/project1/public/make_table

in my case to execute the above code. Your path will depend on how you installed Laravel of course, but it should be similar if you are following my tutorials. You won’t see anything but a blank window open when going to the URL. To check your work, go to phpmyadmin and examine the users table inside the database you created. It should have all the fields from the code above, but note that the timestamps() function actually creates two columns in the table, created_at and updated_at. So you should have six fields in your table, not five as you may have expected with only five lines of code.

Different Types of Data Fields

As you may know there are several types of data fields in Mysql, such as varchar, increment, bigint, etc just to name a few. Here is a list of Laravel commands for each so you can create the necessary fields of data for your own table:

Command Description
$table->increments('id'); Incrementing ID to the table (primary key).
$table->bigIncrements('id'); Incrementing ID using a “big integer” equivalent.
$table->string('email'); VARCHAR equivalent column
$table->string('name', 100); VARCHAR equivalent with a length
$table->integer('votes'); INTEGER equivalent to the table
$table->bigInteger('votes'); BIGINT equivalent to the table
$table->smallInteger('votes'); SMALLINT equivalent to the table
$table->float('amount'); FLOAT equivalent to the table
$table->decimal('amount', 5, 2); DECIMAL equivalent with a precision and scale
$table->boolean('confirmed'); BOOLEAN equivalent to the table
$table->date('created_at'); DATE equivalent to the table
$table->dateTime('created_at'); DATETIME equivalent to the table
$table->time('sunrise'); TIME equivalent to the table
$table->timestamp('added_on'); TIMESTAMP equivalent to the table
$table->timestamps(); Adds created_at and updated_at columns
$table->softDeletes(); Adds deleted_at column for soft deletes
$table->text('description'); TEXT equivalent to the table
$table->binary('data'); BLOB equivalent to the table
$table->enum('choices', array('foo', 'bar')); ENUM equivalent to the table
->nullable() Designate that the column allows NULL values
->default($value) Declare a default value for a column
->unsigned() Set INTEGER to UNSIGNED

Summary

That is it, you know now how to create a table using Laravel and routes! congratulations!

To learn more, see all my Laravel tutorials by Clicking HERE!

 

 

 

Installing Laravel PHP Framework on XAMPP

This is a straight-to-the-point tutorial on how to install and use the Laravel PHP framework with a local XAMPP server on your machine’s localhost. This post covers installing Laravel, but be sure to read other posts here in the Laravel Category to learn much more about the Laravel PHP framework.

Prerequisites:

  1. php version 5.3.7 or higher
  2. mcrypt module which comes with xampp and wampp by default so you shouldn’t have to do anything, but maybe check php info to make sure it’s there.
  3. Make sure openssl is enabled in your php.ini file
  4. make sure your httpd.conf file includes the httpd-vhosts.conf file in it.

Install Directions

  1. First, install composer by going to http://getcomposer.org/download/ and clicking on the link that reads: “Composer-Setup.exe” just under the “Windows INstaller” heading on that webpage.
  2. Secondly, install Laravel by going to http://laravel.com/ and click on the “Five Minute Quickstart” button to get a full set of instructions in case you need help, but I’ll give you the basic install steps next to keep it quick and easy for you.
  3. Go into your Xampp directory, open the htdocs folder and make a new directory for your Laravel project. You can name it simply “laravel” if you like to keep it easy to follow these instructions.
  4. Open your Command Prompt in Windows by clicking on start/All Programs/Accessories/Command Prompt and change your current working directory to that of the laravel folder you just created by using the cd command followed by the directory path.
  5. copy and paste the following text into your command prompt window: composer create-project laravel/laravel your-project-name --prefer-dist
  6. before you hit enter, replace “your-project-name” with a project name of your choice such as “project1” as I did for this tutorial. Then press enter and Laravel will take several minutes to install usually.

That is all there is to a simple install on Xampp. Now you can go to your favorite browser and open up http://localhost/laravel/project1 and you should see the Laravel logo along with a quick message saying “You have arrived.” Now it’s time to learn how to use Laravel and find out about some of Laravel’s features.

Bundles

Bundles are add-ons that you can download and plug into your Laravel installation for added functionality. Be sure to check out the bundles at http://bundles.laravel.com/

Click on the Laravel category at the bottom of this page or type “laravel” in the search box of my blog to find more tutorials on Laravel right here! …or CLICK RIGHT HERE to jump there now.

Laravel Routes & Controllers

One of the first things I learned when discovering the Laravel PHP framework, was how to use routes. Routes are a simple method of using sub-directories in a URL to show different content. For example you can set a route to “about” and code that route to show your about page content. Let’s expand on that idea with a code example to help you get it:

Go to your project directory in Laravel and locate the app directory and the file name routes.php. This is where you can add your own routes. Lets start with simple route by adding the following code to routes.php at the end of the file:

Route::get(‘about’, function(){

return(‘<h1>About Us</h1>Jafty.com is a fully functional web development company offering almost any service to do with web development, including, but by no means limited to, PHP, HTML5, CSS3, JavaScript, Photoshop, Logo Design, Jquery, Server Installation, Site Migration, WordPress, Joomla, Linux servers, Windows servers, etc. Just ask, I pretty much do it all. Yes, Jafty.com is basically, jut me, Ian L. I do hire additional help as needed ,but I personally manage and oversee every project that comes through my company and make sure that it meets or exceeds my rigid quality control standards.’);

});

You can copy and paste the above green text into your app/routes.php file at the end and it will produce the following when you go to (in my case)localhost/laravel/project1/public/about. Here is a screenshot:

Snap 2013-09-19 at 12.13.15Now you may not wish to put all that code inside your routes.php file, especially in times where you need a lot more code for a page. You can use controller classes with your routes to effectively put most of the code in another file which I will explain next.

Here is an example of a basic controller class:

class UserController extends BaseController {

    public function showWelcome()
    {
        return ‘Hello controller world!’;
    }

}

to make that class work, you would put the above code in a file named “UserController.php” inside of the app/controllers folder of your Laravel project directory and then add the following to your app/routes.php file at the end:

Route::get(‘usercontrol’, ‘UserController@showWelcome’);

Finally, after you create a new controller, you always need to flush the autoload contents before the new controller will work, so do so by opening your command prompt that you use composer from, change the working directory to that of your application and type:

composer dump-autoload

I’ve found you don’t need to do the above command if you only create a route, but if you make a controller, do it! Also if you have issues running the above command from localhost, make sure you have the correct path and command prompt. If you installed Composer through Windows, open a Windows command prompt. If you installed it in Xampp, open a Xampp command prompt etc.

That’s all there is to learning how to use basic routes and basic controllers. Of course there are more complex solutions than this, but this will get you started off on the right foot at least. To learn more, CLICK HERE FOR MORE LARAVEL TUTORIALS. I have written a boat load of Laravel tutorials on this blog and am adding more daily as of September of 2013, so check back if it is still 2013 when you read this or the start of 2014 even.