Как в laravel организовать роуты для элемента с составными ключами?

Добрый день:

Есть миграция:

class CreatePricesTable extends Migration
{
    public function up()
    {
        Schema::create('prices', function (Blueprint $t) {
            $t->primary(['vehicle_id','days']);
            $t->decimal('price');
            $t->integer('vehicle_id')->default(1)->index;
            $t->foreign('vehicle_id')->references('id')->on('vehicles')->onDelete('cascade');
            $t->integer('days');
            $t->timestamps();
            $t->softDeletes();
        });
    }

    public function down()
    {
        Schema::dropIfExists('prices');
    }
}


Первое что приходит в голову - обозначить в RouteServiceProvider:

Route::bind('price', function ($days, $price) {
            return Price::where([
                'days' => $days,
                'price' => $price,
            ]);
        });


routes/web

Route::group([
                'as' => 'prices.',
                'prefix' => 'prices',
            ], function() {

                Route::get('{days}/{price}/edit', 'PricesController@edit')->name('edit');

                Route::get('create', 'PricesController@create')->name('create');
                Route::get('{days}/{price}', 'PricesController@show')->name('show');
                Route::post('', 'PricesController@store')->name('store');
                Route::put('{days}/{price}', 'PricesController@update')->name('update');
                Route::delete('{days}/{price}', 'PricesController@destroy')->name('destroy');
            });
        });


Но если я допустим в контроллере пишу так:

public function edit(Price $price)
    {
        dd($price);
}


$price Не проглатывается(

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string


Получается в любом случае придется писать аргументы такого вида:
public function edit($days, $price) {
        $price = Price::where([
            'days' => $days,
            'price' => $price
        ])->first();
...
}


И RouteServiceProvider тут никак не поможет?
  • Вопрос задан
  • 438 просмотров
Пригласить эксперта
Ответы на вопрос 1
erniesto77
@erniesto77
oop, rb, py, php, js
должно работать, только я не уверен что приходит в функцию в качестве аргументов
Route::bind('price', function (...$arguments) {
    if ( ! isset($arguments['days') or ! isset($arguments['price']))
        return abort(422, 'Invalid data')
            return Price::where([
                'days' => $arguments['days'],
                'price' => $arguments['price'],
            ])->firstOrFail();
        });
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы