"Day4 Laravel Assignments: Laravel Routing Basics"
Day4 Laravel Assignments
Laravel Routing Basics
Assignment 1: Define a Basic Route and Link It to a Controller
Objective:
Create a simple route that links to a controller method and returns a view.
Steps:
1. Define a Route:
o Open the routes/web.php file.
o Define a route that listens for the GET method at /welcome and links it to a controller method called showWelcome.
php
Copy code
Route::get('/welcome', [WelcomeController::class, 'showWelcome']);
2. Create a Controller:
o Use the php artisan make:controller command to create a controller named WelcomeController.
o Run the command:
bash
Copy code
php artisan make:controller WelcomeController
3. Define the Controller Method:
o Open the newly created app/Http/Controllers/WelcomeController.php.
o Add the showWelcome method inside the controller:
php
Copy code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WelcomeController extends Controller
{
public function showWelcome()
{
return view('welcome');
}
}
4. Create the View:
o In the resources/views folder, create a new file called welcome.blade.php.
o Add some simple content to this file:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome Page</title>
</head>
<body>
<h1>Welcome to the Laravel Application!</h1>
</body>
</html>
5. Test the Route:
o Start the Laravel development server by running the command:
bash
Copy code
php artisan serve
o Open your browser and visit http://localhost:8000/welcome. You should see the message "Welcome to the Laravel Application!" on the page.
Explanation:
- In this assignment, you created a route in web.php, linked it to a controller (WelcomeController), and returned a view. The route /welcome now triggers the showWelcome method in the controller, which returns the welcome.blade.php view.
Assignment 2: Dynamic Route with a Parameter
Objective:
Create a route with a dynamic parameter that can accept user input from the URL.
Steps:
1. Define a Route with a Parameter:
o Open routes/web.php.
o Define a route that accepts a name parameter and links it to a controller method called greetUser.
php
Copy code
Route::get('/greet/{name}', [GreetingController::class, 'greetUser']);
o Here, {name} is a dynamic parameter that will accept a value from the URL.
2. Create the Controller:
o Run the following command to create a new controller named GreetingController:
bash
Copy code
php artisan make:controller GreetingController
3. Define the Controller Method:
o Open GreetingController.php in the app/Http/Controllers directory.
o Add the greetUser method that accepts a $name parameter and returns a view:
php
Copy code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class GreetingController extends Controller
{
public function greetUser($name)
{
return view('greeting', ['name' => $name]);
}
}
4. Create the View:
o Create a new view file called greeting.blade.php in the resources/views folder.
o Inside greeting.blade.php, display a greeting message that includes the user's name:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Greeting Page</title>
</head>
<body>
<h1>Hello, {{ $name }}! Welcome to Laravel.</h1>
</body>
</html>
5. Test the Route:
o Start the Laravel development server if it’s not already running:
bash
Copy code
php artisan serve
o Open your browser and visit http://localhost:8000/greet/John. You should see the message "Hello, John! Welcome to Laravel."
Explanation:
- This assignment demonstrates how to define a route that accepts dynamic parameters. The route /greet/{name} captures the {name} segment and passes it to the greetUser method in the controller. The value of name is then displayed in the view using Laravel’s Blade syntax ({{ $name }}).
Assignment 3: Named Route
Objective:
Learn how to define and use named routes in Laravel.
Steps:
1. Define a Named Route:
o Open routes/web.php.
o Define a route that responds to /profile and assign it a name using the name() method:
php
Copy code
Route::get('/profile', [ProfileController::class, 'showProfile'])->name('profile.show');
2. Create the Controller:
o Run the following command to create a ProfileController:
bash
Copy code
php artisan make:controller ProfileController
3. Define the Controller Method:
o Open ProfileController.php in the app/Http/Controllers directory.
o Add the showProfile method that returns a view:
php
Copy code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function showProfile()
{
return view('profile');
}
}
4. Create the View:
o Create a new file called profile.blade.php in the resources/views folder and add the following content:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile Page</title>
</head>
<body>
<h1>Welcome to your profile page!</h1>
</body>
</html>
5. Generate a URL Using the Named Route:
o To generate a URL for the named route, you can use the route() helper function in Blade or elsewhere in your application. For example, in the resources/views/profile.blade.php file, you can add a link:
html
Copy code
<a href="{{ route('profile.show') }}">Go to Profile</a>
6. Test the Route:
o Start the Laravel development server:
bash
Copy code
php artisan serve
o Open your browser and visit http://localhost:8000/profile. You should see the "Welcome to your profile page!" message.
o Click on the "Go to Profile" link, and you should be redirected to the same profile page using the named route.
Explanation:
- Named routes allow you to reference routes by name instead of URL. This makes your code more maintainable, especially when URLs change. In this assignment, you defined a named route profile.show for the /profile route and generated its URL using route('profile.show').
Assignment 4: Route Grouping
Objective:
Learn how to group routes together for shared settings such as middleware or URL prefixes.
Steps:
1. Define Route Group with Prefix:
o Open routes/web.php.
o Group two routes (/dashboard and /profile) under a common URL prefix (/user):
php
Copy code
Route::prefix('user')->group(function () {
Route::get('/dashboard', [UserController::class, 'showDashboard']);
Route::get('/profile', [UserController::class, 'showProfile']);
});
2. Create the Controller:
o Run the following command to create a UserController:
bash
Copy code
php artisan make:controller UserController
3. Define the Controller Methods:
o Open UserController.php and add two methods: showDashboard and showProfile.
php
Copy code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function showDashboard()
{
return view('user.dashboard');
}
public function showProfile()
{
return view('user.profile');
}
}
4. Create the Views:
o Create two views in the resources/views/user folder: dashboard.blade.php and profile.blade.php.
dashboard.blade.php:
html
Copy code
<h1>Welcome to the Dashboard!</h1>
profile.blade.php:
html
Copy code
<h1>Welcome to your Profile Page!</h1>
5. Test the Routes:
o Start the Laravel development server:
bash
Copy code
php artisan serve
o Open your browser and visit http://localhost:8000/user/dashboard and http://localhost:8000/user/profile. You should see the respective pages.
Explanation:
- This assignment demonstrates how to group routes that share a common prefix (/user). Route grouping helps to keep your routes organized and reduces duplication when applying settings like middleware or prefixes.
Assignment 5: Using Middleware to Protect Routes
Objective:
Learn how to use middleware to protect routes that require authentication.
Steps:
1. Define Routes with Middleware:
o Open routes/web.php.
o Use the auth middleware to protect routes that require the user to be logged in.
php
Copy code
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth');
2. Create the Controller:
o Create a DashboardController by running the following command:
bash
Copy code
php artisan make:controller DashboardController
3. Define the Controller Method:
o Open DashboardController.php and add an index method:
php
Copy code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index()
{
return view('dashboard');
}
}
4. Create the View:
o Create a view file called dashboard.blade.php in the resources/views folder with some content:
html
Copy code
<h1>Welcome to the Dashboard!</h1>
5. Test the Middleware:
o Ensure that authentication is set up on your Laravel application (you can use Laravel’s built-in authentication system or any custom system).
o Visit http://localhost:8000/dashboard. You will be redirected to the login page if you're not logged in.
Explanation:
- Middleware is used in Laravel to filter HTTP requests. In this case, the auth middleware is protecting the /dashboard route, ensuring that only authenticated users can access it. If a user is not logged in, they will be redirected to the login page.
These assignments cover basic Laravel routing concepts, controllers, views, and middleware. Let me know if you need further clarification or additional examples!
4o mini
You said:
give more
ChatGPT said:
ChatGPT
Sure! Here are more assignments on Laravel Routing Basics with detailed solutions and explanations:
Assignment 6: Route Redirect
Objective:
Learn how to use route redirects in Laravel to redirect users from one route to another.
Steps:
1. Define a Route with a Redirect:
o Open routes/web.php.
o Create a route that redirects users from /old-url to /new-url:
php
Copy code
Route::redirect('/old-url', '/new-url');
2. Define a New Route:
o After setting the redirect, define the /new-url route that returns a simple view:
php
Copy code
Route::get('/new-url', function () {
return view('new-url');
});
3. Create the View for /new-url:
o Create a view file called new-url.blade.php in the resources/views folder:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New URL</title>
</head>
<body>
<h1>You have been redirected to the new URL!</h1>
</body>
</html>
4. Test the Redirect:
o Start the Laravel development server:
bash
Copy code
php artisan serve
o Visit http://localhost:8000/old-url. You should be redirected to http://localhost:8000/new-url and see the message "You have been redirected to the new URL!"
Explanation:
- The redirect() method allows you to redirect from one route to another. This is useful when you want to change the URL structure of your application and need to make sure users who visit old URLs are sent to new ones.
Assignment 7: Resource Routes
Objective:
Learn how to define resource routes in Laravel for common CRUD operations.
Steps:
1. Define Resource Route:
o Open routes/web.php.
o Use the Route::resource() method to define routes for a PostController:
php
Copy code
Route::resource('posts', PostController::class);
This single line will automatically generate all the routes needed for CRUD operations for the PostController. The routes are as follows:
o GET /posts -> index() method
o GET /posts/create -> create() method
o POST /posts -> store() method
o GET /posts/{post} -> show() method
o GET /posts/{post}/edit -> edit() method
o PUT/PATCH /posts/{post} -> update() method
o DELETE /posts/{post} -> destroy() method
2. Create the Controller:
o Run the following command to create a PostController:
bash
Copy code
php artisan make:controller PostController --resource
3. Define the Controller Methods:
o Open PostController.php in the app/Http/Controllers directory.
o Add the following methods for handling the CRUD operations:
php
Copy code
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
$posts = Post::all();
return view('posts.index', compact('posts'));
}
public function create()
{
return view('posts.create');
}
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required',
'content' => 'required',
]);
Post::create($validated);
return redirect()->route('posts.index');
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post)
{
$validated = $request->validate([
'title' => 'required',
'content' => 'required',
]);
$post->update($validated);
return redirect()->route('posts.index');
}
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index');
}
}
4. Create the Views:
o Create views for each of the CRUD operations (index.blade.php, create.blade.php, show.blade.php, edit.blade.php), following the standard pattern of displaying the data and providing forms for creating and editing posts.
5. Test the Routes:
o Visit the generated routes:
§ GET /posts -> List all posts
§ GET /posts/create -> Form to create a new post
§ POST /posts -> Submit new post
§ GET /posts/{post} -> View a specific post
§ GET /posts/{post}/edit -> Edit a specific post
§ PUT/PATCH /posts/{post} -> Update the post
§ DELETE /posts/{post} -> Delete the post
Explanation:
- The Route::resource() method automatically generates multiple routes for common CRUD operations. It is a convenient way to handle resourceful routes when you're building a resource like a blog post or user profile.
Assignment 8: Route Model Binding
Objective:
Learn how to use route model binding to automatically inject model instances into your route handler methods.
Steps:
1. Define a Route with Model Binding:
o Open routes/web.php.
o Define a route that accepts a post parameter and automatically binds it to the Post model:
php
Copy code
Route::get('/post/{post}', [PostController::class, 'show']);
2. Create the Controller:
o If you haven’t already created a PostController, run:
bash
Copy code
php artisan make:controller PostController
3. Define the Controller Method:
o Open PostController.php and add the show method that accepts a Post model instance:
php
Copy code
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
4. Create the View:
o Create a view show.blade.php in the resources/views/posts folder to display the details of the post:
html
Copy code
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
5. Test the Route:
o Visit http://localhost:8000/post/1 (assuming there is a post with an ID of 1 in your database).
o Laravel will automatically inject the Post model instance with the given id into the show method of the controller.
Explanation:
- Route model binding in Laravel allows you to automatically inject model instances into your route methods based on the route parameters. This eliminates the need to manually query the database for the record in the controller method.
Assignment 9: Route Prefixing and Middleware Combination
Objective:
Learn how to combine route prefixing with middleware to organize routes that share common logic and settings.
Steps:
1. Define a Route Group with Prefix and Middleware:
o Open routes/web.php.
o Group routes under a dashboard prefix and apply middleware to ensure that only authenticated users can access the routes.
php
Copy code
Route::prefix('dashboard')->middleware('auth')->group(function () {
Route::get('/', [DashboardController::class, 'index']);
Route::get('/settings', [DashboardController::class, 'settings']);
});
2. Create the Controller:
o Run the following command to create a DashboardController:
bash
Copy code
php artisan make:controller DashboardController
3. Define the Controller Methods:
o Open DashboardController.php and add the index and settings methods:
php
Copy code
public function index()
{
return view('dashboard.index');
}
public function settings()
{
return view('dashboard.settings');
}
4. Create the Views:
o Create the views index.blade.php and settings.blade.php in the resources/views/dashboard folder with some content for the dashboard and settings pages.
5. Test the Routes:
o Start the Laravel development server:
bash
Copy code
php artisan serve
o Try to visit http://localhost:8000/dashboard. If you are not authenticated, Laravel will redirect you to the login page. Once logged in, you should see the dashboard page.
Explanation:
- In this assignment, you used route grouping with both a prefix and middleware. This is useful for organizing routes that share common attributes, such as being part of a dashboard or requiring authentication. The prefix() method adds a common segment to the URL, and middleware('auth') ensures only authenticated users can access these routes.
Assignment 10: Customizing Route Response
Objective:
Learn how to return different types of responses from routes.
Steps:
1. Define Routes Returning Different Response Types:
o Open routes/web.php.
o Create routes that return different response types (text, JSON, and views).
php
Copy code
Route::get('/text', function () {
return response('Hello, World!', 200)->header('Content-Type', 'text/plain');
});
Route::get('/json', function () {
return response()->json(['message' => 'Hello, JSON World!']);
});
Route::get('/html', function () {
return view('welcome');
});
2. Test the Routes:
o Start the Laravel development server:
bash
Copy code
php artisan serve
o Visit http://localhost:8000/text, http://localhost:8000/json, and http://localhost:8000/html. Each route should return a different type of response: plain text, JSON, and HTML.
Explanation:
- Laravel allows you to return various types of responses from routes. You can return plain text with response(), JSON with response()->json(), or views with view(). This flexibility lets you handle different use cases in a web application.

Comments
Post a Comment