Since its initial release in 2011, Laravel has experienced exponential growth. In 2015, it became the most starred PHP framework on GitHub and rose to the go-to framework for people all over the world.

Laravel focuses on the end user first, which means its focus is on simplicity, clarity, and getting work done. People and companies are using it to build everything from simple hobby projects all the way to Fortune 500 companies.

My goal with this Laravel tutorial to create a guide for those just learning the framework. This guide will take you from the very beginning of an idea into a real deployable application.

This look at Laravel will not be exhaustive, covering every detail of the framework, and it does expect a few prerequisites. Here is what you will need to follow along:

A local PHP environment (Valet, Homestead, Vagrant, MAMP, etc.).

A database. I’ll be using MySQL.

PHPUnit installed.

Node installed.

Note: For the local PHP environment I am using a Mac and Valet because it automatically sets up everything. If you are on Windows, you should consider Homestead or some flavor of a virtual machine.

I am attempting to go through the process of creating a new application just as I would in a real-world environment. In fact, the code and idea are from a project I built.

Planning

Every project has to start from somewhere, either assigned to you by your work or just an idea in your head. No matter where it originates, thoroughly planning out all the features before you start coding is paramount in completing a project.

How you plan is dependent on how your mind works. As a visual person, I like to plan on paper, drawing out the way I picture the screens looking and then working backward into how I would code it. Others prefer to write a project plan in a text file, wiki, or some mind mapping tool. It doesn’t matter how you plan, just that you do it.

For this guide, we are going to be building a link directory. Here is a list of fundamental goals for this links app:

Display a simple list of links.

Create a form where people can submit new links.

Validate the form.

Insert the data into the database.

Let’s get started!

The First Steps

With a simple plan of attack outlined, it’s time to get a brand new empty project up and running. I like to put all my projects in a ~/Sites directory, and these instructions will use that location. I’ve already “parked” this directory in Valet, so any folders will automatically be mapped to “foldername.dev” in the browser.

Open your terminal application and switch into this directory.

mkdir ~/Sites
cd ~/Sites

Next, install Laravel’s command line installer:

composer globalrequire"laravel/installer"

You need to make sure that the global Composer bin is in your path. You can do so by adding the following to your PATH in your ~/.bash_profile or ~/.zshrc if you are using Z shell:

export PATH="$HOME/.composer/vendor/bin:$PATH"

For the path to take effect, you need to restart your terminal session of source the file again:

source ~/.bash_profile

Now you can use the Laravel installer to create new projects from the command line:

laravel new links

This will create a new directory at ~/Sites/links and install an stock Laravel project. Visiting links.dev in the browser now shows the default Laravel welcome page:

Now scaffold out the authentication system by running:

phpartisanmake:auth

Even though this tutorial will not dive into authentication by running this command, it will modify our views and routes. So by doing it early, we don’t have to worry about it messing with any of our code.

With the basics set up and working, it’s time to start doing some coding.

Building a List of Links

If you start thinking about the whole finished project, it’s easy to get overwhelmed. The best way to fight this is to break everything down into small tasks. So, let’s start with showing a list of links.

Even though showing a list of links sounds like a small task it still requires a database, a database table, data in the table, a database query, and a view file.

Creating a migration will be the first step, and the Laravel Artisan command line tool can help us build that.

php artisan make:migration create_links_table --create=links

Now, open the file this command created. It will be located at database/migrations/{{datetime}}_create_links_table.php.

While you are working with test data, you can quickly apply the schema:

phpartisanmigrate:fresh

Next, we need some data and a model to work with our database table. Laravel provides two features which help with this: the first is a database seeder, which populates the database with data, and second, the model factory files that allow us to generate fake model data that we can use to fill our development database and tests:

phpartisanmake:model--factoryLink

The --factory flag will generate a new factory file in the database/factories path, in our case a new LinkFactory file will include an empty factory definition for our Link model.

We have the data place and a model to interact with the database. We are now ready to start building the UI to add new links to the application.

Routing and Views

To build out a view showing the list of links, we need to update the main project route and also define a new route that will display our submission form. We can add new routes to our application in the routes/web.php file.

In the web routes file you should see the default route below:

Route::get('/', function(){
return view('welcome');
});

To create a new route we can either use a route closure or a dedicated controller class. In this tutorial, we will use closures for our submission and index routes.

First, let’s update the home route by getting a collection of links from the database and passing them to the view:

If you refresh your browser, you should now see the list of all the links added. With that all set, let’s move to submitting links.

Displaying the Link Submission Form

We are almost done creating our first application in Laravel. We will round out this Laravel tutorial with the ability for others to submit links into the app, which requires three fields: title, URL, and a description.

I am a visual person, and before planning out features requiring HTML, I like to draw them out so I can get an idea of what I’m building in my head. Here is a simple drawing of this form:

Since we’ve added all the core structure, model factory, migration, and model, in the last section, we can reap the benefits by reusing all those for this section.

First, create a new route in the routes/web.php file:

Route::get('/submit', function(){
return view('submit');
});

Next, we need to create the submit.blade.php template at resources/views/submit.blade.php with the following boilerplate bootstrap markup:

There’s quite a bit going on in this form, so let’s go over the major points that might be confusing when you are new to Laravel.

Near the top of the form, we have a blade conditional that checks to see if there are any validation errors. When errors exist, the bootstrap alert message will be shown, prompting the user to fix the invalid form fields:

If the user submits invalid data, the route will store validation in the session and redirect the user back to the form. The {{ old('title') }} function will populate the originally submitted data. If a user forgot to submit one of the fields, the other fields that have data would be populated after validation fails and errors are shown.

