Laravel
A Framework For Web Artisans
Composer
Dependency Manager
Over 7000 Laravel-specific packages
composer.json
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"laravel/framework": "4.1.*",
"way/generators": "dev-master",
"twitter/bootstrap": "*",
"itsgoingd/clockwork": "1.*"
},
"require-dev": {
"mockery/mockery": "dev-master"
},
artisan cli
commands
key:generate Generate a secure application key.
# Seeding of the DB
db:seed
#Create a new resourceful controller
controller:make
# Migrations
migrate:install Create the Laravel migration table.
migrate:make Create a migration.
migrate Run outstanding migrations.
migrate:rollback Roll back the most recent migration.
migrate:reset Roll back all migrations.
generate
generate:controller Generate a new controller.
generate:form Dump form HTML for a model
generate:migration Generate a new migration.
generate:model Generate a new model.
generate:pivot Generate a pivot table
generate:resource Generate a resource.
generate:scaffold Generate scaffolding for a resource.
generate:seed Generate a seed file.
generate:test Generate a PHPUnit test class.
generate:view Generate a new view.
Command list
php artisan list
Every command has a description, defined inputs, etc.
Database
Schema Builder
Schema::create('posts', function($table)
{
$table->increments('id');
$table->string('title');
$table->string('tagline', 64); // constraint as second argument
$table->text('body');
$table->integer('category_id')
->unsigned() // chain methods for other options
->nullable(); // for optional fields
$table->softDeletes();
$table->timestamps();
});
Migrations
database version control
prefixed with timestamp
ordered alphabetically
good for teams / feature branching in git
seeding
Fills the database with sample data
Brilliant for development
Even better for Acceptance Testing
Eloquent
works with MySQL, PostgreSQL, SQLite, SQL Server
class Company extends Eloquent {}
$company = Company::create(array(
'address' => '155 Harbor Blvd',
'city' => 'Fullerton'
));
$company = Company::find(1);
echo $company->address; // 155 Harbor Blvd
$company = Company::where('city', "Fullerton")->first();
$companies = Company::orderBy('city', 'desc')->take(10)->get();
Pagination built in! Example:
$companies = Company::orderBy('city', 'desc')->paginate(10);
Chainable Relationships
function comments()
{
return $this->hasMany('Comment');
}
$post->comments()->where('user_id', $user->id)->get();
Dynamic properties:
$post->comments;
RELATIONSHIPS
One to One
class Company extends Eloquent {
public function salesperson()
{
return $this->hasOne('Salesperson');
}
}
$salesperson = Company::find(1)->salesperson->name;
Many to One
class Company extends Eloquent {
public function customers()
{
return $this->hasMany('Customer');
}
}
$customers = Company::find(1)->customers;
Many to Many + Polymorphic
Eager Loading
function friends()
{
return $this->belongsToMany('User');
}
User::with('friends')->get();
Blade
SYNTAX
PHP
<a href="<?php echo $post->link; ?>">
<?php echo $post->title; ?>
</a>
Blade
<a href="{{ $post->link }}">
{{ $post->title }}
</a>
BLADE
Control Statements
@if( $a > 3 )
{{ $a }} @endif
@foreach ($users as $user) <p>This is user {{ $user->id }}</p> @endforeach
Partials
@section('content')
<p>This is my body content.</p>
@stop
@yield('content')
helper
Form::open(); Form::text('username'); Form::password('password'); Form::checkbox('name', 'value', true); Form::file('image'); Form::select('size', array('L' => 'Large', 'S' => 'Small')); Form::submit('Click Me!'); Form::close();
Routing
Routes
Route::get('/posts/{post}', function($post)
{
return "Post title: $post!";
});
Passing parameters
Route Constraints
Route::get('user/{id}/{name}', function($id, $name)
{
//
})
->where(array('id' => '[0-9]+', 'name' => '[a-z]+'))
Controllers
Route::get('home', ['as' => 'home', 'uses' => 'SiteController@index']);
Route::controller('/', 'SiteController');
/* In SiteController.php */
public function getIndex() { return ''; }
public function postIndex() { return ''; }
Resource Controllers
Route::resource('post', 'PostController');
Filters
Route::get('create', array('before' => 'auth|csrf', function()
{
//
}));
Route Groups
Route::group(['prefix' => 'post'], function() {
Route::get('{post-slug}', function($post) { return 'the post'; });
Route::get('{post-slug}/edit', function($post) { return 'edit post'; });
Route::post('{post-slug}/edit', function($post) {
// Validate
// Save
return Redirect::route('blog.post');
});
});
Named Routes
Route::get('posts', ['as' => 'posts.list', function()
{
return 'list of posts';
}]);
Redirect::route('posts.list);
URL::route('posts.list');
URL::route('posts.show', ['post-slug' => $post->slug]);
Security
User logins, auth checks, secure hashing, password resets
all built in.
Authentication
$credentials = array(
'username' => 'example@gmail.com',
'password' => 'secret'
);
if (Auth::attempt($credentials))
{
return Redirect::to('user/profile');
}
Get user's info :
$email = Auth::user()->email;
Logout:
Auth::logout();
input
Session
cookie
Easy to manage, easy to use
example
$name = Input::get('name', 'Sally');
$input = Input::only('username', 'password'); $input = Input::except('credit_card');
$input = Input::get('products.0.name');
Session::put('key', 'value'); Session::flash('key', 'value'); $value = Session::get('key'); Session::forget('key'); Session::flush();
$value = Cookie::get('name');
$cookie = Cookie::forever('name', 'value');
Validation
$input = Input::all();
$rules = array(
'name' => 'required|min:3|max:32|alpha',
'age' => 'required|integer',
'image'=> 'image|max:1500',
'password' => 'confirmed'
);
$v = Validator::make($input, $rules);
if( $v->fails() ){
// code for validation failure :(
}else{
// code for validation success!
}
+ 14 more types(including RegEx)
Environments
bootstrap/start.php
$env = $app->detectEnvironment(array(
'local' => array('http://localhost*', '*.dev'),
'test' => array('http://test.mywebsite.com*'),
'production' => array('http://mywebsite.com*'),
));
add environment config files under app/config
app
- config
- test
- database.php
- session.php
- production
- database.php
...
Testing
Support for PHPUnit out of the box
Unit Testing
IOC Container
Dependancy Injection
Mockery
Example of a test:
$response = $this->call('GET', 'user/profile');
DOM crawler:
$this->assertCount(1, $crawler->filter('h1:contains("Hello World!")'));
Schedule
Laravel 4.0 - May 2013
Laravel 4.1 - Nov 2013
Laravel 4.2 - May 2014
Laravel 4.3 - Nov 2014
Conclusion
It encourages better coding
Utilizes the best PHP has to offer
Lightweight and crazy fast
Well designed API with great docs
Resource
http://laravel.comhttp://github.com/laravel/laravelhttp://docs.laravel.com http://forums.laravel.comhttp://builtwithlaravel.com - list of sites using Laravelhttp://laravel-tricks.com - tips and tricks for Laravel users
thanks!
Laravel 4 - PHP on Rails
By xfyuan
Laravel 4 - PHP on Rails
- 651