Sei sulla pagina 1di 15

Workflow

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
//

php artisan make:migration create_users_table --create=users

Running the migration


php artisan migrate

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

Add this to DatabaseSeeder class


public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(PostsTableSeeder::class);
$this->call(CommentsTableSeeder::class);
}

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');

return array_merge($post, ['admin' => true]);


});

factory(App\User::class, 50)->create()->each(function($u) {
$u->posts()->save(factory(App\Post::class)->make());
});

Factory with relationships


$factory->define(App\Post::class, function ($faker) {
return [
'title' => $faker->title,
'content' => $faker->paragraph,
'user_id' => function () {
return factory(App\User::class)->create()->id;
}

];
});
$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');
}

//

Setters And Getters


public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);

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

the request class

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...
}

Nb user is added automatically

Policies
php artisan make:policy PostPolicy or
php artisan make:policy PostPolicy --model=Post

In the authserviceprovider class


protected $policies = [
Post::class => PostPolicy::class,
];

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

Eg. $price = DB::table('orders')


->where('finalized', 1)
->avg('price');
$users = DB::table('users')->select('name', 'email as user_email')->get();
$users = DB::table('users')->distinct()->get();
//orWhere orWhere('name', 'John')
->whereBetween('votes', [1, 100])->get();
->whereIn('id', [1, 2, 3])
->whereNull('updated_at')

//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);

Carbon::createFromDate($year, $month, $day, $tz);


Carbon::createFromTime($hour, $minute, $second, $tz);
Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

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)

// bool(true) => uses


//
//
//
//
//

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');

Stored relative to storage/app directory


Get a file

$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

php artisan email:send --id=1 --id=2


Descriptions
Eg. protected $signature = 'email:send
{user : The ID of the user}
{--queue= : Whether the job should be queued}';

Command i/o
$userId = $this->argument('user');
$arguments = $this->arguments();
$queueName = $this->option('queue');
$options = $this->options();

Ask for value

$name = $this->ask('What is your name?');


Ask for sensitive value
$password = $this->secret('What is the password?');

Confirmation

if ($this->confirm('Do you wish to continue? [y|N]'))

autocompletion

$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);

Multichoice

$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $default);

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;

executed if n is different from all labels;

Potrebbero piacerti anche