Sie sind auf Seite 1von 18

Laravel 5

Student's Script

Ivan Domazet, bacc.ing.comp.


Spain, December 2015.
Table of Contents:
Introducing Laravel 5 ....................................................................................................................... 3
Laravel History .............................................................................................................................. 3
Laravel - MVC Framework ............................................................................................................ 3
Building Our Website ....................................................................................................................... 4
Installing Laravel ........................................................................................................................... 4
Artisan .......................................................................................................................................... 4
Register And Login .......................................................................................................................... 5
Routes .......................................................................................................................................... 5
Controllers .................................................................................................................................... 6
Views ............................................................................................................................................ 8
Requests ...................................................................................................................................... 8
User ................................................................................................................................................. 9
Migration ....................................................................................................................................... 9
Model .......................................................................................................................................... 11
Joke ............................................................................................................................................... 12
Routes ........................................................................................................................................ 12
Controller .................................................................................................................................... 12
Request ...................................................................................................................................... 13
Migration ..................................................................................................................................... 14
Model .......................................................................................................................................... 14
Admin ............................................................................................................................................. 15
Routes ........................................................................................................................................ 15
User Controller............................................................................................................................ 16
User Request .............................................................................................................................. 17
Joke Controller ........................................................................................................................... 18

2
Introducing Laravel 5
Laravel 5 is an open source PHP framework, which is created by Taylor Otwell. Many developers
around the globe are using its beautiful, clean code to create their great web applications. You can
start to build a Laravel application within a few minutes! Its always a fun process. Laravel gives
you right tools and nice ideas to help you build your website faster, more stable and very easy to
maintain. Using Laravel, You can create a lot of things! From simple blogs to nice CMSs (Content
Management System), eCommerce solutions, large scale business applications, social websites
and more.

Laravel History
In 2011, Taylor Otwell, a great web developer has created an open source PHP framework, he
called it Laravel. For only just 2 years, many developers around the world have been developing
and using Laravel to build their applications. Laravel has come to version 5.1 today. It has many
features such as built in session management, database management, Composer, Eloquent ORM
and many more. Laravel is a full stack framework, it means that you can develop web application
completely from scratch using its amazing database wrapper called Eloquent ORM and its own
templating engine called Blade.

Many problems in the process of creating web application have been solved by Laravel. Laravel is
a great tool, a great time saver to help you build things faster and faster. There are many reasons
for using Laravel to develop web applications. One of the reasons is, Laravel has a welcoming and
supportive community. Unlike Symfony or Zend framework, you can easily find many code
snippets, tutorials, courses about Laravel. Even though the Laravel 5 has just been released a few
months ago.

Laravel is not only Taylor Otwells product. Its the product of a big community. Its an open source
framework, thus hundred developers worldwide have been providing many new features, bug
fixes, ideas. You can easily ask questions in the community forum, or through Laravel IRC
channel. If youre a mobile developer, you find a right way to develop your web backend
application. Laravel supports JSON very well.

The syntax of Laravel is very clean and easy to follow. The methods, functions are well defined.
Sometimes you can even guess them without looking at the documentation. You can also create
your own rules, your own way to write your code. Laravel gives you a lot of freedom. You can also
maintain your code or upgrade it to a new version easily.

Laravel - MVC Framework


MVC (Model-View-Controller) pattern is very popular and many developers are using it for their
application today. Laravel also loves the MVC. You can find folders called models-views-
controllers inside Laravel. If you dont know about MVC, Laravel will help you to master it easily by
just developing application with it.

MVC is a architecture pattern that enforces seperation between models (information), controller
(users interaction) and view (models display). Simply put, it helps to seperate your applications to
many small parts in an organized structure. The main benefits of using MVC pattern is that, it
helps you to change, extend and maitain your applications easily.

3
Building Our Website
Were going to build a small website while were learning some Laravel basic stuffs. Getting start
with some PHP frameworks could be a painful process with a steep learning curve. However, you
will feel that its very easy to begin with Laravel. This script will teach you to create your web
application with Laravel. You will learn how to use Composer, Artisan, Laravel application
structure and some Laravel features such as: routing, templating, database operations and many
more.

Installing Laravel
Install Laravel on Windows is a piece of cake! You can install it easily using XAMPP.

XAMPP is a free and open source cross-platform web server solution stack package developed by
Apache Friends, consisting mainly of the Apache HTTP Server, MySQL database,
and interpreters for scripts written in the PHP and Perl programming languages.

Now go to Composer site, download and install Composer-Setup.exe.

Laravel 5 consists of many components that are put together automatically into the framework
through Composer. Using Composer, you can easily specify which other PHP libraries are used in
your code, initiate installation and update of those dependencies through the command line.

