Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
front
Create route
Create controller to handle route
Create page to be fetched
Routes
Requests
$name = Request::input('name', 'Sally');
if (Request::has('name'))
$input = Request::all();
$input = Request::only('username', 'password');
$input = Request::except('credit_card');
$input = Request::input('products.0.name'); // array
Request::flashOnly('username', 'email');
Request::flashExcept('password');
return redirect('form')->withInput() = redirect('form')+ Request::flash();
return redirect('form')->withInput(Request::except('password'));
{{ old('username') }
$username = Request::old('username');
$value = Request::cookie('name');
$file = Request::file('photo');
if (Request::hasFile('photo')
if (Request::file('photo')->isValid()
Request::file('photo')->move($destinationPath)
Request::file('photo')->move($destinationPath, $fileName)
Redirects
return redirect('user/login');
return redirect()->back();
return redirect()->back()->withInput();
return redirect()->route('login');
Migrations
//
Column types
increments('id'), timestamp('added_on'), timestamps(),string('email'), string('name', 100),
text('description'), unsignedInteger('votes'), softDeletes(),integer('votes'),
float('amount', 8, 2), double('column', 15, 8), decimal('amount', 5, 2)
Boolean,
modifiers
default($value), unsigned(),
indexes
primary('id'), primary(['first', 'last']),
unique('email'), unique('state', 'my_index_name'),
index('state')
foreign key
$table->foreign('user_id')->references('id')->on('users')
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
Seeding
make:seeder UsersTableSeeder
run db:seed to seed or php artisan migrate:refresh --seed
Factories
$users = factory(App\User::class, 1000)->create();
factory(App\User::class, 'admin', 10)->create();
factory(App\User::class, 'admin')->create();
base
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'username' => $faker->userName,
'email' => $faker->email,
'name' => $faker->name
];
});
base with differences
$factory->defineAs(App\User::class, 'admin', function ($faker) use ($factory) {
$post = $factory->raw('App\User');
factory(App\User::class, 50)->create()->each(function($u) {
$u->posts()->save(factory(App\Post::class)->make());
});
];
});
$factory->state(App\User::class, 'delinquent', function ($faker) {
return [
'account_status' => 'delinquent',
];
});
$users = factory(App\User::class, 'admin', 3)->make();
$users = factory(App\User::class, 5)->states('premium', 'deliquent')>make();
My Fields
Faker\Factory::create() to create and initialize a faker generator,
DateTime
$faker->dateTimeBetween($startDate=Carbon\Carbon::now()->subMonths(3),
$endDate=Carbon\Carbon::now()->addMonths(1));
Internet
safeEmail
$faker->userName;
$faker->password;
Text
text($maxNbChars = 200)
sentence($nbWords = 6, $variableNbWords = true)
realText($maxNbChars = 200, $indexSize = 2)
Person
name($gender = null|'male'|'female')
// 'Dr. Zane Stroman'
firstName($gender = null|'male'|'female') // 'Maynard'
firstNameMale
// 'Maynard'
firstNameFemale
// 'Rachel'
lastName
// 'Zulauf'
Common fields
//address
$faker->address;
$faker->streetName;
$faker->streetAddress;
$faker->postCode;
$faker->address;
$faker->country;
//company
$faker->company;
//payment
$faker->creditCardType;
$faker->creditCardNumber;
Models
// make:model
php artisan make:model Issues m
creates table issues m option creates corresponding migration
Fields
//protected $fillable = [name,type,danger_level]
//protected $table = fish
// public function bear() {
return $this->belongsTo('Bear');
}
//
Scope
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
Rels
One to one
public function phone()
{
return $this->hasOne('App\Phone');
}
public function user()
{
return $this->belongsTo('App\User');
}
$phone = User::find(1)->phone;
One to many
public function comments()
{
return $this->hasMany('App\Comment');
}
public function post()
{
return $this->belongsTo('App\Post');
}
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
//
}
$comments = App\Post::find(1)->comments()->where('title', 'foo')->first();
Many to many
public function roles()
{
return $this->belongsToMany('Role', 'users_roles', 'user_id',
'role_id
);
}
public function users()
{
return $this->belongsToMany('Role', 'users_roles', 'user_id',
'role_id
);
}
$user = App\User::find(1);
foreach ($user->roles as $role) {
//
}
$roles = App\User::find(1)->roles()->orderBy('name')->get();
Eloquent
$flights = App\Flight::all();
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
toArray(),
findMany,
updateOrCreate(array $attributes, array $values = array())
first(array $columns = array('*'))
value(string $column)
Insert
Save($array)
App\Category::create(array('name' => 'Music'));
staticforceCreate,
Update
Update($attributesArray,$optionsArray)
Validation
Direct
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
Using Requests
php artisan make:request CreateArticleRequest
authorise method
public function authorize()
{
$comment = Comment::find($this->route('comment'));
return $comment && $this->user()->can('update', $comment);
Rules method
rules allowed
required ,
Messagebag
if ($errors->has('email')) {
//
}
$errors->first('email');
foreach ($errors->get('email') as $message) {
//
}
Authentication
Auth class
Check,user,guest
Auth::attempt(array $credentials = array(), $remember = false)
Auth::login(UserInterface $user, $remember = false)
Auth::logout()
Authorisation
Gates
In the authserviceprovider class
public function boot()
{
$this->registerPolicies();
Gate::define('update-post', function ($user, $post) {
return $user->id == $post->user_id;
});
}
Usage
if (Gate::allows('update-post', $post)) {
// The current user can update the post...
}
Policies
php artisan make:policy PostPolicy or
php artisan make:policy PostPolicy --model=Post
Usage
Model based
if ($user->can('update', $post)) {
//
}
if ($user->can('create', Post::class)) {
// Executes the "create" method on the relevant policy...
}
Using middleware
Route::put('/post/{post}', function (Post $post) {
// The current user may update the post...
})->middleware('can:update,post');
Route::post('/post', function () {
// The current user may create posts...
})->middleware('can:create,App\Post');
Controllers
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// The current user can update the blog post...
}
$this->authorize('create', Post::class);
Querybuilder
Query
$users = DB::table('users')->get();
$user = DB::table('users')->where('name', 'John')->first();
$email = DB::table('users')->where('name', 'John')->value('email');
$titles = DB::table('roles')->pluck('title');
$roles = DB::table('roles')->pluck('title', 'name');
Where(col,<=,val)
Max,count,min,avg,sum
//whereNotNull
->orderBy('name', 'desc')
->groupBy('account_id')
->having('account_id', '>', 100)
Inserts
DB::table('users')->insert([
['email' => 'taylor@example.com', 'votes' => 0],
['email' => 'dayle@example.com', 'votes' => 0]
]);
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);
Update
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);
Delete
DB::table('users')->where('votes', '>', 100)->delete();
Misc
DB::table('users')->increment('votes', 5);
DB::table('users')->increment('votes', 1, ['name' => 'John']);
Controllers
Blade
Hello, {{ $name }}. //escaped
{!! $name !!} //unescaped
{{ $name or 'Default' }}
CONDITIONALS
@if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
I don't have any records!
@unless (Auth::check())
You are not signed in.
@endunless
loops
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach
@forelse($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
@while (true)
<p>I'm looping forever.</p>
@endwhile
Carbon
Instantiation
$now = Carbon::now();
datetime
$carbon = Carbon::instance($dt);
Addition Subtraction
$dt->addYears(5);
$dt->addYear();
$dt->subYear();
$dt->subYears(5);
$dt->addMonths(60);
$dt->addDays(29);
$dt->addWeekdays(4);
$dt->addHours(24);
$dt->addMinutes(61);
$dt->addSeconds(61);
->startOfDay();
->endOfDay():
Comparison
$first->eq($second)
Ne,gt,gte,lt,lte
String Formatting
$dt = Carbon::create(1975, 12, 25, 14, 15, 16);
var_dump($dt->toDateTimeString() == $dt);
__toString()
echo $dt->toDateString();
echo $dt->toFormattedDateString();
echo $dt->toTimeString();
echo $dt->toDateTimeString();
echo $dt->toDayDateTimeString();
2:15 PM
// ... of course format() is still available
echo $dt->format('l jS \\of F Y h:i:s A');
December 1975 02:15:16 PM
Collections
toArray
implode(separator)
get(key)
1975-12-25
Dec 25, 1975
14:15:16
1975-12-25 14:15:16
Thu, Dec 25, 1975
// Thursday 25th of
File Handling
The local driver
Storage::disk('local')->put('file.txt', 'Contents');
$contents = Storage::get('file.jpg');
Check existence
$exists = Storage::disk('s3')->exists('file.jpg');
Storage::prepend('file.log', 'Prepended Text');
Storage::append('file.log', 'Appended Text');
Storage::copy('old/file1.jpg', 'new/file1.jpg');
Storage::move('old/file1.jpg', 'new/file1.jpg');
Commands
php artisan make:command SendEmails
protected $signature = 'email:send {user}';
protected $description = 'Send drip e-mails to a user';
public function handle()
{
$this->drip->send(User::find($this->argument('user')));
}
Register Command
protected $commands = [
Commands\SendEmails::class
];
Arguments
Wrapped in curly braces eg protected $signature = 'email:send {user}';
optional
email:send {user?}
optional with default
email:send {user=foo}
Options
As a switch
protected $signature = 'email:send {user} {--queue}';
As a value
protected $signature = 'email:send {user} {--queue=}';
with default
email:send {user} {--queue=default}
Option shortcut
email:send {user} {--Q|queue}
array
email:send {user} {--id=*}
usage
Command i/o
$userId = $this->argument('user');
$arguments = $this->arguments();
$queueName = $this->option('queue');
$options = $this->options();
Confirmation
autocompletion
Multichoice
Output
line, info, comment, question and error
eg. $this->info('Display this on the screen');
table layouts
$headers = ['Name', 'Email'];
$users = App\User::all(['name', 'email'])->toArray();
$this->table($headers, $users);
Progress bar
$users = App\User::all();
$bar = $this->output->createProgressBar(count($users));
foreach ($users as $user) {
$this->performTask($user);
}
$bar->advance();
$bar->finish();
Arrays
str_split converts string to array
array array_map ( callable $callback , array $array1 [, array $... ] )
Strings
strtolower("Hello WORLD.");
strlen("Hello world!");
echo strpos("Hello world!", "world");
string gettype ( mixed $var ) returns
Boolean,integer,double,string,array,object,NULL
switch (n) {
case label1:
code to be
break;
case label2:
code to be
break;
case label3:
code to be
break;
...
default:
code to be
}
executed if n=label1;
executed if n=label2;
executed if n=label3;