deep
deep

Reputation: 57

Make Laravel 8 slug variable case insensitive

I have dynamic URL structure, with the following pages table, where page URL is set as page type. I have Apache server, where URLs are case-sensitive. I want to force route variable to lowercase in case user types in uppercase URL or throw 404 error.

Currently it shows View [About] not found when URLs are typed in uppercase. How can I force route variable to lowercase or throw Fail error when View/Directory not found?

View not found

Page Table

id |     name      |     type     | slug
1  |     About     |      about   | about
2  |    Contact    |    contact   | contact-us
3  | Events & Blog | event_blog | events-blog

web.php

Route::get('/{page}', 'Controller@page')->name('view_page')->where(['page' => Str::lower('[\w\d\-]+(.*)')]);

Controller

public function page($page)
{
  $page = Page::where('slug' => $page)->firstOrFail();
  return  view($page,  compact('page'));
}

I have about, contact, event_blog directories in resources folder, which is working correctly for lowercase URLs, its showing error for uppercase URLs.

Upvotes: 0

Views: 1356

Answers (2)

STA
STA

Reputation: 34718

You're geeting this error not from the model or database, you geeting the error for this line view($page, compact('page'));, because the ****.blade.php file is not there. You can change this to :

return  view(strtolower($page),  compact('page'));

Alternatively, you can use whereRaw() clause to check case sensitive character on your database :

Page::whereRaw('BINARY slug=?', $page)->firstOrFail();

Or,

Page::where(DB::raw('BINARY slug'), $page)->firstOrFail();

Upvotes: 1

Waska Chaduneli
Waska Chaduneli

Reputation: 362

If I understand, maybe Str::lower() / strtolower() will help you to solve the problem.

$page = Page::where('slug' => \Illuminate\Support\Str::lower($page))->firstOrFail();

Upvotes: 0

Related Questions