Now you can install Laravel. Install Via Composer Create-Project:


open command prompt and navigate to htdocs
type composer create-project laravel/laravel

Good job, you have just installed Laravel. You can open your web browser and go to your site at
this address: http://localhost/laravel/public

Artisan
Laravel comes with a command line interface called Artisan. We can use Artison to execute
repetitive tasks. For example we can launch development server, create models, and run
database migrations. You can run Artisan command through your system command line. You
need to navigate to your application folder to run Artisan.

4
Register And Login
By default, no routes are included to point requests to the authentication controllers. You may
manually add them to your app/Http/routes.php file. We will together create authentication
controller which is located in the App\Http\Controllers\Auth namespace.
The AuthController handles new user registration and authentication. We will need to provide
views that this controllers can render. The views should be placed in the resources/views/auth
directory. You are free to customize these views however you wish. The login view should be
placed at resources/views/auth/login.blade.php, and the registration view should be placed at
resources/views/auth/register.blade.php.

Routes
Each website has certain endpoints that are reachable by typing a URL in your web browser
address bar. For example, when you type google.com, you will go to Googles home page. If you
type google.com/mail, you will go to Gmail!

Laravel called it "routes". Usually, we will have the home page (or index page) at a root route: "/" :
root route, applications home page. We can go to app/Http/routes.php to modify applications
routes. So lets go to our laravel app and Http folder, find routes.php, open it with your text editor
and define register and login routes:

Route::get('/', function () {

return redirect('/login');

});

// Auth routes

Route::group(['namespace' => 'Auth'], function()

Route::get('/register', 'AuthController@getRegister');

Route::post('/register', 'AuthController@postRegister');

Route::get('/login', 'AuthController@getLogin');

Route::post('/login', 'AuthController@postLogin');

Route::get('/logout', 'AuthController@getLogout');

});

5
Controllers
Instead of defining all of your request handling logic in a single routes.php file, you may wish to
organize this behavior using Controller classes. Controllers can group related HTTP request
handling logic into a class. Controllers are typically stored in the app/Http/Controllers directory.

o open app/Http/Controllers/Auth/AuthController or create one if you don't have it


o write methods for login, register and logout:

