Day 1 Laravel Assignments: Kickstart Your Journey

  


Day 1 Laravel Assignments


Kickstart Your Journey


Follow the step-by-step instructions provided and attempt each task. 


Assignment 1: Install Laravel and Set Up Your First Project

Objective: Install Laravel and set up your first Laravel project.

Instructions:

1.   Install Composer (if not installed yet) from getcomposer.org.

2.   Create a new Laravel project named myfirstlaravel.

3.   Open the terminal and navigate to your Laravel project directory.

4.   Start the Laravel development server and access your application via http://localhost:8000.

Solution:

1.   Install Composer:

o    Go to the Composer website and download the Composer installer.

o    Follow the installation instructions specific to your operating system (Windows, macOS, or Linux).

2.   Create a New Laravel Project:

o    In your terminal, run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel myfirstlaravel

o    This command installs the latest version of Laravel and creates a directory called myfirstlaravel.

3.   Navigate to Your Project Directory:

cd myfirstlaravel

4.   Start the Laravel Development Server:

o    In your project directory, run the following Artisan command to start the built-in development server:

php artisan serve

5.   Access Your Application:

o    Open your web browser and go to http://localhost:8000. You should see the Laravel welcome page, which means everything is set up correctly.


Assignment 2: Explore Laravel's Folder Structure

Objective: Understand the Laravel project structure and its contents.

Instructions:

1.   Open your Laravel project in a code editor (e.g., VS Code).

2.   Explore the different directories in the Laravel project.

3.   Answer the following questions:

o    What does the app directory contain?

o    What is the purpose of the routes directory?

o    What is the purpose of the resources/views directory?

Solution:

1.   app Directory:

o    The app directory contains the core code of your application, including modelscontrollers, and middleware. It's where most of the application logic resides.

o    For example, app/Http/Controllers contains the controller files that handle requests and responses, while app/Models contains the models that represent database tables.

2.   routes Directory:

o    The routes directory contains the files where all the route definitions are made. The most common route file is web.php for defining web routes (URLs that load web pages).

o    You can also define API routes in the api.php file if you're building a RESTful API.

3.   resources/views Directory:

o    This directory holds the views that are rendered in the browser. Views are typically HTML files mixed with Blade templating engine code.

o    You can think of views as the front-end part of your application, where you define how the HTML will be displayed to the user.


Assignment 3: Understanding the MVC Architecture in Laravel

Objective: Learn about the MVC architecture used in Laravel.

Instructions:

1.   Create a simple ModelView, and Controller in your Laravel application.

2.   Display data from the model in a view using a controller.

3.   Answer the following questions:

o    How does the Model interact with the Controller in Laravel?

o    How does the Controller send data to the View?

Solution:

1.   Create a Model:

o    Laravel comes with an easy-to-use ORM (Eloquent), which allows you to define models for your database tables. To create a model, use the following command:

php artisan make:model Product

o    This command creates a Product model in app/Models/Product.php.

2.   Create a Controller:

o    Next, create a controller to manage the logic for displaying products:

php artisan make:controller ProductController

o    This command creates a ProductController in app/Http/Controllers/ProductController.php.

o    In the ProductController, define a method to fetch data from the model and pass it to a view:

<?php

namespace App\Http\Controllers;

use App\Models\Product;

use Illuminate\Http\Request;

class ProductController extends Controller

{

    public function index()

    {

        $products = Product::all();  // Fetch all products from the database

        return view('products.index', ['products' => $products]);

    }

}

3.   Create a View:

o    Now, create a Blade view to display the data. In the resources/views folder, create a new file called products/index.blade.php.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Products</title>

</head>

<body>

    <h1>Product List</h1>

    <ul>

        @foreach ($products as $product)

            <li>{{ $product->name }} - ${{ $product->price }}</li>

        @endforeach

    </ul>

</body>

</html>

4.   Define a Route:

o    Open the routes/web.php file and define a route to link to the controller's index method:

use App\Http\Controllers\ProductController;

Route::get('/products', [ProductController::class, 'index']);

5.   Test the Application:

o    Now, when you visit http://localhost:8000/products, you should see a list of products fetched from the database.

Explanation:

  • The Model (Product) represents the data layer and interacts with the database.
  • The Controller (ProductController) contains the logic for fetching data from the model and passing it to the view.
  • The View (products.index) displays the data to the user.

Assignment 4: Using Artisan Commands

Objective: Understand and practice using Artisan commands.

Instructions:

1.   List all available Artisan commands in Laravel.

2.   Create a database migration for a new posts table using Artisan.

3.   Answer the following questions:

o    What is the role of migrations in Laravel?

