If condition in Laravel 9

Created at 22-Dec-2022 , By samar

You can use if condition in php or blade file in Laravel 9. If condition in use to execute a block of code only if a certain condition is met. It is commonly used to make decisions based on the values of variables or expression.

Here's an example of using an if statement in Laravel PHP file.

$user = User::find($request->id);

if ($user->isAdmin()) {
    return view('admin.show', compact('user'));
} else {
    return view('users.show', compact('user'));
}

In the above example, if the user is an admin is will return to admin.show view file else it will return to users.show file in Laravel.

Here we have another example of using if statement in blade file.

<div>
    @if ($user->isAdmin())
        <p>Welcome, Admin!</p>
    @else
        <p>Welcome, User!</p>
    @endif
</div>

This code will display "Welcome, Admin!" if the isAdmin method of the $user object returns true, and "Welcome, User!" if it returns false.

There are many different ways that if statements can be used in real-world applications. Here are a few examples like validating user input, displaying content based on user permissions, responding to different conditions and displaying error messages.

  • Code examples of using if condition in Laravel (PHP)

    Example 1: Check if a request has a specific input value

    if ($request->has('name')) {
        echo "Request has name";
    }
    

    Example 2: Check if a user is authenticated

    if (Auth::check()) {
        echo "user is authenticate do whatever you want to do.";
    }
    

    Example 3: Check if a value is present in an array

    if (in_array($value, $array)) {
        echo "value exists in array";
    }
    

    Example 4: Check if a model has a specific attribute

    if ($model->hasAttribute('name')) {
        echo "Model have name attribute";
    }
    

    Example 5: Check if a string starts with a specific substring

    if (starts_with($string, 'w3codegenerator')) {
        echo "string start with w3codegenerator";
    }
    

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.