For accessing previous URL in laravel. I am using this code in my controller.
$current_url = Request::url();
$back_url = redirect()->back()->getTargetUrl();
if ($current_url != $back_url) {
Session::put('previous_url', redirect()->back()->getTargetUrl());
}
This method helps maintainging previous url even when server side validation fails. In my blade I access previous url like this {{ Session::get('previous_url') }}
.
I need to find the second segment of my previous url. Thanks
You can do it this way:
request()->segment(2);
request()
is a helper function that returns Illuminate\\Http\\Request , but you can also use the facade Request or inject the class as a dependency in your method.
EDIT
with the redirect back: redirect()->back()->getRequest()->segment(2);
Under the hood, Laravel is doing these two things to get the segments of a url (from within the Request class):
public function segment($index, $default = null)
{
return Arr::get($this->segments(), $index - 1, $default);
}
public function segments()
{
$segments = explode('/', $this->path());
return array_values(array_filter($segments, function ($v) {
return $v != '';
}));
}
You could do something similar in a helper function:
public function segment($url, $index, $default)
{
return Arr::get($this->segments($url), $index - 1, $default);
}
public function segments($url)
{
$segments = explode('/', $url);
return array_values(array_filter($segments, function ($v) {
return $v != '';
}));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.