"Day5 Laravel Assignments: Laravel Blade Templating Basics"
Day5 Laravel Assignments
Laravel Blade Templating Basics
Assignment 1: Conditional Statements with Blade
Objective:
- Understand how to use Blade’s conditional @if, @elseif, and @else directives to display content based on conditions.
Task:
Create a Blade view that displays a personalized message for users based on their role. The roles can be admin, editor, or guest.
- If the user is an admin, display: "Welcome Admin!"
- If the user is an editor, display: "Welcome Editor!"
- If the user is a guest, display: "Welcome Guest!"
Solution:
Step 1: Controller First, create a controller method that passes a user role to the view.
// UserController.php
public function showDashboard()
{
$user = User::find(1); // Assume we're getting the user from the database
return view('dashboard', compact('user'));
}
Step 2: Blade View
Create the Blade view to display the content based on the user's role.
<!-- resources/views/dashboard.blade.php -->
<h1>Dashboard</h1>
@if($user->role == 'admin')
<p>Welcome Admin!</p>
@elseif($user->role == 'editor')
<p>Welcome Editor!</p>
@else
<p>Welcome Guest!</p>
@endif
Explanation:
- The @if directive checks if the user's role is 'admin'. If true, it displays the message for the admin.
- The @elseif directive checks if the user's role is 'editor'. If true, it displays the message for the editor.
- The @else directive handles the case when the user is neither an admin nor an editor, assuming the role is 'guest'.
Assignment 2: Displaying a List of Items Using @foreach
Objective:
- Learn how to loop through an array or collection using the @foreach directive.
Task:
Create a Blade view that displays a list of products with their names, descriptions, and prices.
1. In your controller, create a list of products (you can simulate this by creating an array of products).
2. Display the product name, description, and price using the @foreach loop.
Solution:
Step 1: Controller
// ProductController.php
public function showProducts()
{
$products = [
(object) ['name' => 'Laptop', 'description' => 'A high-performance laptop', 'price' => 999],
(object) ['name' => 'Smartphone', 'description' => 'A cutting-edge smartphone', 'price' => 799],
(object) ['name' => 'Headphones', 'description' => 'Noise-cancelling headphones', 'price' => 199]
];
return view('products.index', compact('products'));
}
Step 2: Blade View
<!-- resources/views/products/index.blade.php -->
<h1>Product List</h1>
@foreach($products as $product)
<div class="product">
<h2>{{ $product->name }}</h2>
<p>{{ $product->description }}</p>
<span>${{ $product->price }}</span>
</div>
@endforeach
Explanation:
- The @foreach directive iterates over the $products array and displays each product's name, description, and price inside the loop.
- The product data is accessed using {{ $product->name }}, {{ $product->description }}, and {{ $product->price }} to display the values in the HTML.
Assignment 3: Creating a Layout with @yield and @section
Objective:
- Understand how to use Blade’s @yield and @section to create a layout and insert dynamic content into it.
Task:
Create a basic layout for your website with a header, footer, and a content area. Then, create a child view that extends this layout and fills the content section.
1. In the layout file, define @yield('title'), @yield('header'), and @yield('content') to mark sections where dynamic content will be inserted.
2. In the child view, use @section('title'), @section('header'), and @section('content') to provide the content for those sections.
Solution:
Step 1: Layout File (Master Layout)
Create the main layout file in resources/views/layouts/app.blade.php.
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@yield('title', 'Default Title')</title>
</head>
<body>
<header>
<h1>@yield('header', 'Welcome to My Website')</h1>
</header>
<main>
@yield('content')
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
Step 2: Child View
Create a child view in resources/views/home.blade.php.
<!-- resources/views/home.blade.php -->
@extends('layouts.app')
@section('title', 'Home Page')
@section('header')
<h1>Welcome to the Home Page!</h1>
@endsection
@section('content')
<p>This is the content of the home page.</p>
<p>Here we can put dynamic content, like the list of users, products, etc.</p>
@endsection
Explanation:
- The layout (app.blade.php) defines placeholders with @yield for the title, header, and content.
- The child view (home.blade.php) uses @extends('layouts.app') to inherit the layout, and @section('title'), @section('header'), and @section('content') to provide the actual content that replaces the placeholders.
Assignment 4: Including Partial Views with @include
Objective:
- Learn how to include partial views using the @include directive.
Task:
Create a header partial view and include it in the main layout. The header should display the website title and a navigation menu.
1. Create a header partial view.
2. Include the header partial in the layout using the @include directive.
Solution:
Step 1: Header Partial View
Create a partial view for the header in resources/views/partials/header.blade.php.
<!-- resources/views/partials/header.blade.php -->
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>
Step 2: Layout File (Main Layout)
Modify the layout file to include the header partial using @include.
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@yield('title', 'Default Title')</title>
</head>
<body>
@include('partials.header') <!-- Include the header here -->
<main>
@yield('content')
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
Explanation:
- The @include('partials.header') directive is used to include the header.blade.php partial view inside the main layout file.
- This makes the layout cleaner and more reusable by separating the header code into its own partial view.
Assignment 5: Creating a Dynamic User Profile Page
Objective:
- Use Blade to create a dynamic user profile page by passing user data from a controller to a view.
Task:
1. In the controller, fetch the user’s profile data from the database.
2. In the Blade view, display the user’s name, email, and profile picture.
Solution:
Step 1: Controller
// UserController.php
public function showProfile($id)
{
$user = User::find($id); // Fetch user from the database
return view('user.profile', compact('user')); // Pass user data to view
}
Step 2: Blade View
<!-- resources/views/user/profile.blade.php -->
<h1>User Profile</h1>
<div class="profile">
<h2>{{ $user->name }}</h2>
<p>Email: {{ $user->email }}</p>
@if($user->profile_picture)
<img src="{{ asset('storage/profile_pictures/'.$user->profile_picture) }}" alt="Profile Picture">
@else
<p>No profile picture available.</p>
@endif
</div>
Explanation:
- The controller fetches the user data and passes it to the view.
- The Blade view uses {{ $user->name }} to display the user’s name and {{ $user->email }} to display the email.
- It also checks if a profile picture exists and displays it. Otherwise, it shows a message indicating no profile picture is available.
Assignment 6: Blade Components for Reusable UI Elements
Objective:
- Learn how to create and use Blade components to build reusable UI elements.
Task:
Create a Blade component for displaying a "card" with a title, description, and an image. Use this component to display multiple cards on a page.
Solution:
Step 1: Create the Blade Component
To create a Blade component, you can use the php artisan make:component command. In this case, we'll create a Card component.
Run the command:
php artisan make:component Card
This creates two files:
1. A view file: resources/views/components/card.blade.php
2. A class file: app/View/Components/Card.php
Step 2: Define the Card Component View
In the resources/views/components/card.blade.php file, define the layout for the card.
<!-- resources/views/components/card.blade.php -->
<div class="card">
<img src="{{ $image }}" alt="Card image" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ $title }}</h5>
<p class="card-text">{{ $description }}</p>
</div>
</div>
Step 3: Use the Card Component in a Blade View
Now, use the Card component in a Blade view (e.g., resources/views/cards.blade.php).
<!-- resources/views/cards.blade.php -->
@extends('layouts.app')
@section('title', 'Product Cards')
@section('content')
<div class="container">
<div class="row">
<x-card title="Product 1" description="This is a great product." image="product1.jpg" />
<x-card title="Product 2" description="This product is even better!" image="product2.jpg" />
<x-card title="Product 3" description="The best product ever!" image="product3.jpg" />
</div>
</div>
@endsection
Explanation:
- We created a reusable card component in resources/views/components/card.blade.php which accepts three parameters: title, description, and image.
- In the cards.blade.php view, we use the <x-card /> tag to render the card component with different content.
Assignment 7: Displaying Form Data with Blade
Objective:
- Use Blade to display user-submitted form data.
Task:
Create a form to collect user information (name, email, and message). Once the form is submitted, display the submitted data on a new page.
Solution:
Step 1: Create the Form in Blade
First, create a form in resources/views/contact.blade.php.
<!-- resources/views/contact.blade.php -->
@extends('layouts.app')
@section('title', 'Contact Us')
@section('content')
<h1>Contact Us</h1>
<form action="{{ route('submit.contact') }}" method="POST">
@csrf
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" id="name" class="form-control" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email" id="email" class="form-control" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea name="message" id="message" class="form-control" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@endsection
Step 2: Handle the Form Submission in the Controller
Create a controller to handle form submission and display the data.
// ContactController.php
use Illuminate\Http\Request;
public function submitForm(Request $request)
{
$data = $request->only(['name', 'email', 'message']);
return view('contact.thankyou', compact('data'));
}
Step 3: Display the Submitted Data
Create a thankyou.blade.php view to display the submitted data.
<!-- resources/views/contact/thankyou.blade.php -->
@extends('layouts.app')
@section('title', 'Thank You')
@section('content')
<h1>Thank You for Your Message!</h1>
<h3>Submitted Information:</h3>
<p><strong>Name:</strong> {{ $data['name'] }}</p>
<p><strong>Email:</strong> {{ $data['email'] }}</p>
<p><strong>Message:</strong> {{ $data['message'] }}</p>
@endsection
Explanation:
- The form in contact.blade.php submits data to the submitForm method in the controller.
- The controller retrieves the submitted data and passes it to the thankyou.blade.php view.
- The thankyou.blade.php view then displays the submitted name, email, and message using Blade's {{ }} syntax.
Assignment 8: Custom Blade Directives
Objective:
- Learn how to create and use custom Blade directives.
Task:
Create a custom Blade directive to display the user's age based on their birthdate. The directive should calculate the user's age from their birthdate and display it in the format "You are X years old."
Solution:
Step 1: Register the Custom Blade Directive
In the AppServiceProvider.php, register the custom directive.
// app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Blade;
public function boot()
{
Blade::directive('age', function ($birthdate) {
return "<?php echo \Carbon\Carbon::parse($birthdate)->age; ?>";
});
}
Step 2: Use the Custom Directive in a Blade View
Use the @age directive in a Blade view to display the user's age.
<!-- resources/views/user/profile.blade.php -->
@extends('layouts.app')
@section('title', 'User Profile')
@section('content')
<h1>User Profile</h1>
<p>Name: {{ $user->name }}</p>
<p>Email: {{ $user->email }}</p>
<p>Age: @age($user->birthdate)</p>
@endsection
Explanation:
- We created a custom Blade directive @age that calculates and displays the user's age based on their birthdate.
- The Carbon::parse($birthdate)->age part uses the Carbon library to parse the birthdate and calculate the age.
Assignment 9: Blade Layouts with Dynamic Title and Content
Objective:
- Use Blade layouts with dynamic content for reusable templates.
Task:
Create a layout with a dynamic title and content section. Then, create multiple child views that extend this layout, each with different content.
Solution:
Step 1: Create the Layout File
Create a layout file in resources/views/layouts/master.blade.php.
<!-- resources/views/layouts/master.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@yield('title', 'Default Title')</title>
</head>
<body>
<header>
<h1>@yield('header', 'Website Header')</h1>
</header>
<main>
@yield('content')
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
Step 2: Create the Child Views
1. Home Page View:
<!-- resources/views/home.blade.php -->
@extends('layouts.master')
@section('title', 'Home Page')
@section('header', 'Welcome to the Home Page')
@section('content')
<p>This is the homepage content.</p>
@endsection
2. About Page View:
<!-- resources/views/about.blade.php -->
@extends('layouts.master')
@section('title', 'About Us')
@section('header', 'About Us')
@section('content')
<p>Learn more about our company here.</p>
@endsection
Explanation:
- The @yield directives in the master layout file allow for dynamic content like the title and header to be defined in child views.
- The child views extend the layout using @extends('layouts.master') and define their own content for the title, header, and main content sections using @section.
Assignment 10: Using @csrf in Forms for Security
Objective:
- Learn how to use the @csrf directive in forms to protect against cross-site request forgery (CSRF) attacks.
Task:
Create a form to collect user feedback and protect it with the @csrf directive.
Solution:
Step 1: Create the Feedback Form
<!-- resources/views/feedback.blade.php -->
@extends('layouts.app')
@section('title', 'Submit Feedback')
@section('content')
<h1>Submit Your Feedback</h1>
<form action="{{ route('feedback.submit') }}" method="POST">
@csrf
<div class="form-group">
<label for="feedback">Your Feedback:</label>
<textarea name="feedback" id="feedback" class="form-control" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@endsection
Step 2: Handle Form Submission in Controller
public function submitFeedback(Request $request)
{
// Process the feedback
$request->validate([
'feedback' => 'required|max:1000',
]);
// Save feedback to the database or process it
return redirect()->route('feedback.thankyou');
}
Explanation:
- The form uses @csrf to include a CSRF token, which is validated automatically by Laravel to prevent CSRF attacks.
- The feedback.submit route handles the form submission and processes the feedback.

Comments
Post a Comment