public function getLogin() {

return view('auth.login');

public function postLogin(LoginRequest $request) {

$email = $request->get('email');

$password = $request->get('password');

if (Auth::attempt(['email' => $email, 'password' => $password])) {

// Check if user is admin

if(Auth::user()->is_admin) {

return Redirect::to('/admin/dashboard');

else {

// If not admin redirect to jokes

return Redirect::to('/jokes');

else {

$message = 'Wrong email and/or password!';

// Login view with error message

return view('auth.login', compact('message'));

6
public function getRegister() {

return view('auth.register');

public function postRegister(RegisterRequest $request) {

$user = new User;

$user->first_name = $request->get('first_name');

$user->last_name = $request->get('last_name');

$user->email = $request->get('email');

$user->password = bcrypt($request->get('password'));

$user->save();

return Redirect::to('/login');

public function getLogout() {

// Logout current user

Auth::logout();

// Back to login screen

return Redirect::to('/login');

7
Views
Laravel comes with a poweful templating engine called Blade. If you know HTML, you can use
Blade easily. Blade looks like plain HTML, but Taylor Otwell has added some special statements
into it to make it output PHP data, loops, use different layouts and many more.

Every Blade file ends with .blade.php. You can find the templates in resources/views directory.
The best feature of Blade is an ability to use a template for all the pages of our web application.
For example, you can create a main menu in a master template, and then use it for all your pages.
We will build a master template, which allows us to keep common elements for our pages.

o open resources/views/templates/auth-master.blade.php file


o open resources/views/auth/ login.blade.php file
o open resources/views/auth/ register.blade.php file
o check all views
o ask if there's anything you don't understand

Requests
We need to apply validation to the form to ensure that the data entered by users is valid. If we
dont check, the data could be bad, and it could cause severe problems to our application or even
a security vulnerability. Laravel provides us a set of validation rules, and some methods to apply
validation easily:
o register request create with php artisan make:request RegisterRequest
o open app/Http/Requests/RegisterRequest and modified it

public function authorize() {

return true;

public function rules() {

return [

'first_name' => 'required|min:3',

'last_name' => 'required|min:3',

'email' => 'required|email',

'password' => 'required|min:6'

];

o login request create with php artisan make:request LoginRequest


o open app/Http/Requests/LoginRequest and modified it as RegisterRequest

8
User
Laravel has introduced Eloquent ORM to allow developers use Active Record pattern.
Active Record pattern is a technique of wrapping database into objects. By using this technique,
developers can present data stored in a database table as class, and row as an object. Each database table has
a corresponding Model which is used to interact with that table.
It helps to make our codes look cleaner and readable. We can use Eloquent ORM to create, edit,
manipulate, query and delete entries easily. More than that, Eloquent ORM has built in relationships, which
allow us to not only manipulate one table in the database, but also we can be able to manipulate all related
data.

Migration
Laravel supports many database platforms and we can choose any of them to develop our
applications: MySQL, SQLite, PostgreSQL, SQL Server. In our web site, we will use MySQL,
which is one of the most popular and free platforms for development. To configure our database,
lets go to config folder, open database.php file and take a look at.

Let's create database for our web site. Open phpMyAdmin (open browser and type
localhost/phpmyadmin). Create database laravel (new->laravel; collaction: utf8_bin).

For our purposes we will use the local environment and we will fill in the data for the database in
.env file. Create .env file with following data:

APP_ENV=local
APP_DEBUG=true
APP_KEY=Koie24iZhlGBChBig14itkujIAmMxUhH

DB_HOST=localhost
DB_DATABASE=laravel
DB_USERNAME='root'
DB_PASSWORD='' (empty string)

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

Database is not simple. It has its own structure, different types, relationships and syntax. In order
to follow along this chapter easily, you need a basic understanding of SQL. At least, you should
know the concept of a database, how to read, update, modify and delete it.

Before doing anything with our database, we need to create and define its structure. Laravel has
a class, called Schema. This class can be used to manipulate database tables. The great thing is,
it works with all database platforms. Before using Schema class, we have to create migrations.

Migrations are like version control for our database, allowing a team to easily modify and share the
application's database schema. Migrations are typically paired with Laravel's schema builder to
easily build your application's database schema.

o create user migration with php artisan make:migration create_table_users


o write migration using schema

9
public function up()

Schema::create('users', function($table)

$table->increments('id');

$table->string('first_name');

$table->string('last_name');

$table->string('email');

$table->string('password');

$table->boolean('is_admin')->default(0);

$table->timestamps();

$table->softDeletes();

$table->rememberToken();

$table->unique('email');

});

public function down()

Schema::drop('users');

o Run migration with php artisan migrate

10
Model
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord
implementation for working with your database. Each database table has a corresponding "Model"
which is used to interact with that table. Models allow you to query for data in your tables, as well
as insert new records into the table. Models are placed in the app folder.

o delete all models which have come with laravel installation


o create User model with php artisan make:model User
o add following code to User model

use Illuminate\Auth\Authenticatable;

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model implements AuthenticatableContract

use Authenticatable, SoftDeletes;

protected $table = 'users';

protected $guarded = [];

protected $dates = ['deleted_at'];

public function jokes()

return $this->hasMany('App\Joke);

11
Joke
We will create routes, controller, views, request, migration and model so registered user can add
and read jokes.

Routes
Let's define joke routes on same way as register and login routes.
Open app/Http/routes.php and add the following code:

// Joke routes

Route::group(['namespace' => 'Joke', 'middleware' => 'auth'], function()

Route::get('/jokes', 'JokeController@getJokes');

Route::get('/add-joke', 'JokeController@getAddJoke');

Route::post('/add-joke', 'JokeController@postAddJoke');

});

We added route which shows all the jokes, route which shows form through we can add new jokes
and route which sends form data to server.

Controller
We put all the activities, that are related to a joke to the JokeController. In fact, we can name the
Controller whatever you like, such as: Jokes, JokeControl, etc. Laravel automatically detects what
we try to do when our controller extends Controller or BaseController. However, its a naming
convention that many developers use, so we should follow it. In app/Http/Controllers folder create
Joke folder. Inside Joke folder create JokeController.
Now, its time to add more pages:

public function getJokes() {

$jokes = Joke::with('user')->orderBy('created_at', 'desc')->paginate(6);

$jokes->setPath('jokes');

return view('jokes.list', compact('jokes'));


}

public function getAddJoke() {

return view('jokes.input');
}

12
public function postAddJoke(AddJokeRequest $request) {

$joke = new Joke;


$joke->text = $request->get('joke');
$joke->user_id = Auth::user()->id;
$joke->save();

return Redirect::to('/jokes');
}

We have created other pages by implementing some new Controller actions for our application.
Those pages will be used to display all the jokes and form to add jokes.

Request
We need to apply validation to the form to ensure that the data entered by users is valid, the same
as for the login and register forms.

o joke request create with php artisan make:request AddJokeRequest


o open app/Http/Requests/AddJokeRequest and modified it

public function authorize()


{
return true;
}

public function rules()


{
return [
'joke' => 'required'
];
}

13
Migration
We have to create jokes table in our laravel database so we can store all jokes.

o create joke migration with php artisan make:migration create_table_jokes


o write migration using schema

public function up()


{
Schema::create(jokes, function($table)
{
$table->increments('id');
$table->text('text');
$table->timestamps();
$table->softDeletes();

$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}

public function down()


{
Schema::drop(jokes);
}

o Run migration with php artisan migrate

Model
o create Joke model with php artisan make:model Joke
o add following code to Joke model

use Illuminate\Database\Eloquent\SoftDeletes;

class Joke extends Model


{
use SoftDeletes;

protected $table = jokes;


protected $guarded = [];
protected $dates = ['deleted_at'];

public function user()


{
return $this->belongsTo('App\User');
}
}

14
Admin
We will create an administrative interface so administrator can edit and delete users, and can view
details about jokes and delete them.

Routes
Let's define admin routes on same way as joke routes.
Open app/Http/routes.php and add the following code:

// Admin Routes
Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'middleware' => 'AdminAuth'],
function()
{
// Dashboard
Route::get('/dashboard', function() {
return view('admin.dashboard');
});

// User routes
Route::get('/users', 'UserController@getUsers');
Route::get('/user/{id}/edit', 'UserController@getEditUser');
Route::get('/user/{id}/delete', 'UserController@getDeleteUser');
Route::post('/user/{id}/edit', 'UserController@postEditUser');

// Joke Routes
Route::get('/jokes', 'JokeController@getJokes');
Route::get('/joke/{id}/details', 'JokeController@getJokeDetails');
Route::get('/joke/{id}/delete', 'JokeController@getDeleteJoke');
});

Route groups allow you to share route attributes, such as middleware or namespaces, across a
large number of routes without needing to define those attributes on each individual route. Shared
attributes are specified in an array format as the first parameter to the Route::groupmethod.

To assign middleware to all routes within a group, you may use the middleware key in the group
attribute array. Another common use-case for route groups is assigning the same PHP
namespace to a group of controllers. You may use the namespace parameter in your group
attribute array to specify the namespace for all controllers within the group.

Remember, by default, the RouteServiceProvider includes your routes.php file within a namespace
group, allowing you to register controller routes without specifying the
fullApp\Http\Controllers namespace prefix. So, we only need to specify the portion of the
namespace that comes after the base App\Http\Controllers namespace root.

The prefix group array attribute may be used to prefix each route in the group with a given URI.

15
User Controller
In app/Http/Controllers folder create Admin folder. Inside Admin folder create UserController file.
UserController file contains four actions:

Show all the users


Show details about single user
Edit existing user
Delete the user

Open UserController file and add following four actions:

public function getUsers() {

$users = User::orderBy('created_at', 'desc')->paginate(6);

return view('admin.users.list', compact('users'));


}

public function getEditUser($id) {

$user = User::find($id);

return view('admin.users.input', compact('user'));


}

public function postEditUser($id, EditUserRequest $request) {

$user = User::find($id);
$user->first_name = $request->get('first_name');
$user->last_name = $request->get('last_name');
$user->email = $request->get('email');
if($request->has('password')) {
$user->password = $request->get('password');
}
$user->save();

return Redirect::to('admin/users');

public function getDeleteUser($id) {

$user = User::find($id);

$user->delete();

return Redirect::to('admin/users');
}

16
User Request
We need to apply validation to the form to ensure that the data entered by users is valid, the same
as for the login and register forms.

o open app/Http/Requests folder and create EditUserRequest file


o open app/Http/Requests/Admin/EditUserRequest and modified it

<?php

namespace App\Http\Requests\Admin;

use App\Http\Requests\Request;

class EditUserRequest extends Request


{

public function authorize()


{
return true;
}

public function rules()


{
return [
'first_name' => 'required|min:3',
'last_name' => 'required|min:3',
'email' => 'required|email'
];
}
}

17
Joke Controller
Inside Admin folder create JokeController file. JokeController file contains three actions:

Show all the jokes


Show details about single joke
Delete the joke

Open JokeController file and add following three actions:

public function getJokes() {

$jokes = Joke::with('user')->orderBy('created_at', 'desc')->paginate(6);

return view('admin.jokes.list', compact('jokes'));


}

public function getJokeDetails($id) {

$joke = Joke::where('id', $id)->with('user')->first();

return view('admin.jokes.input', compact('joke'));


}

public function getDeleteJoke($id) {

$joke = Joke::find($id);

$joke->delete();

return Redirect::to('admin/jokes');
}

18

Das könnte Ihnen auch gefallen