composer create-project laravel/laravel --prefer-dist PROJECT
```jo
This will setup a new laravel project in PROJECT subfolder of current folder, and set the encryption key.
## Development dependecies
Things that I find useful for development in every project.
After updatind composer.json always run:
composer update --dev
or, if out of memory error occurs:
php -dmemory_limit=1G /usr/local/Cellar/composer/1.0.0-alpha8/libexec/composer.phar update --dev
### Generators
Add following line to composer.json
"require-dev": {"way/generators": "2.*"}
Then, add this to app/config/app.php in the providers section:
'Way\Generators\GeneratorsServiceProvider'
### Phpunit, Faker and Mockery
"require-dev":{"phpunit/phpunit": "3.7.", "mockery/mockery": "dev-master@dev", "phpunit/phpunit": "3.7.", "fzaninotto/faker": "v1.3.0" }
## Database configuration
Add mySQL username/password for in app/config/database.php, and change database name into something more meaningful.
# Creating stuff
## Create migrations
Create a simple users table:
php artisan generate:migration create_users_table --fields="name:string, email:string, password:string, remember_token:string:nullable, is_admin:boolean"
Run all migrations:
php artisan migrate
## Create seeds
Create a seeder:
php artisan generate:seed users
Edit it using faker to fill values:
truncate();
$faker = Faker::create();
User::create(array('name'=> 'nikos', 'email' => 'nikolaos.zisimos@gmail.com', 'is_admin'=>true, 'password'=>Hash::make('nikos')));
foreach(range(1, 10) as $index)
{
$user = User::create(array(
'name' => $faker->userName,
'email' => $faker->email,
'is_admin' => false,
'password' => Hash::make($faker->userName)
));
}
}
}
```
Don't forget to add call to seeder class in DatabaseSeeder.php!
Run seeds:
```
php artisan db:seed
```
### Create model
```
php artisan model:make
```
### Create controller
```
php artisan controller:make FooController
```
### Create scaffolding
This will create all necessary files (migrations, views, resourceful controller with some boilerplate code).
```
php artisan generate:scaffold poem --fields="title:string, body:text, tweep: string"
```
# Views
## @if statement example
```
@if($item->is_enabled)
@else
@endif
```
## form input with class
```html
{{ Form::text('title', null, array('class' => 'whatever')) }}
```
## populate a select list from a model
```php
// in the controller
$my_select_items = MyModel::all()->lists('title', 'id');
// then pass it to the view
// then in the view
{{ Form::select('select_name', $my_select_items) }}
```
## multi select (chzn select)
```php
{{ Form::label('data[package][filtered_items]', 'Item Blacklist:', ['class' => 'control-label']) }}
```
## Forms
## Set a checkbox default
```
{{ Input::checkbox('my_checkbox', '1', $item->is_enabled) }}
```
### Signup form example
```
@section('content')
{{Form::open(array('url'=>'user','class'=>'form-signin', 'role'=>'form'))}}
{{Form::email('email', '', array('placeholder'=>'email', 'class'=>'form-control'))}}
{{$errors->first('email', '
@foreach($items as $item)
{{-- if package template is set, select this option *if* it's currently blacklisted for this package template --}}
filteredItems->contains($item->id) ? 'selected="selected"' : '') : '' }} >
{{ $item->title }}
@endforeach
:message
')}}
{{Form::text('name', '', array('placeholder'=>'name', 'class'=>'form-control'))}}
{{$errors->first('name', ':message
')}}
{{Form::password('password', array('placeholder'=>'password', 'class'=>'form-control'))}}
{{$errors->first('password', ':message
')}}
{{Form::password('password_confirmation', array('placeholder'=>'verify password', 'class'=>'form-control'))}}
{{$errors->first('password_confirmation', ':message
')}}
{{Form::submit('sign up', array('class'=>'btn btn-lg btn-primary btn-block'))}}
{{Form::close()}}
```
### Login form example
```
{{Form::open(array('class'=>'form-signin', 'role'=>'form'))}}
{{Form::email('email', '', array('placeholder'=>'email', 'class'=>'form-control'))}}
{{$errors->first('email', ':message
')}}
{{Form::password('password', array('placeholder'=>'password', 'class'=>'form-control'))}}
{{$errors->first('password', ':message
')}}
{{Form::checkbox('remember','1', false, array('class'=>'checkbox'))}}
{{Form::label('remember', 'Remember me')}}
{{Form::submit('login', array('class'=>'btn btn-lg btn-primary btn-block'))}}
{{Form::close()}}
```
# Validation
## Sign up form validation example
```
public function store()
{
$rules = ['email'=>['email', 'unique:users,email','required'], 'name'=>['required', 'alpha_dash', 'unique:users,name'], 'password'=>['required', 'digits_between:6,12'],
'password_confirmation'=>['required','same:password']];
$validation = Validator::make(Input::all(), $rules);
if($validation->fails()){
return Redirect::back()->withInput()->withErrors($validation->messages());
}
}
```
# Route tricks
## 404 if empty find result
with no extra lines of code!
```php
// will do App::abort(404) if no model found
$my_model = MyModel::findOrFail($id);
```
# Testing
## mock a collection so you can return it's contents _and_ mock a method call on it
```php
// in the test file
$mock_all = Mockery::mock('\Illuminate\Database\Eloquent\Collection');
$mock_all[0] = Mockery::mock('Einstein\MyElement\MyElementModelInterface');
$mock_all[0]->id = 1;
$mock_all[0]->title = 'whatever';
$mock_all[1] = Mockery::mock('Einstein\MyElement\MyElementModelInterface');
$mock_all[1]->id = 2;
$mock_all[1]->title = 'whatever';
MyElement::shouldReceive('all')
->once
->andReturn($mock_all);
// now you can add methods chained to all()
$mock_all::shouldReceive('lists')
->once()
->andReturn($something);
```
# Models
## Accessors
```php
/**
* sets the EffectiveDate into Y-m-d format
*
* @param datetime
*/
public function setEffectiveDateAttribute($effective_date)
{
if ($effective_date) {
$this->attributes['effective_date'] = date('Y-m-d', (strtotime($effective_date)));
} else {
$this->attributes['effective_date'] = null;
}
}
/**
* returns the EffectiveDate into m/d/Y format
*
* @param datetime
*/
public function getEffectiveDateAttribute()
{
$tmpdate = $this->attributes['effective_date'];
if ($tmpdate == "0000-00-00" || $tmpdate == "") {
return "";
} else {
return date('m/d/Y', strtotime($tmpdate));
}
}
```
# Relationships
# Relationships
##Join a table to itself
e.g. a category that can have a parent_id which is another category
```php
public function parent()
{
return Category::where('id', '=', $this->category_id)->first();
}
```
## belongsToMany(): many-to-many
*in the Employee model*
```php
class Employee extends Eloquent
{
public function employer()
{
// tracking happens in the pivot table
return $this->belongsToMany('EmployerNamespace\EmployerEloquentModel');
}
}
```
*in the Employer model*
```php
class Employer extends Eloquent
{
public function Employee()
{
// tracking happens in the pivot table
return $this->belongsToMany('EmployeeNamespace\EmployeeEloquentModel');
// You may override the conventional pivot *table_name* and foreign keys as follows
return $this->belongsToMany(
'EmployerNamespace\EmployerEloquentModel',
'employer_table_employee_table',
'employer_name',
'employee_name'
);
}
}
```
means that the foreign key fields *employer_id* and *employee_id* are defined in the *employers_table_employees_table* pivot table.
employees_table | |
---|---|
id | title, etc. |
employers_table_employees_table (pivot table) | ||
---|---|---|
id | employee_id (foreign key) | employer_id (foreign key) |
employers_table | |
---|---|
id | title, etc. |
owners_table | |
---|---|
id | title, etc. |
dogs_table | ||
---|---|---|
id | owner_id (foreign key) | title, etc. |