Laravel: Redirect back with all previous parameters

- Andrés Cruz

En español

Laravel: Redirect back with all previous parameters

One of the aspects that can be a small stone in the shoe is that when we create our fantastic CRUD, with the best design, best validations and the best performance in general, when we decide to edit a record that is NOT from the first page of the list when we finish editing the record, the classic operation is to send it to the listing page... The problem is that we send it to page one of the listing and NOT to the page where we edit the record: I'm going to present you a simple scheme that you can use in any framework, or even without using a framework.

So, if you use Django, CodeIgniter, Flask, or Laravel which is our case study, you can use this solution even if you use Inertia, Livewire or basic Laravel.

Using the a session to save the current page

The trick is to always save somewhere, for example in the session when we are on the listing page; i.e. the complete listing page with parameters and everything: in Laravel it would be something like the following:

//echo request()->fullUrl();
//if(!Str::contains(request()->fullUrl(), ["livewire/message","???"]))
Session::put("url_return",request()->fullUrl());

For example, you can put it in the index (or you should put it...) if you are using basic Laravel with all possible filters and page parameters.

    public function index()
    {
        $posts = Post::orderBy('created_at', 'desc')->paginate(10);
        // select * from posts
        return view('dashboard.post.index', ['posts' => $posts]);
    }

 

With fullUrl() we obtain the full URL, with EVERYTHING including the parameters, and we save this in the session, a serious extra for livewire or inertia, that when sending requests behind control or internal to this package, you have to filter these occurrences and that's what the conditional you see in the code above is for.

On the edit page

Now once, when we're on the edit page, editing that record from page 2 or higher, we ask if we have anything in the session, from the parameter we set earlier, and if so, we send our user to that page and everything:

if(session("url_return"))
return redirect(session("url_return"));
//Session::put('url_return', null);

You could also clear the session in some key part of your app.

In the case of basic Laravel, it would be the update function for this purpose:

public function update(StorePostPost $request, Post $post)
{
     $post->update($request->validated());
     return back()->with('status', 'Post actualizado con éxito');
}

You could also clear the session in some key part of your app.

In the case of basic Laravel, it would be the update function for this purpose:

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.