Support the ongoing development of Laravel.io →
posted 5 years ago
Last updated 1 year ago.
0

Should I just write something like this?

public function index($town)
    {
        //
        $pubs=\App\Pub::all();
        if ($request->has('rsTown')) {
            $pubs=\App\Pub::where('rsTown', $town)
            ->orderBy('id', 'desc')
               ->paginate(50);
        } else {
            $pubs=\App\Pub::where('rsTown', 'london')
               ->orderBy('id', 'desc')
               ->paginate(50);
        }
        return view('pub2index',compact('pubs/'.$town));
    }
0

Hi John,

If you define the route as returning a view, it will not hit the index method. In other words

public function index($town)
// This $town will always be empty

There are two easy options.

  1. Create a TownController, which on the Show method returns all pubs in that town. It depends on if there are any other entities to sort on, like theatres, take aways or Tesco's;
  2. Just route to the index-method on the PubController, not directly to a view.

For option two:

Route::get('/pubs/{town}', 'Pubcontroller@index');
Route::resource('pubs','PubController');

This way, the route will hit the index-method on the PubController and be returned a view there.

But, notice I put the /pubs/{town} route before the resource route. Reason is that if it were to be after, Laravel would route /pubs/brighton to the wildcard Pub route it generates. In other words, in /pubs/brighton, Brighton would be seen as the identifier of a pub, not a town.

So, this will only work if you don't use the show-method on the PubController. If you do, option 1 will be the other solution. Or, as a third option, work with filters:

http://127.0.0.1:8000/pubs?town=brighton
http://127.0.0.1:8000/pubs?town=worthing

But, that's a whole different story. Using a TownController is probably the easiest way.

0

Thank you so much Maarten! I managed to sort it earlier...

I created a new function:

public function index($town) {
        $pubs=\App\Pub::all();
        $pubs=\App\Pub::where('rsTown', '=', $town)
               ->orderBy('id', 'desc')
               ->paginate(50);
        return view('pub2index',compact('pubs'));
    }
Route::get('/pubs/{town}','PubsTown@index');
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.