Vous êtes sur la page 1sur 28

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 is 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. Ill 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 Id code it out.
Others prefer to write a project plan in a text file, wiki, or some mind
mapping tool. It doesnt 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.

Lets get started building all this out.

The First Steps


With a simple plan of attack outlined, its 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. Ive 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 Laravels 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 dont have to worry about it messing with any of our code.

With the basics setup and working its time to start doing some coding.

Building a List of Links


If you start thinking about the whole finished project, its easy to get
overwhelmed. The best way to fight this is to break everything down
into small tasks. So, lets 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 lets 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 automatically add data
to the table:

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 lets 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)

<li>{{ $link->title }}</li>

@endforeach

If you refresh your browser, you should now see the list of all the links
added. With that all set, lets 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 Im building
in my head. Here is a simple drawing of this form:
Since weve 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')

<div 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, lets create a route to handle the POST data and do our
validation. Lets create that route and add our validation rules in:
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 complex 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.

https://laravel-news.com/your-first-laravel-application
Creating a Basic Laravel 5
MVC Application in 10
Minutes
by Alex Coleman | Laravel, PHP, Web App, Web Development
This is a free resource from my online course, From Idea To Launch, where I teach you the
skills you need to become a Professional PHP Web Developer. Learn more

Laravel applications follow the traditional Model-View-Controller design pattern, where


you use:

Controllers to handle user requests and retrieve data, by leveraging Models


Models to interact with your database and retrieve your objects information
Views to render pages

Additionally, routes are used to map URLs to designated controller actions, as shown
below.
The full MVC request cycle in a Laravel 5 application

So

A request is made say, when a user enters a URL associated with your
application.
A route associated with that URL maps the URL to a controller action.
That controller action leverages the necessary model(s) to retrieve information
from the database, and then passes that data off to a view.
And that view renders the final page.

I like to say that an MVC application is a lot like playing with Legos.

And building one using Laravel 5 is a breeze.

Building a sample application


For the sake of demonstration, Im going to walk you through the process of building the
start of a sample Laravel 5 application with all the MVC components a model, a view,
and a controller.

So, lets say you wanted to build an application dealing with cars

The Model
Well start by creating a model, to represent a Car.

Laravel comes with a fantastic, built-in command line interface, the Artisan CLI, which
provides you with a bunch of useful commands to help you build your application.

So, fire up your command line (and connect to your Homestead virtual machine, if youre
using Laravel Homestead), move into your applications main directory, and run the
following command to generate a new Car model:
$ php artisan make:model Car --migration

Models are all stored in the main app directory, so that command will generate
an app/Car.php model file with the following code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model


{

//

Due to Laravels built-in model functionality, just by creating an empty model class,
Laravel will assume that this model is associated with a database table named cars.

And, actually, by supplying that --migration option when generating the model,
Laravel also generated a database migration file for creating that cars database table.
The migration file is located at [timestamp]_create_cars_table.php and
contains the following code:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCarsTable extends Migration
{

/**
* Run the migrations.
*
* @return void

*/
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void

*/
public function down()
{
Schema::drop('cars');
}
}

(If youre unfamiliar with the concept of database migrations, read more about how
Laravel uses database migrations to help you manage your database from directly within
your application. Its awesome.)
All you have to do now is use Laravels Schema builder documentation to complete the
migration file. So you could define a few additional columns to, say, store the cars make,
model, and production date:

.
.
.
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('make');
$table->string('model');
$table->date('produced_on');
$table->timestamps();
});
.
.
.

And then you can run the migration to create the cars table using the following Artisan
command:

$ php artisan migrate

With the database-related items addressed, we can now move on to create a controller.

Note: For the sake of testing, at this point, I just manually added an entry to the cars database
table.

The Controller
In Laravel, a type of object such as a Car, in this case is referred to as a resource.
Since its so common to build applications around resources, you can generate a resource
controller a controller to handle all requests related to a resource using another
simple Artisan command:

$ php artisan make:controller CarController

That will generate an app/Http/Controllers/CarController.php controller


file with the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class CarController extends Controller


