Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sonix's avatar
Level 1

Must not open url out of the loop in Laravel

Hi,

I have a loop to show Alphabets from A to Z with function to get list of students with those initials.

Like

http://www.example.com/students/a

show a list of all students starting with character a.

controller and view is working file changes url from a to b is also working fine but the problem is if someone changes the url to

http://www.example.com/students/alpha

it fetches data for 'alpha' but how Can I stop it. Or how can I redirect it to the 404 page created. I only want it to be within A to not even numeric or a second character in it.

0 likes
6 replies
tykus's avatar

Check the length of the string, e.g.:

public function index($character)
{
    if (strlen($character !== 1) {
        throw new HttpNotFoundException('Please enter a valid letter');
    }
}

or more strict and probably better, check that the character is in the approved set:

public function index($character)
{
    if (in_array(strtolower($character), range('a', 'z'))) {
        throw new HttpNotFoundException('Please enter a valid letter');
    }
}
Sonix's avatar
Level 1

I am also working on other routes as follows.

    Route::get('/students/{alphabet}', 'PostController@showByAlphabet');
    Route::get('/students/{name}', 'PostController@showByName');
    Route::get('/students/{class}', 'PostController@showByClass');

Resulting in

    http://example.com/students/a
    http://example.com/students/example_name
    http://example.com/students/b_com

So I cannot limit the range or character limit.

Vilfago's avatar

@tykus : I think it will, it's only regex.

So

  • [a-z]+ will not limit to 1
  • [a-z] should limit to 1 letter
  • [a-z]{2} - should be exactly 2 characters

But I haven't tested, so I will try soon to be sure of that :) // Edit : I just test it, it works great.

@Sonix : you can use global constraints if needed : https://laravel.com/docs/5.7/routing#parameters-regular-expression-constraints

You set some name for when you want only one letter, or a full name, or a number, etc. and you set it as a global constraint to use it and control the string in every route.

But with my solution, as you can set it for each route, I don't see where is your issue.

Route::get('/students/{alphabet}', 'PostController@showByAlphabet')->where('alphabet', '[a-z]');
Route::get('/students/{name}', 'PostController@showByName')->where('name', '[A-Za-z]+');;
Route::get('/students/{class}', 'PostController@showByClass')->where('class', '[A-Za-z]+');;

Please or to participate in this conversation.