public function handle($request, Closure $next)
{
return $this->encrypt($next($this->decrypt($request)));
}
RouteServiceProvider.php
Route::bind('test', function (string $value) {
return new Test($value);
});
web.php
Route::get('/{test}', [TestController::class, 'index']);
TestController.php
class TestController extends Controller
{
public function index(Request $request, Test $test){
dd($test);
}
public function category(Request $request, $code) {
//Получаю все товары данной катигории следующим образом: $category->products
$category = Category::where('code', $code)->firstOrFail();
//А пагинация строится в отдельном запросе к таблице Товаров
$products = $category->products()
->when(($request->get('price_min'), function(Builder $query, $price_min){
return $query->where('price', '>=', $price_min);
})->when(($request->get('price_max'), function(Builder $query, $price_max){
return $query->where('price', '<=', $price_max);
})->paginate(4);
return view('category', compact('category', 'products'));
}
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->integer('price');
$table->text('des');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories');
});
}
select sum(number), country_id from table group by country_id;
select sum(number), city_name, country_id from table group by country_id;
public function project(): HasOne
{
$instance = $this->newRelatedInstance(Project::class);
$relation = new HasOne($instance->newQuery(), $this, DB::raw('project_user.user_id'), $this->getKeyName());
return $relation->leftJoin('project_user', 'project_user.project_id', '=', 'projects.id');
}
Model::insert([
[row1], [row2], [row3], [row4],
]);
public static function fromRequest(FormRequest $request): static
{
$data = $request->validated();
$properties = (new \ReflectionClass(self::class))->getProperties(\ReflectionProperty::IS_PUBLIC);
foreach ($properties as $property){
if(!isset($data[$property->name])){
$data[$property->name] = $property->getDefaultValue();
}
}
return new static(...$data);
}
public function __invoke($attribute, $value, $fail)
{
$dishesRequest = collect($value);
$data = Dishe::whereIn('id', $dishesRequest)->Active()->whereHas('menu', function ($query) {
return $query->where('project_id', $this->project->id)->Active();
})->selectRaw('count(1) as count, sum(price) as sum');
if($data->count != $dishesRequest->count()){
return $fail(__('validation.exists'));
}
# Получаем список блюд по массиву идентификаторов
$totalDishes = $data->sum;
$total = $this->order ? $totalDishes + $this->order->totalPrice : $totalDishes;
if ($total < 1 || $total > 150000) {
return $fail('Сумма заказа должна быть от 1 ₽ до 150 000 ₽');
}
}
php artisan make:policy OrderPolicy
class OrderPolicy
{
use HandlesAuthorization;
public function update(User $user, Order $order)
{
if (!$user->isEmployee()) {
return false;
}
if ($user->id !== $order->user_id) { // остальной кусок ифа не понял - но он должен быть здесь.
return false;
}
return in_array($order->status, [Order::NEW, Order::WORK]);
}
}
class OrderUpdateRequest extends FormRequest
{
public function authorize()
{
return $this->user()->can('update', $this->order);
}
}
products
--- id
--- name
product_attributes
--- id
--- name
product_attribute_values
--- id
--- attribute_id
--- product_id
--- value
class Product extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function attributes(): BelongsToMany
{
return $this->belongsToMany(Attribute::class, 'product_attribute_value')->withPivot(['value']);
}
}
class Attribute extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function getValuesAttribute($value){
return collect(explode(',', $value));
}
}
$a1 = \App\Models\Attribute::create([
'name' => 'Attr1',
]);
$a2 = \App\Models\Attribute::create([
'name' => 'Attr2',
]);
$a3 = \App\Models\Attribute::create([
'name' => 'Multy Attr3',
]);
$p1 = \App\Models\Product::create([
'name' => 'Product1',
]);
$p1->attributes()->attach($a1->id, [
'value' => '2012',
]);
$p1->attributes()->attach($a2->id, [
'value' => 'Джинса',
]);
$p1->attributes()->attach($a3->id, [
'value' => 'Синий',
]);
$p1->attributes()->attach($a3->id, [
'value' => 'Черный',
]);
$p1->attributes()->attach($a3->id, [
'value' => 'Зеленый',
]);
$p2 = \App\Models\Product::create([
'name' => 'Product2',
]);
$p2->attributes()->attach($a1->id, [
'value' => '2013',
]);
$p2->attributes()->attach($a2->id, [
'value' => 'Лен',
]);
$p2->attributes()->attach($a3->id, [
'value' => 'Красный',
]);
$p2->attributes()->attach($a3->id, [
'value' => 'Серобурый',
]);
$p3 = \App\Models\Product::create([
'name' => 'Product3',
]);
$p3->attributes()->attach($a1->id, [
'value' => '2015',
]);
$p3->attributes()->attach($a2->id, [
'value' => 'Лен',
]);
$p3->attributes()->attach($a3->id, [
'value' => 'Синий',
]);
$p3->attributes()->attach($a3->id, [
'value' => 'Желтый',
]);
public function attributes_with_grouped_values(): HasMany{
$instance = $this->newRelatedInstance(Attribute::class);
$query = $instance->newQuery()->join('product_attribute_value', 'product_attribute_value.attribute_id', '=', 'attributes.id')
->groupBy('attributes.id', 'attributes.name', 'product_attribute_value.product_id')
->select('attributes.id', 'attributes.name', 'product_id', DB::raw('string_agg(product_attribute_value.value, \',\') as values'));
// в случае с мускул string_agg(product_attribute_value.value, \',\') заменить на group_concact
return $this->newHasMany(
$query, $this, 'product_attribute_value.product_id', 'id'
);
}
public function getValuesAttribute($value){
return collect(explode(',', $value));
}
$products = Product::with('attributes_with_grouped_values')->get();
foreach ($products as $product){
echo $product->name.PHP_EOL;
foreach ($product->attributes_with_grouped_values as $attribute){
dump(json_encode([$attribute->name => $attribute->values->all()]));
}
}
Product1
^ "{"Attr1":["2012"]}"
^ "{"Attr2":["\u0414\u0436\u0438\u043d\u0441\u0430"]}"
^ "{"Multy Attr3":["\u0421\u0438\u043d\u0438\u0439","\u0417\u0435\u043b\u0435\u043d\u044b\u0439","\u0427\u0435\u0440\u043d\u044b\u0439"]}"
Product2
^ "{"Attr1":["2013"]}"
^ "{"Attr2":["\u041b\u0435\u043d"]}"
^ "{"Multy Attr3":["\u041a\u0440\u0430\u0441\u043d\u044b\u0439","\u0421\u0435\u0440\u043e\u0431\u0443\u0440\u044b\u0439"]}"
Product3
^ "{"Attr1":["2015"]}"
^ "{"Attr2":["\u041b\u0435\u043d"]}"
^ "{"Multy Attr3":["\u0416\u0435\u043b\u0442\u044b\u0439","\u0421\u0438\u043d\u0438\u0439"]}"