o    How do you run database migrations in Laravel?

Solution:

1.   List All Available Artisan Commands:

o    In your terminal, run the following command to see all the available Artisan commands:

php artisan list

o    This will display a list of all available commands, categorized by type (e.g., make, route, migrate).

2.   Create a Migration for posts Table:

o    To create a migration for a new table, run the following Artisan command:

php artisan make:migration create_posts_table --create=posts

o    This command creates a migration file in the database/migrations directory. The migration file contains the schema for the posts table.

3.   Run the Migration:

o    Open the migration file and define the schema for the posts table. Example:

public function up()

{

    Schema::create('posts', function (Blueprint $table) {

        $table->id();

        $table->string('title');

        $table->text('content');

        $table->timestamps();

    });

}

o    After defining the schema, run the migration using the following command:

php artisan migrate

Explanation:

  • Migrations in Laravel provide a way to version control your database schema. They ensure that the database structure is consistent across different environments (development, production, etc.).
  • The php artisan migrate command runs all the pending migrations and creates the corresponding tables in the database.

Assignment 5: Understanding Blade Templating

Objective: Learn about Blade templating and how it simplifies views in Laravel.

Instructions:

1.   Create a simple layout using Blade templating.

2.   Extend this layout in a new view.

3.   Answer the following questions:

o    What is Blade, and how does it differ from regular PHP in views?

o    How do you pass data from the controller to the view in Laravel?

Solution:

1.   Create a Blade Layout:

o    Create a new file 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')</title>

</head>

<body>

    <header>

        <h1>Welcome to My Laravel Application</h1>

    </header>

    <main>

        @yield('content')

    </main>

</body>

</html>

2.   Create a View that Extends the Layout:

o    Now, create a file resources/views/home.blade.php that extends the app.blade.php layout:

@extends('layouts.app')

@section('title', 'Home Page')

@section('content')

    <p>This is the home page of my Laravel app.</p>

@endsection

3.   Display the View:

o    In the ProductController, return the view as follows:

return view('home');

Explanation:

  • Blade is Laravel’s templating engine. It provides a simple and clean syntax for writing views, such as using @yield and @section to define and inject content into layouts.
  • Data Passing: In Laravel, you pass data from controllers to views using the view() function and the second parameter (an array of data). Example: return view('home', ['title' => 'Home Page']);.

Assignment 6: Working with Routes in Laravel

Objective: Learn how to define routes in Laravel and understand route parameters.

Instructions:

1.   Define two routes in the routes/web.php file:

o    GET route for the URL /hello that returns a simple "Hello, Laravel!" message.

o    GET route for the URL /user/{id} that takes a user ID as a parameter and returns a message saying, "User ID: {id}".

2.   Test both routes in the browser by visiting /hello and /user/{id}, where {id} is any number.

Solution:

1.   Define the Routes: In the routes/web.php file, define the two routes:

use Illuminate\Support\Facades\Route;

Route::get('/hello', function () {

    return 'Hello, Laravel!';

});

Route::get('/user/{id}', function ($id) {

    return 'User ID: ' . $id;

});

2.   Test the Routes:

o    Visit http://localhost:8000/hello in your browser, and you should see the message "Hello, Laravel!".

o    Visit http://localhost:8000/user/123, where 123 is the user ID, and you should see "User ID: 123".

Explanation:

  • In Laravel, routes are defined in the routes/web.php file.
  • The {id} in the /user/{id} route is a route parameter, which allows you to pass dynamic values in the URL and access them within the route closure.

Assignment 7: Working with Eloquent Models

Objective: Learn how to interact with the database using Eloquent models in Laravel.

Instructions:

1.   Create a new Product model and migration for a table named products. The table should contain the following columns: name, description, and price.

2.   Use Eloquent to create a new product entry in the database.

3.   Retrieve and display all products from the products table in a simple view.

Solution:

1.   Create the Product Model and Migration:

o    Run the following command to create a new model and migration:

php artisan make:model Product -m

o    This creates a model at app/Models/Product.php and a migration file in database/migrations.

o    Open the migration file and add the columns to the products table:

public function up()

{

    Schema::create('products', function (Blueprint $table) {

        $table->id();

        $table->string('name');

        $table->text('description');

        $table->decimal('price', 8, 2);

        $table->timestamps();

    });

}

2.   Run the Migration:

o    Run the migration to create the products table in the database:

php artisan migrate

3.   Insert a New Product Using Eloquent:

o    You can use Eloquent's create method to insert a new product into the database. Add the following code in the routes/web.php file:

use App\Models\Product;

