Skip to content

Instantly share code, notes, and snippets.

@juanlopezdev
Last active December 6, 2023 00:45
Show Gist options
  • Save juanlopezdev/44ce0303a155e2626fe34e2ac31fe7e7 to your computer and use it in GitHub Desktop.
Save juanlopezdev/44ce0303a155e2626fe34e2ac31fe7e7 to your computer and use it in GitHub Desktop.
Comandos útiles de Laravel

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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment