Shakun Chaudhary
Shakun Chaudhary

Reputation: 339

Get URL segment in Laravel 5

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

Upvotes: 6

Views: 8483

Answers (2)

Chris
Chris

Reputation: 58182

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

Upvotes: 2

thefallen
thefallen

Reputation: 9749

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

Upvotes: 4

Related Questions