Laravel: Difference between revisions

From Adam Colton
Jump to navigation Jump to search
 
(44 intermediate revisions by the same user not shown)
Line 11: Line 11:
[https://laracasts.com/series/whats-new-in-laravel-5-2/episodes/3?autoplay Video]
[https://laracasts.com/series/whats-new-in-laravel-5-2/episodes/3?autoplay Video]
   php artisan make:auth
   php artisan make:auth
Creates a bunch of views, routes and adds a controller.
Creates auth stufff.


== Email ==
== Email ==
Line 33: Line 33:
   $input = Request::all();
   $input = Request::all();
   SomeModel::create($input);
   SomeModel::create($input);
== Controller ==
  php artisan make:controller Name
  php artisan make:controller Name --resource
See [https://laravel.com/docs/5.0/controllers#restful-resource-controllers Restful controllers]


== Eloquent ==
== Eloquent ==
Line 39: Line 45:
* $fillable: which fields can be assigned
* $fillable: which fields can be assigned
* $dates: an array of fields that will be treated as Carbon dates
* $dates: an array of fields that will be treated as Carbon dates
=== Artisan ===
  php artisan make:model User --migration


=== Accessors and Mutators ===
=== Accessors and Mutators ===
Line 49: Line 58:


=== Relationships ===
=== Relationships ===
One-to-one
  //in the one being referenced
  public function users(){
    return $this->hasOne('App\Author');
  }
 
  //in the one referencing
  public function author(){
    return $this->belongsTo('App\User');
  }
One-to-many (author to article)
One-to-many (author to article)
   //in the 'one' (author)
   //in the 'one' (author)
Line 57: Line 77:
   //in the 'many' (article)
   //in the 'many' (article)
   public function author(){
   public function author(){
     return $this->belongsTo('App\user');
     return $this->belongsTo('App\User');
   }
   }


Line 64: Line 84:
     return $this->belongsToMany('article');
     return $this->belongsToMany('article');
   }
   }
The many to many can handle insert/delete diffs with ->sync().
To check if one exists from the other
  $author->articles->contains('title', 'Intro to PHP');
==== Querying ====
  $activeClients = App\Organization::whereHas('tags', function($query){
    $query->where('tag','Active Client');
  })->get();
The closure function attaches methods to the sub query.
  Products::whereIn('id', function($query){
    $query->select('paper_type_id')
    ->from(with(new ProductCategory)->getTable())
    ->whereIn('category_id', ['223', '15'])
    ->where('active', 1);
  })->get();
  Model::lists(value, key);
Key is optional. Both key and value are column names. Returns an array. Very useful for selects.


== Form Requests ==
== Form Requests ==
   php artisan make:requestion NameOfRequest
   php artisan make:request NameOfRequest
Starts with the methods authorize and rules.
Starts with the methods authorize and rules.


Line 112: Line 153:
All methods have the same args $request and $next and the continue by calling $next($request);
All methods have the same args $request and $next and the continue by calling $next($request);


In http/Kernal.php, every piece of middleware in $middleware is run against every request.
In http/Kernal.php, every piece of middleware in $middleware is run against every request. To use middleware, it must be added to $routeMiddleware (in http/Kernal.php).


Middleware can be attached in a controllers constructor:
Middleware can be attached in a controllers constructor:
Line 132: Line 173:
   Session::has('key'); // get
   Session::has('key'); // get
Anything set with flash will only persist for one request.
Anything set with flash will only persist for one request.
== Migrations ==
=== Artisan ===
  php artisan make:migration create_NAME_table --create=NAME
  php artisan make:migration add_SOMETHING_to_NAME_table --table=NAME
  php artisan migrate //run latest migrations
  php artisan migrate:refresh //drop and re-run all
NAME should be plural. For create, it may be better to create the migration along with the model. For a link table, it's singular, alphabetical order (role_user).
=== Types ===
From the [https://laravel.com/docs/5.2/migrations#creating-columns documentation]:
* $table->increments('id');
* $table->integer('role')->unsigned;
* $table->string('name');
=== Indexes ===
* $table->string('email')->unique();
* $table->index(COLUMNS, NAME); // columns can be one col or an array, name is optional
* $table->foreign('user_id')->references('id')->on('users')>onDelete('cascade');
* $table->dropForeign('posts_user_id_foreign');
=== Notes ===
Renamed a migration and broke stuff. Had to run composer dump-autoload
== Blade ==
commands
* @extends('some.parent.view');
* @if (cond) ... @elseif(cond) ... @else ... @endif
* @for(;;) ... @endfor
* @foreach($foo as $bar) ... @endforeach
* @while(cond)...@endwhile)
* @include('view.name');
* @section('name') ... @endsection // defines a section
* @overwrite used in place of @endsection, allows a section to be re-used
* @yeild('sectionName') renders the section
Section can take a second param instead of wrapping a chunk. The second param becomes the value.
processors
* {{ }} : escapes output
* {!! !!} : does not escape output
* @{{ }} : displays the raw contents - no processing
I DON'T GET @section
=== Notes ===
ORDER MATTERS!!! When if you include a partial before defining a section that partial uses, it will not work!
Missing a closing quote throws a really strange error: '__data' (T_STRING)
== Validation ==
  exists:roles,id
Probably a better way
=== Via Request ===
https://laravel.com/docs/master/validation
  php artisan make:request SomeNameRequest
The rules function returns the rules array. If the authorize function isn't being used, make sure to set it to true.
in the controller, use it with
  public function controllerMethod(Requests\SomeNameRequest $request)
https://laravel.com/docs/master/validation#available-validation-rules
== Collections ==
  $col->contains($id);
  $col->contains('name', $name);


== Research These ==
== Research These ==
* https://github.com/laracasts/Laravel-5-Generators-Extended
* https://github.com/laracasts/Laravel-5-Generators-Extended
* https://github.com/Zizaco/entrust : looks good but does not work, try again later
* https://github.com/matriphe/laravel-imageupload
* https://github.com/formers/former
== Debugging Notes ==
On some hosts (1and1 is where I encountered it) you need to add
  RewriteBase /
to .htaccess
I had to change /storage/logs/laravel.log to 777 to get error output to work.
To view the sql output:
  DB::listen(function($query){print($query->sql . '<br>');});
== Testing ==
  vendor/bin/phpunit

Latest revision as of 14:37, 31 May 2016

Implicit Route Binding

From this video

 Route::get('users/{user}', function(App\User $user){
   return $user;
 });

If the arg name matches the token, it will magic that value into place. With the type hinting, it will find a user with the primary key given in the url.

To use something other than the primary key, you have to add a route binding in RouteServiceProvider.

Auth

Video

 php artisan make:auth

Creates auth stufff.

Email

Easiest is to use 'sendmail'. Make sure to set 'from' in config/mail.php.

Homestead

I'll need to try setting up a homestead instance on AWS with Vagrant. Could be useful to know for other projects too.

Illuminate/html

 composer require illuminate/html

Then in config/app.php, add 'Illuminate\Html\HtmlServiceProvider' to the providers array and 'Form' => 'Illuminate\Html\FormFacade' to the aliases array.

This seems to be the most up-to-date documentation.

Request

 $input = Request::all();
 $foo = Request::get('foo');

Gets all inputs from get and post.

Good shorthand

 $input = Request::all();
 SomeModel::create($input);

Controller

 php artisan make:controller Name
 php artisan make:controller Name --resource

See Restful controllers

Eloquent

The $fillable property limits which properties can be assigned. Special protected properties:

  • $fillable: which fields can be assigned
  • $dates: an array of fields that will be treated as Carbon dates

Artisan

 php artisan make:model User --migration

Accessors and Mutators

Accessors modify data coming from the database before it's inserted in the model. Mutators modify it before inserting.

A mutator method must have a name following the pattern setFieldNameAttribute

Query Scope

Name is scopeName, takes a query as an arg. Useful for attaching repeated query logic to the model.

Relationships

One-to-one

 //in the one being referenced
 public function users(){
   return $this->hasOne('App\Author');
 }
 
 //in the one referencing
 public function author(){
   return $this->belongsTo('App\User');
 }

One-to-many (author to article)

 //in the 'one' (author)
 public function articles(){
   return $this->hasMany('App\Articles');
 }
 
 //in the 'many' (article)
 public function author(){
   return $this->belongsTo('App\User');
 }

Many-to-many: create the pivot table, name is singular underscore singular, alphabetic order. Then in each

 public function article(){ //in tag
   return $this->belongsToMany('article');
 }

The many to many can handle insert/delete diffs with ->sync().

To check if one exists from the other

 $author->articles->contains('title', 'Intro to PHP');

Querying

 $activeClients = App\Organization::whereHas('tags', function($query){
   $query->where('tag','Active Client');
 })->get();

The closure function attaches methods to the sub query.

 Products::whereIn('id', function($query){
   $query->select('paper_type_id')
   ->from(with(new ProductCategory)->getTable())
   ->whereIn('category_id', ['223', '15'])
   ->where('active', 1);
 })->get();
 Model::lists(value, key);

Key is optional. Both key and value are column names. Returns an array. Very useful for selects.

Form Requests

 php artisan make:request NameOfRequest

Starts with the methods authorize and rules.

Rules returns an array of fields and their validation logic.

Validators

  • required
  • min:n
  • date

Authorize returns a bool.

If validation fails, it's redirected back to the previous page with $errors populated with proper errors.

Form requests are implemented with type hinting on the controller.

The controller method looks like this:

 public function someMethod(SomeRequest $request){
   Model::create(request->all());
   return redirect('someplace');
 }

Direct Validation

Rather than creating a form request, we can do this

 public function someMethod(Request $request){
   $this->validate($request, ['title' => 'required|min:3']);
   Model::create(request->all());
   return redirect('someplace');
 }

Routes

 php artisan route:list

Shows a table of the routes.

Route Resource

Implements restful crud.

Route Model Binding

Done through RouteServicesProvider.php in the boot method, add a line like:

 $router->model('article', 'App\Article');

now any instance of {article} in a route will be used to look up an Article by it's primary id and that article will be passed into the controller method.

Middleware

All methods have the same args $request and $next and the continue by calling $next($request);

In http/Kernal.php, every piece of middleware in $middleware is run against every request. To use middleware, it must be added to $routeMiddleware (in http/Kernal.php).

Middleware can be attached in a controllers constructor:

 public function __construct(){
   $this->middleware('auth');
 }

We can also limit what methods it applies to

 public function __construct(){
   $this->middleware('auth', ['only'=>'create']);
 }

At the route level:

 Route::get('create', ['middleware' => 'auth', 'uses' => 'ArticleController@create']);

Sessions

Flash Messaging

 \Session::flash('key','value') // set
 Session::has('key'); // get

Anything set with flash will only persist for one request.

Migrations

Artisan

 php artisan make:migration create_NAME_table --create=NAME
 php artisan make:migration add_SOMETHING_to_NAME_table --table=NAME
 php artisan migrate //run latest migrations
 php artisan migrate:refresh //drop and re-run all

NAME should be plural. For create, it may be better to create the migration along with the model. For a link table, it's singular, alphabetical order (role_user).

Types

From the documentation:

  • $table->increments('id');
  • $table->integer('role')->unsigned;
  • $table->string('name');

Indexes

  • $table->string('email')->unique();
  • $table->index(COLUMNS, NAME); // columns can be one col or an array, name is optional
  • $table->foreign('user_id')->references('id')->on('users')>onDelete('cascade');
  • $table->dropForeign('posts_user_id_foreign');

Notes

Renamed a migration and broke stuff. Had to run composer dump-autoload

Blade

commands

  • @extends('some.parent.view');
  • @if (cond) ... @elseif(cond) ... @else ... @endif
  • @for(;;) ... @endfor
  • @foreach($foo as $bar) ... @endforeach
  • @while(cond)...@endwhile)
  • @include('view.name');
  • @section('name') ... @endsection // defines a section
  • @overwrite used in place of @endsection, allows a section to be re-used
  • @yeild('sectionName') renders the section

Section can take a second param instead of wrapping a chunk. The second param becomes the value.

processors

  • {{ }} : escapes output
  • {!! !!} : does not escape output
  • @{{ }} : displays the raw contents - no processing

I DON'T GET @section

Notes

ORDER MATTERS!!! When if you include a partial before defining a section that partial uses, it will not work!

Missing a closing quote throws a really strange error: '__data' (T_STRING)

Validation

 exists:roles,id

Probably a better way

Via Request

https://laravel.com/docs/master/validation

 php artisan make:request SomeNameRequest

The rules function returns the rules array. If the authorize function isn't being used, make sure to set it to true.

in the controller, use it with

 public function controllerMethod(Requests\SomeNameRequest $request)

https://laravel.com/docs/master/validation#available-validation-rules

Collections

 $col->contains($id);
 $col->contains('name', $name);

Research These

Debugging Notes

On some hosts (1and1 is where I encountered it) you need to add

 RewriteBase /

to .htaccess

I had to change /storage/logs/laravel.log to 777 to get error output to work.

To view the sql output:

 DB::listen(function($query){print($query->sql . '
');});

Testing

 vendor/bin/phpunit