"Day3 Laravel Assignments: Understanding and Implementing the MVC Architecture in Laravel"
Assignment 1: Understanding and Implementing the MVC Architecture in Laravel
Objective:
To understand the structure of Laravel’s MVC architecture and implement it by creating a simple blog application where a user can view posts.
Assignment Details:
1. Create a new Laravel project.
2. Set up the database:
o Create a database named blog.
o Create a posts table with the columns: id, title, body, created_at, and updated_at.
3. Create a Model for Posts.
4. Create a Controller to handle the logic.
5. Create a View to display the posts.
6. Define routes to link the controller to the view.
Step-by-Step Solution:
Step 1: Create a New Laravel Project
If you don’t have Laravel installed, use Composer to install Laravel:
composer create-project --prefer-dist laravel/laravel blog
This command will create a new Laravel project in a folder named blog.
Step 2: Set Up the Database
1. Create the Database: Open your database management tool (like phpMyAdmin) and create a new database called blog.
2. Create the posts Table: In the Laravel project, open the database/migrations directory. Create a migration file for the posts table.
Run the command:
php artisan make:migration create_posts_table
Inside the generated migration file (found in database/migrations), define the posts table structure:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
To create the table in the database, run:
php artisan migrate
Step 3: Create the Model for Posts
Models in Laravel are used to interact with the database. To create a Post model, use the Artisan command:
php artisan make:model Post
This will generate a Post.php file in the app/Models directory. Open the file and ensure that the $fillable property is set correctly:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'body']; // Allows mass assignment for these fields
}
Step 4: Create the Controller
Controllers in Laravel handle user requests and return views or data. To create a PostController, use this command:
php artisan make:controller PostController
This will create a file PostController.php in the app/Http/Controllers directory. Open the controller and add the index method to display posts:
namespace App\Http\Controllers;
use App\Models\Post;
class PostController extends Controller
{
public function index()
{
// Get all posts from the database
$posts = Post::all();
// Return the view and pass the posts data
return view('posts.index', ['posts' => $posts]);
}
}
Step 5: Create the View
Views in Laravel are typically stored in the resources/views directory. In this case, we will create a posts folder and an index.blade.php file inside it to display the list of posts.
Create the following directory structure:
resources/views/posts/index.blade.php
Inside the index.blade.php file, write the following code to display the posts:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Posts</title>
</head>
<body>
<h1>All Posts</h1>
@foreach ($posts as $post)
<div>
<h2>{{ $post->title }}</h2>
<p>{{ $post->body }}</p>
</div>
@endforeach
</body>
</html>
This view will loop through all the posts passed from the controller and display their title and body.
Step 6: Define Routes
To make the controller accessible, we need to define a route in routes/web.php.
Open routes/web.php and add the following line to map the route to the PostController@index method:
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);
Step 7: Test the Application
Now that we’ve completed the setup, it's time to test the application.
1. Start the Laravel development server:
php artisan serve
2. Open your browser and navigate to:
http://localhost:8000/posts
3. You should see the list of posts displayed.
Assignment 2: Adding a New Post (Create Post)
Objective:
Learn to add new posts to the database using Laravel’s MVC structure.
Assignment Details:
1. Create a Form to Add Posts.
2. Add a New Route to Show the Form.
3. Create a Method in the Controller to Handle Form Submission.
Step-by-Step Solution:
Step 1: Add the Form to Create a New Post
First, create a new view file called create.blade.php in the resources/views/posts directory. This will contain the form to create a new post.
Create the following structure:
resources/views/posts/create.blade.php
Inside this file, create a simple form to accept a post’s title and body:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Post</title>
</head>
<body>
<h1>Create a New Post</h1>
<form action="/posts" method="POST">
@csrf
<label for="title">Title:</label>
<input type="text" id="title" name="title" required>
<br>
<label for="body">Body:</label>
<textarea id="body" name="body" required></textarea>
<br>
<button type="submit">Create Post</button>
</form>
</body>
</html>
Step 2: Add a Route to Show the Form
Now, add a new route in routes/web.php to show the form for creating a new post:
Route::get('/posts/create', [PostController::class, 'create']);
This route will direct the user to a view where they can fill in the post title and body.
Step 3: Add a Method to Handle Form Submission
In PostController.php, add a new method create() to show the form, and a store() method to handle the form submission:
public function create()
{
return view('posts.create'); // Show the form
}
public function store(Request $request)
{
// Validate the form data
$request->validate([
'title' => 'required',
'body' => 'required',
]);
// Create a new post
Post::create([
'title' => $request->title,
'body' => $request->body,
]);
// Redirect to the posts list
return redirect('/posts');
}
Step 4: Define the Store Route
Add the following POST route to routes/web.php to handle form submission:
Route::post('/posts', [PostController::class, 'store']);
Step 5: Test the Create Functionality
1. Visit http://localhost:8000/posts/create in the browser.
2. Fill out the form and submit it.
3. After submission, the page will redirect to the list of posts, and you should see your new post listed.
Assignment 3: Displaying Post Details (Show Method)
Objective:
Learn how to display individual post details by using Laravel’s MVC architecture.
Assignment Details:
1. Add a Route to Display a Single Post.
2. Create a Method in the Controller to Fetch and Display a Post.
3. Create a View to Display Post Details.
Step-by-Step Solution:
Step 1: Add the Route to Display a Single Post
In routes/web.php, add a new route that will handle displaying the details of a single post. This route should accept a post ID as a parameter:
Route::get('/posts/{id}', [PostController::class, 'show']);
Step 2: Add the Show Method in the Controller
In PostController.php, add the show() method to fetch a post by its ID and pass it to a view:
public function show($id)
{
// Find the post by its ID
$post = Post::findOrFail($id);
// Return the view and pass the post data
return view('posts.show', ['post' => $post]);
}
- The findOrFail() method is used to fetch the post by ID. If the post is not found, it will throw a 404 error.
Step 3: Create the View to Display Post Details
Now, create a view that will display the details of a single post. Create a new file called show.blade.php in resources/views/posts.
The file structure should be:
resources/views/posts/show.blade.php
Inside the show.blade.php file, add the following code to display the post's title and body:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $post->title }}</title>
</head>
<body>
<h1>{{ $post->title }}</h1>
<p>{{ $post->body }}</p>
<a href="/posts">Back to Posts</a>
</body>
</html>
Here, {{ $post->title }} and {{ $post->body }} display the title and body of the post that was passed from the controller.
Step 4: Test the Show Functionality
1. Start the Laravel development server if it’s not already running:
php artisan serve
2. Open your browser and visit http://localhost:8000/posts/{id}, where {id} is the ID of a post in your database.
For example:
http://localhost:8000/posts/1
3. You should see the details of the selected post.
Assignment 4: Editing a Post (Update Method)
Objective:
Learn how to edit an existing post using Laravel’s MVC structure.
Assignment Details:
1. Create a Route to Display the Edit Form.
2. Create a Method in the Controller to Show the Edit Form.
3. Create a View for Editing the Post.
4. Add a Method in the Controller to Handle the Update.
Step-by-Step Solution:
Step 1: Add the Route to Show the Edit Form
In routes/web.php, add a new route to show the form for editing a post. This route will accept the post ID as a parameter:
Route::get('/posts/{id}/edit', [PostController::class, 'edit']);
Step 2: Add the Edit Method in the Controller
In PostController.php, add the edit() method to fetch the post by ID and return the view to edit the post:
public function edit($id)
{
// Find the post by its ID
$post = Post::findOrFail($id);
// Return the view and pass the post data
return view('posts.edit', ['post' => $post]);
}
Step 3: Create the Edit Form View
Create a new view file named edit.blade.php in resources/views/posts.
File structure:
resources/views/posts/edit.blade.php
Inside edit.blade.php, create a form that allows users to edit the post’s title and body:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Post</title>
</head>
<body>
<h1>Edit Post</h1>
<form action="/posts/{{ $post->id }}" method="POST">
@csrf
@method('PUT') <!-- This is to indicate it's a PUT request -->
<label for="title">Title:</label>
<input type="text" id="title" name="title" value="{{ $post->title }}" required>
<br>
<label for="body">Body:</label>
<textarea id="body" name="body" required>{{ $post->body }}</textarea>
<br>
<button type="submit">Update Post</button>
</form>
</body>
</html>
This form will pre-fill the fields with the existing post data and submit a PUT request to update the post.
Step 4: Add the Route to Handle the Form Submission
In routes/web.php, add a route to handle the form submission and update the post in the database:
Route::put('/posts/{id}', [PostController::class, 'update']);
Step 5: Add the Update Method in the Controller
In PostController.php, add the update() method to handle the form submission and update the post data in the database:
public function update(Request $request, $id)
{
// Validate the form data
$request->validate([
'title' => 'required',
'body' => 'required',
]);
// Find the post by its ID
$post = Post::findOrFail($id);
// Update the post with the new data
$post->update([
'title' => $request->title,
'body' => $request->body,
]);
// Redirect to the posts list
return redirect('/posts');
}
Step 6: Test the Edit and Update Functionality
1. Start the Laravel development server if it’s not already running:
php artisan serve
2. Open your browser and visit http://localhost:8000/posts/{id}/edit, where {id} is the ID of the post you want to edit.
For example:
http://localhost:8000/posts/1/edit
3. Edit the post and submit the form.
4. The page should redirect to the posts list, and the updated post will be displayed.
Assignment 5: Deleting a Post (Delete Method)
Objective:
Learn how to delete a post from the database using Laravel’s MVC structure.
Assignment Details:
1. Create a Route to Delete a Post.
2. Create a Method in the Controller to Handle Deleting a Post.
3. Add a Delete Button to the Post Details View.
Step-by-Step Solution:
Step 1: Add the Route to Delete a Post
In routes/web.php, add a route to delete a post by its ID:
Route::delete('/posts/{id}', [PostController::class, 'destroy']);
Step 2: Add the Destroy Method in the Controller
In PostController.php, add the destroy() method to delete the post from the database:
public function destroy($id)
{
// Find the post by its ID
$post = Post::findOrFail($id);
// Delete the post from the database
$post->delete();
// Redirect to the posts list
return redirect('/posts');
}
Step 3: Add a Delete Button to the Post Details View
In resources/views/posts/show.blade.php, add a form with a delete button to allow the user to delete the post:
<form action="/posts/{{ $post->id }}" method="POST">
@csrf
@method('DELETE') <!-- This is to indicate it's a DELETE request -->
<button type="submit">Delete Post</button>
</form>
Step 4: Test the Delete Functionality
1. Start the Laravel development server if it’s not already running:
php artisan serve
2. Open your browser and visit http://localhost:8000/posts/{id}, where {id} is the ID of the post you want to delete.
For example:
http://localhost:8000/posts/1
3. Click the “Delete Post” button.
4. The post will be deleted, and you will be redirected to the list of posts.
Conclusion
These assignments cover the fundamental CRUD operations in Laravel: creating, reading, updating, and deleting posts.

Comments
Post a Comment