Tuesday, September 19, 2017

Laravel Tutorial: Step by Step Guide to Building Your First Laravel Application

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 you, 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 like to use 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 taken 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’d code it out. 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 basic goals for this links app:
  1. Display a simple list of links.
  2. Create a form where people can submit new links.
  3. Validate the form
  4. Insert the data into the database.
Let’s get started building all this out.

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.
cd ~/Sites
Next, install Laravel’s command line installer:
composer global require "laravel/installer"
Once that finishes you can create the project by running:
laravel new links
This will create a new directory named “links” and install an empty Laravel project. Visiting “links.dev” in the browser now shows the default Laravel welcome page:

Now scaffold out the authentication system by running:
php artisan make: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 setup 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 create 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
Inside the up method add our new columns:
Schema::create('links', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->string('url’)->unique();
      $table->text('description');
      $table->timestamps();
});
Save the file and run the migration:
php artisan migrate
Now we need to enter some data and Laravel provides two features that help with this. The first is database seeds and model factories. But before we can use those we will need a model which can be generated like this:
php artisan make:model Link
Open the ModelFactory.php file and let’s add one for the links table:
$factory->define(App\Link::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->name,
        'url' => $faker->url,
        'description' => $faker->paragraph,
    ];
});
Next, create the link seeder, so we can easily add demo data to the table:
php artisan make:seeder LinksTableSeeder
Open the LinksTableSeeder.php file that was just created, and in the run method we will utilize the links model factory we created above:
public function run()
{
    factory(App\Link::class, 10)->create();
}
Open the DatabaseSeeder.php and add this to the run method:
$this->call(LinksTableSeeder::class);
You can now run the migrations and seeds to add data to the table automatically:
php artisan migrate --seed

Routing and Views

To build out a view showing the list of links first open the routes/web.php file and you should see the default route below:
Route::get('/', function () {
    return view('welcome');
});
Laravel provides us two options at this point. We can either add our code additions directly to the route closure, where the “return view..” is, or we can move the code to a controller. For simplicity let’s add our needed code to fetch the links directory in the closure.
Route::get('/', function () {
    $links = \App\Link::all();
    return view('welcome', ['links' => $links]);
});
Next, edit the welcome.blade.php file and add a simple foreach to show all the links:
@foreach ($links as $link)
  • {{ $link->title }}
  • @endforeach
    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.

    Submitting Links

    The next major feature is the ability for others to submit links into the app. This will require three fields: title, URL, and a description.
    I am a visual person and before planning out features that will require 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');
    });
    
    We will also need this view file so we can go ahead and create it at resources/views/submit.blade.php and add the following boilerplate bootstrap code:
    @extends('layouts.app')
    @section('content')
        
    class
    ="container"> <div class="row"> <h1>Submit a link</h1> <form action="/submit" method="post"> {!! csrf_field() !!} <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" name="title" placeholder="Title"> </div> <div class="form-group"> <label for="url">Url</label> <input type="text" class="form-control" id="url" name="url" placeholder="URL"> </div> <div class="form-group"> <label for="description">Description</label> <textarea class="form-control" id="description" name="description" placeholder="description"></textarea> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </div> @endsection Now, let’s create a route to handle the POST data and do our validation. Let’s create that route and add our validation rules in:
    use Illuminate\Http\Request;
    
    Route::post('/submit', function(Request $request) {
        $validator = Validator::make($request->all(), [
            'title' => 'required|max:255',
            'url' => 'required|max:255',
            'description' => 'required|max:255',
        ]);
        if ($validator->fails()) {
            return back()
                ->withInput()
                ->withErrors($validator);
        }
        $link = new \App\Link;
        $link->title = $request->title;
        $link->url = $request->url;
        $link->description = $request->description;
        $link->save();
        return redirect('/');
    });
    
    This route is a little more complicated than the others. First, we are injecting the Illuminate\Http\Request which will hold all of the POST data. Then, we create a new Validator instance with our rules. If this validation fails, it returns the user back with the original input data and with the validator errors.
    Finally, if everything passed validation, we use the “App::Link” model to add the data.

    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 you gain the skills you need to build 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.
    Join the weekly newsletter and check out the Laravel tutorials section of the site to go deeper and learn even more about the framework.

    No comments:

    Post a Comment