Introduction to Stringable::endsWith in Laravel 11

laravel 11 endswith method
18 April 2025

Description about Stringable::endsWith()


Being a member of Laravel, this is one of the attractive capabilities of this framework that allows developers to easily handle and utilize strings. One of the functions available in this class, endsWith, is used to check if a string ends with a specific substring or not, and has practical use.


By using this method, you can check if the end of a string matches a specific value. For example, assume you want to check if the names of uploaded files end with '.jpg'. This method easily helps you do this.


This capability is especially useful for working with paths, file names, and other strings in Laravel. For this reason, many developers use this method in their projects to ensure data and name reliability.


As an example, you can use Stringable::endsWith in a specific scenario and based on its results make specific decisions. In a web development project, you can easily verify whether user inputs end with specific extensions.


Code Example


use Illuminate\Support\Str;

$string = new Str('example.jpg');

if ($string->endsWith('.jpg')) {
echo 'This string ends with the jpg extension';
} else {
echo 'This string does not end with the jpg extension';
}

Code Explanation



use Illuminate\Support\Str;

This line imports the Str class from the Laravel framework.


$string = new Str('example.jpg');

In this line, a new instance of the Str class is created with the string 'example.jpg'.


if ($string->endsWith('.jpg')) {

Here, it checks whether the string ends with '.jpg' or not.


echo 'This string ends with the jpg extension';

If the previous condition is correct, this message will be printed.


} else {

Otherwise, the flow continues to the else part.


echo 'This string does not end with the jpg extension';

If the condition is not correct, this message will be printed.


}

This closes the if and else condition.

FAQ

?

What is the endsWith method in Laravel?

?

How can I use endsWith in Laravel?

?

Can I pass multiple substrings to endsWith?