E
E
EVOSandru62018-08-12 00:50:04
Laravel
EVOSandru6, 2018-08-12 00:50:04

How to organize routes for an element with composite keys in laravel?

Good afternoon:
There is a migration:

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');
    }
}

The first thing that comes to mind is to designate in 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', '[email protected]')->name('edit');

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

But if I'm allowed in the controller I write like this:
public function edit(Price $price)
    {
        dd($price);
}

$price Not swallowed(
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

It turns out that in any case you have to write arguments like this:
public function edit($days, $price) {
        $price = Price::where([
            'days' => $days,
            'price' => $price
        ])->first();
...
}

And RouteServiceProvider will not help here in any way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ernest Faizullin, 2018-08-12
@erniesto77

should work, but I'm not sure what comes into the function as arguments

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();
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question