If a field has an error, the first() method returns the first error for a given field:

{{ $errors->first('title') }}

Submitting the Form

With the form in place, we are ready to handle the POST data and validate data. Back in the routes/web.php file, create another route for the POST request:

First, we are injecting the Illuminate\Http\Request object, which holds the POST data and other data about the request.

Next, we use the request’s validate() method to validate the form data. The validate method was introduced in Laravel 5.5 and is a nice shortcut over other methods used for validation. As a bonus, the validated fields are returned to the $data variable, and we can use them to populate our model.

We require all three fields, and using the pipe character; we can define multiple rules. All three rules can have a max of 255 characters, and the url field requires a valid URL.

If validation fails, an exception is thrown, and the route returns the user with the original input data and validation errors.

Next, we use the tap() helper function to create a new Link model instance and then save it. Using tap allows us to call save() and still return the model instance after the save.

Typically, you would have to do the following without tap, it just adds a little syntactic sugar:

$link = new \App\Link($data);
$link->save();
return $link;

If we want to populate a new model with data, we need to allow the fields to be “fillable” via mass assignment. The fillable property is designed to prevent fields from being mass-assigned except for the items you define in the array.

In our case, we are validating each field so allowing them to be mass-assigned is safe. To allow our model assign values to these fields, open the app/Link.php file and update it to look like the following:

The last thing we do in our POST route redirects the user back to the home page after saving the link successfully.

Testing the Form Submission

Laravel makes HTTP testing a breeze for performing integration tests against routes and middleware, so let’s write a few feature tests to verify our code works as expected.

Before we get started, we need to adjust a few things in our phpunit.xml file so that we can use an in-memory SQLite database. You will need to make sure that you have the proper PHP modules installed.

Using environment variables, we can change the database connection by adding a few new variables to the config:

Take note of the RefreshDatabase trait which makes sure that each test has a new database to give each test a pristine database environment with all the migrations.

Our first test submits valid post data, which returns a response object that we can use to assert that our route responded as expected. We verify that the database contains a record with the title we just created.

Next, we verify that the response was a 302 status code with a Location header pointing to the homepage.

Last, we request the home page and verify that the link title is visible on the homepage.

Testing Failed Validation

When a user generally submits bad data, we expect the validation to trigger an exception and we can use that to make sure our validation layer is working:

We use Laravel’s assertSessionHasErrors() to make sure that the session has validation errors for each of our required fields. Because we submitted empty data to the route, we expect the required rule will trigger for each field.

Laravel 5.5 introduced the withoutExceptionHandling() method which disables Laravel’s route exception handling code used to generate an HTTP response after an exception. We use this to our advantage so we can inspect the validation exception object and assert against the error messages.

We loop through various cases (add your own if you’d like to cover more scenarios) and catch instances of ValidationException. If the text makes it past the exception handling, we manually fail the test because we expect the route throws a ValidationExcepiton exception each time.

The catch block uses the validator object to check the url error and asserts that the actual error message matches the expected validation error message.

I like using the try/catch technique, followed by a $this->fail() as a safety harness instead of using exception annotations provided by PHPUnit. I feel catching the exception allows the ability to do assertions that wouldn’t otherwise be possible and provides a more granular control that I like in most cases.

Testing Max Length Validation

We will test a few scenarios with the max:255 validations rules: when the field fails max-length validation with a length of 256 characters, and when the field is long enough to pass validation at 255 characters.

Although Laravel contains the max validation rule functionality, I like to test it to verify that my application applies the rules. If someone removes the max validation rule, then the tests will catch it.

I like to test the threshold of min and max validation rules as an extra caution to make sure my application respects the min and max boundaries I set.

Conclusion

Congratulations on making it through the tutorial. This guide was designed to get you started on building your app, and you can use this as a building block to gain the skills you need to develop your application. I know this covers a lot of features and can be overwhelming if you are not familiar with the framework.

I hope this introduction to Laravel shows you why so many people are excited about the framework.

Learn about Python tuples: what they are, how to create them, when to use them, what operations you perform on them and various functions you should know.

Similar to Python lists, tuples are another standard data type that allows you to store values in a sequence. They might be useful in situations where you might want to share the data with someone but not allow them to manipulate the data. They can however use the data values, but no change is reflected in the original data shared.

In this tutorial, you will see Python tuples in detail:

You will learn how you can initialize tuples. You will also see the immutable nature of tuples through examples;

You’ll also discover how a tuple differs from a Python list;

Then, you will see the various tuple operations, such as slicing, multiplying, concatenating, etc.;

Be sure to check out DataCamp’s Data Types for Data Science course, where you can consolidate and practice your knowledge of data structures such as lists, dictionaries, sets, and many more! Alternatively, also check out this Python Data Structures Tutorial, where you can learn more about the different data structures that Python uses.

Python Tuple

As you already read above, you can use this Python data structure to store a sequence of items that is immutable (or unchangeable) and ordered.

Tuples are initialized with () brackets rather than [] brackets as with lists. That means that, to create one, you simply have to do the following:

cake = ('c','a','k','e')
print(type(cake))

<class 'tuple'>

Remember that the type() is a built-in function that allows you to check the data type of the parameter passed to it.

Tuples can hold both homogeneous as well as heterogeneous values. However, remember that once you declared those values, you cannot change them:

mixed_type = ('C',0,0,'K','I','E')
for i in mixed_type:
print(i,":",type(i))