6

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

2
  • What do you mean by second segment? Can you give an example? Commented Jul 27, 2016 at 6:49
  • www.example.com/segment1/segment2/12/114/122 - I need this segment 2 sir iin laravel way,if exists. Commented Jul 27, 2016 at 6:57

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

6 Comments

redirect()->back()->getTargetUrl() returns back url with params.need to extract the second segment.
@ShakunChaudhary my mistake, I didn't understand that you want the segment from the previous URL. Please check my edit.
i need segment from target url.If i use this redirect()->back()->getRequest()->segment(2).It gives segment of current url not from previous url.
@ShakunChaudhary aah yes, but redirect()->back() returns RedirectResponse object which cant access the segments. So in this case use getTargetUrl() and parse it like @Chris suggests.
I also feel the same.but in chris method, what is return Arr::.May be he just copy pasted.so now i have to do this in php way.Thanks @TheFallen
|
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 != '';
    }));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.