Favorit

Breaking News

Laravel Tutorial - Building List


Laravel - 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 by 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.

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
While you are working with test data, you can quickly apply the schema:

php artisan migrate: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:

php artisan make:model --factory Link
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.

Open the LinkFactory.php file and fill in the following:

<?php

use Faker\Generator as Faker;

/* @var Illuminate\Database\Eloquent\Factory $factory */

$factory->define(App\Link::class, function (Faker $faker) {
    return [
        'title' => substr($faker->sentence(2), 0, -1),
        'url' => $faker->url,
        'description' => $faker->paragraph,
    ];
});

We use the $faker->sentence() method to generate a title, and substr to remove the period at the end of the sentence.

Next, create the link seeder, so we can easily add demo data to the table:

php artisan make:seeder LinksTableSeeder
The make:seeder command generates a new database seeder class to seed our links table. Open the database/seeds/LinksTableSeeder.php file and add the following:

public function run()
{
    factory(App\Link::class, 5)->create();
}

In order to “activate” the LinksTableSeeder, we need to call it from the main database/seeds/DatabaseSeeder.php run method:

public function run()
{
    $this->call(LinksTableSeeder::class);
}

You can now run the migrations and seeds to add data to the table automatically. Using the migrate:fresh command, we can get a clean schema that applies all migrations and then seeds the database:

$ php artisan migrate:fresh --seed
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2017_11_03_023418_create_links_table
Migrated:  2017_11_03_023418_create_links_table
Seeding: LinksTableSeeder

Using the tinker shell you can start playing around with the model data:

>>> \App\Link::first();
=> App\Link {#747
     id: 1,
     title: "Aliquam quo pariatur",
     url: "https://gibson.com/consequuntur-consequatur-eius-expedita-maiores-quaerat-occaecati.html",
     description: "Temporibus eaque aspernatur...",
     created_at: "2017-11-04 05:35:45",
     updated_at: "2017-11-04 05:35:45",
   }
>>>

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:

Route::get('/', function () {
    $links = \App\Link::all();

    return view('welcome', ['links' => $links]);
});

The second argument can be an associative array of data, and the key ends up being the variable name in the template file.

You can also use a fluent API to define variables if you prefer:

// with()
return view('welcome')->with('links', $links);

// dynamic method to name the variable
return view('welcome')->withLinks($links);
Next, edit the welcome.blade.php file and add a simple foreach to show all the links:

@foreach ($links as $link)
    <a href="{{ $link->url }}">{{ $link->title }}</a>
@endforeach
Here’s what the welcome.blade.php HTML should look like:

<body>
    <div class="flex-center position-ref full-height">
        @if (Route::has('login'))
            <div class="top-right links">
                @auth
                    <a href="{{ url('/home') }}">Home</a>
                @else
                    <a href="{{ route('login') }}">Login</a>
                    <a href="{{ route('register') }}">Register</a>
                @endauth
            </div>
        @endif

        <div class="content">
            <div class="title m-b-md">
                Laravel
            </div>

            <div class="links">
                @foreach ($links as $link)
                    <a href="{{ $link->url }}">{{ $link->title }}</a>
                @endforeach
            </div>
        </div>
    </div>
</body>

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.

No comments