jacobdo
jacobdo

Reputation: 1615

modify back route in laravel

In my scenario, I am coming from the following route:

model/{model}/edit

and I am accessing route:

model/{model}/duplicate

I make a copy of the model and store it

$duplicate_model = $model->replicate();
$duplicate_model->save();

after that I wish to return back to edit route of the new model by doing something along the lines of this:

return redirect()->back()->with('model' => $duplicate_model);

hoping that it would replace the model id with that of the duplicated model, but it does not.

I cannot access a specific route, because there are different cases in which the duplicate route may be accessed.

Upvotes: 4

Views: 697

Answers (2)

user7116461
user7116461

Reputation:

You can define a "path()" in your model. In this case /

/model/{model}/edit

define a function in your model

public function path() { return '/model/' . $this->id . '/edit'; }

in your ThatModelController.php

simply

return redirect($dumplicate_model->path());

It should work,Jeffery Way uses this convention.

Note: If you are using route model binding and using slug the path() function should return $this->slug instead of $this->id

Upvotes: 0

jacobdo
jacobdo

Reputation: 1615

One of the solutions is to get resolve to resolve a route name from the back URL like this, provided that all possible back routes are named:

$back_route_name = app('router')->getRoutes()->match(app('request')->create(redirect()->back()->getTargetUrl()))->getName();

and then redirect to the route by name:

return redirect()->route($back_route_name, ['template' => $duplicate_template]);

Upvotes: 4

Related Questions