{

/**
* Display a listing of the resource.
*
* @return Response

*/
public function index()
{

//
}

/**
* Show the form for creating a new resource.
*
* @return Response

*/
public function create()
{

//

/**
* Store a newly created resource in storage.
*
* @return Response

*/
public function store()
{

//

}
/**
* Display the specified resource.
*
* @param int $id
* @return Response

*/
public function show($id)
{

//

/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response

*/
public function edit($id)
{

//

/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response

*/
public function update($id)
{

//

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response

*/
public function destroy($id)
{

//

}
}

Note that it automatically generates a controller with all of the typical CRUD actions.

Now, we just need to define routes to associate URLs with all these controller actions.
The Routes
Again, since this is such a common scenario, you can define a single resource route,
which creates routes for all of those resource controller actions.

In the routes configuration file app/Http/routes.php add the following to


define a Car resource route:

Route::resource('cars', 'CarController');

That single route definition will define all of the routes related to our Car resource:

Request Type Path Action Route Name

GET /cars index cars.index

GET /cars/create create cars.create

POST /cars store cars.store

GET /cars/{car} show cars.show

GET /cars/{car}/edit edit cars.edit

PUT/PATCH /cars/{car} update cars.update

DELETE /cars/{car} destroy cars.destroy

Now, for the sake of example, lets complete the implementation of the Show Car
page.
The Controllers show action
As per the previous table, the Show Car page will be accessible
at http://app.url/cars/{car}. In this case, the {car} will, in fact, be an id of
a car object in the database.

So, for example, the URL to view the car with an id of 1 would
be http://app.url/cars/1.

In order to implement the Show Car page, in the controllers show action, we need to:

1. Use the Car model to retrieve the designated Car object from the database.
2. Load a view for the Show Car page, and pass it the Car object retrieved from the
database.

First, in order to access the Car model in the controller, we need to add a
new use statement above the controller class:

.
.
.
use App\Car;

class CarController extends Controller


{
.
.
.

Then, we can complete the show action with the following code:

.
.
.
public function show($id)
{
$car = Car::find($id);
return view('cars.show', array('car' => $car));
}
.
.
.

When we visit car 1s URL http://app.url/cars/1 Laravel makes the 1 in


the URL accessible via the $id variable in the show function, shown above.

And retrieving the car object using the Car model is as easy as calling Car::find and
passing in that $id.

The view is then loaded using the view function and passing the name of the view
(which well create in a minute) and an array with the data to be supplied to the view.

Last, we need to create the show view.

The View and Completing the Page


Laravel view files are all stored in the resources/views folder. And they can be
organized into subfolders within that directory.

In the previous step, we passed the view function the view name cars.show. That
tells Laravel to look for a view file located in a subfolder named cars (within the
main resources/views directory) named show.blade.php.

Laravel view files utilize the Blade templating engine, and hence are
named .blade.php.
So, to finish the implementation of this Show Car page, we can create
the resources/views/cars/show.blade.php view file with the following
code:

<!DOCTYPE html>
<html>
<head>
<title>Car {{ $car->id }}</title>
</head>
<body>
<h1>Car {{ $car->id }}</h1>
<ul>
<li>Make: {{ $car->make }}</li>
<li>Model: {{ $car->model }}</li>
<li>Produced on: {{ $car->produced_on }}</li>
</ul>
</body>
</html>

Since we passed the Car object to the view back in the show action of the controller
with the array key car, we can access it in the view via a variable of the same
name, $car.

Objects retrieved via a model are instances of that model class.

And, as you can see, the Car objects values can be accessed using the same names as its
associated cars database tables column names.

Finally, you see the use of the Blade syntax for printing out information. The following,
for example, prints out the cars make:

{{ $car->make }}
That statement is simply translated into a pure PHP echo statement in the background:

<?php echo $car->make; ?>

But the Blade syntax makes writing views much faster and more enjoyable, and reading
them much easier.

The Start of a Full MVC Web App in Just


10 Minutes
And there you have it!

That is how quickly, and easily, you can build a MVC web application using Laravel 5.

With the combination of the Artisan CLI commands and the built-in functionality
provided, building Laravel applications is both fast and fun.