In this article, we will see how to use the switch case statement in the blade/view file in Laravel with an Example. Let’s just jump into it.
How Switch Case Statement Works
Switch statement is used to check the condition of many blocks one by one and it will execute the matched block. If no matches found then it will execute the default block and break the statement.
Let’s see the example of the Laravel blade switch case statement.
Example Laravel Blade Switch Case
Laravel switch statements can be constructed using the @switch
, @case
, @break
, @default
and @endswitch
directives:
app/Http/Controllers/PostController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostsController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function index()
{
$status = 'publish';
return view('posts.post', compact('status'));
}
}
resources/views/posts/post.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Switch Case Statement Example | ScratchCode</title>
</head>
<body>
@switch($status)
@case('publish')
<span class="status">Publish</span>
@break
@case('draft')
<span class="status">Draft</span>
@break
@default
<span class="status">Trash</span>
@endswitch
</body>
</html>
You can see in the above example, we are passing the status
(publish, draft, trash) of post from the controller. Then in the blade file, we have used the switch case statement which will execute the publish
case and then break the statement.
Additionally, read our guide:
- Base Table Or View Already Exists In Laravel Migration
- Add Column After A Column In Laravel Migration
- Laravel: Change Column Type In Migration
- Laravel: Change Column Name In Migration
- How To Use Where Date Between In Laravel
- How To Add Laravel Next Prev Pagination
- Laravel Remove Column From Table In Migration
- Laravel: Get Month Name From Date
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Update Pivot Table In Laravel
- How To Dynamic iFrame URL In Elementor
- How To Handle Failed Jobs In Laravel
- Laravel: Add New Column With A Value In Select Query
- How To Get Latest Records In Laravel
- How To Break Nested Loops In PHP Or Laravel
- How To Pass Laravel URL Parameter
- Laravel Run Specific Migration
- How To Fix Elementor Icons Not Showing
That’s it from our end. We hope this article helped you to learn how to use the laravel switch case statement in the views/blade file.
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!Laravel: Add New Column With A Value In Select Query