Laravel Controller If Else

Laravel Controller If Else:

In a Laravel controller, you can use if-else statements to control the flow of your code and make decisions based on conditions.

Here’s an example to help explain:

<?php
  
  namespace App\Http\Controllers;
  
  use App\Models\User;
  use Illuminate\Http\Request;
  
  class UserController extends Controller
  {
      public function show($id)
      {
          $user = User::find($id);
  
          if ($user) {
              return view('user.show', compact('user'));
          } else {
              return redirect()->route('users.index');
          }
      }
  }

In this example, we have a UserController with a show method that takes an $id parameter. Inside the method, we retrieve the user with the given id using the User model’s find method.

Then, we use an if-else statement to check if the user exists. If the user is found, we pass the $user variable to the view named “user.show” using the compact function.

Otherwise, if the user is not found, we redirect the user to the “users.index” route using the redirect function.

This is just a simple example, but you can use if-else statements to handle more complex logic in your Laravel controllers based on your specific requirements.

Same cateogry post

Leave a comment