Route::get('/add-product', function () {

    Product::create([

        'name' => 'Sample Product',

        'description' => 'This is a sample product.',

        'price' => 99.99,

    ]);

    return 'Product added!';

});

4.   Retrieve and Display All Products:

o    Create a view to display all products from the products table. First, define a route to fetch all products:

Route::get('/products', function () {

    $products = Product::all();

    return view('products.index', ['products' => $products]);

});

o    In the resources/views/products/index.blade.php file, display the products:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Products</title>

</head>

<body>

    <h1>Product List</h1>

    <ul>

        @foreach ($products as $product)

            <li>{{ $product->name }} - ${{ $product->price }}</li>

        @endforeach

    </ul>

</body>

</html>

5.   Test the Application:

o    Visit http://localhost:8000/products in your browser, and you should see the list of products.

Explanation:

  • Eloquent is Laravel's ORM (Object-Relational Mapping) that simplifies database interactions by allowing you to treat database records as objects.
  • The create method allows you to insert records, and all() retrieves all records from a table.

Assignment 8: Laravel Controllers and Views

Objective: Learn how to use controllers to handle requests and pass data to views.

Instructions:

1.   Create a new BlogController that will manage blog posts.

2.   Add a method to the controller that fetches blog posts from the database and passes them to a view.

3.   Display the blog posts in the view, including the title and content.

Solution:

1.   Create the BlogController:

o    Run the following command to create a controller:

php artisan make:controller BlogController

2.   Create the BlogPost Model and Migration:

o    Run the following command to create the BlogPost model and migration:

php artisan make:model BlogPost -m

o    In the migration file, add the necessary fields:

public function up()

{

    Schema::create('blog_posts', function (Blueprint $table) {

        $table->id();

        $table->string('title');

        $table->text('content');

        $table->timestamps();

    });

}

3.   Run the Migration:

o    Run the migration:

php artisan migrate

4.   Define the Controller Method:

o    Open BlogController.php and define the index method to fetch blog posts:

use App\Models\BlogPost;

public function index()

{

    $posts = BlogPost::all();

    return view('blog.index', ['posts' => $posts]);

}

5.   Create the Blog Post View:

o    Create the resources/views/blog/index.blade.php file to display the blog posts:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Blog Posts</title>

</head>

<body>

    <h1>Blog Posts</h1>

    <ul>

        @foreach ($posts as $post)

            <li>

                <h2>{{ $post->title }}</h2>

                <p>{{ $post->content }}</p>

            </li>

        @endforeach

    </ul>

</body>

</html>

6.   Define the Route:

o    In routes/web.php, define the route to call the controller method:

use App\Http\Controllers\BlogController;

Route::get('/blog', [BlogController::class, 'index']);

7.   Test the Application:

o    Visit http://localhost:8000/blog and verify that the blog posts are displayed correctly.

Explanation:

  • controller is a class that contains methods responsible for handling user requests and returning a response.
  • The controller fetches data from the database and sends it to the view, where the data is displayed to the user.
  • In this case, the controller method index fetches all blog posts and passes them to the blog.index view.

Assignment 9: Create and Use Blade Components

Objective: Learn how to use Blade components to reuse common UI elements.

Instructions:

1.   Create a Blade component for a navigation bar that can be reused in multiple views.

2.   Add a simple navigation menu with links to "Home," "About," and "Contact."

3.   Include the navigation bar in the layout of your application.

Solution:

1.   Create the Blade Component:

o    Run the following command to create a new Blade component:

php artisan make:component Navbar

o    This creates a component class at app/View/Components/Navbar.php and a Blade view at resources/views/components/navbar.blade.php.

2.   Define the Navigation Bar in the Component:

o    In resources/views/components/navbar.blade.php, define the HTML for the navigation menu:

<nav>

    <ul>

        <li><a href="{{ url('/') }}">Home</a></li>

        <li><a href="{{ url('/about') }}">About</a></li>

        <li><a href="{{ url('/contact') }}">Contact</a></li>

    </ul>

</nav>

3.   Include the Component in the Layout:

o    In resources/views/layouts/app.blade.php, include the navigation component:

<x-navbar />

4.   Test the Application:

o    Now, when you load any page that uses the app.blade.php layout, you should see the navigation bar displayed at the top of the page.

Explanation:

  • Blade components allow you to define reusable pieces of code for UI elements like navigation bars, headers, or footers.
  • The <x-navbar /> syntax is used to include the Navbar component in any Blade view.

Comments

Popular posts from this blog

MCQs Of Day CRUD 8 Operations with Eloquent

Lecture Notes Of Day 24: Laravel Policies

MCQs of Day 7 Eloquent ORM Basics