Sunday, January 14, 2018

modify back route in laravel

Leave a Comment

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.

2 Answers

Answers 1

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]); 

Answers 2

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment