Crear un controlador tipo recurso
$ php artisan make:controller PhotoController --resource
Crear un Form Request
Su nomenclatura es (Nombre-del-modelo-que-impacta)+(Acción)+Request. Por ejemplo, si quieres crear un Form Request para validar los datos que actualizarán el modelo Post, deberías ponerle el siguiente nombre:
$ php artisan make:request PostCreateRequest
Crear un modelo
$ php artisan make:model User
Solucionar cuando se tiene el mismo nombre al importar con USE
// Produce error:
use App\Image;
use GImage\Image;
// Dar un alias para solucionar el error:
use App\Image;
use GImage\Image as GIImage;
Crear relaciones en el modelo
Si tenemos las siguiente estructura de tabla:
- shops
- id
- name
- products
- id
- name
- product_shop
- product_id
- shop_id
// Option 1
class Shop extends Model {
/**
* The products that belong to the shop.
*/
public function products() {
return $this->belongsToMany('App\Product');
}
}
// Option 2
class Product extends Model {
/**
* The shops that belong to the product.
*/
public function shops() {
return $this->belongsToMany('App\Shop');
}
}
// Use
Shop::find($id)->with('products');
Si tenemos la siguiente estructura
- Persons
- id
- name
- profession_id
- Professions
- id
- name
class Person extend Models {
public function profession() {
return $this->belongsTo(Profession::class);
}
}
Hacer filtros en la relationships
// https://stackoverflow.com/questions/21378889/how-to-filter-many-to-many-structure-in-laravel
// https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence
$users = User::whereHas('roles', function($q) {
$q->where('name', '=', 'admins');
})->get();
$initiative = Initiative::select('initiatives.*')
->with(['program' => function ($queryProgram) {
$queryProgram->with(['entities' => function ($queryEntities) {
$queryEntities->where('state', '!=', 0);
}]);
}])
->find($id);
Decodificar JWT usando JWT-auth
use Tymon\JWTAuth\Facades\JWTAuth; //use this library
$token = JWTAuth::getToken();
$apy = JWTAuth::getPayload($token)->toArray();
Filtrar por Año en Eloquent
// Reference: https://stackoverflow.com/questions/33534677/mysql-year-equivalent-in-laravel-query-builder
Initiative::whereYear('start_date', '=', $year)
Obtener solo valor de un objeto Collection
$email = User::where('id', 1)->value('email');
Links de referencia:
- Form Request
- Artículos
- Solución de errores
- Eloquent
- Relationships
- Articulos
- Soluciones
- JWT
- Decodificar usando JWT-AUTH https://stackoverflow.com/questions/48309645/how-to-decode-jwt-using-jwt-auth-in-laravel
- Miscelanea
- Buenas practicas - GITHUB https://github.com/alexeymezenin/laravel-best-practices-
- Buenas prácticas - MEDIUM https://medium.com/@alexrenoki/pushing-laravel-further-best-tips-good-practices-for-laravel-5-7-ac97305b8cac