Assignments on Class 25: Introduction to PHP Frameworks

Rashmi Mishra
0

Assignments on Class 25: Introduction to PHP Frameworks


Here are some assignments to help students practice and deepen their understanding of PHP frameworks, specifically Laravel:

Assignment 1: Exploring PHP Frameworks

1.   Research Task:

o    Write a brief report (1-2 pages) on at least three different PHP frameworks, including Laravel. Discuss their features, advantages, and typical use cases.

o    Include information about their community support and documentation availability.

2.   Questions:

o    What are the key differences between using a framework and coding in plain PHP?

o    Why do you think using a framework could be beneficial for a team working on a web application?


Assignment 2: Setting Up Laravel

1.   Installation Task:

o    Install Laravel on your local machine following the steps provided in the lecture.

o    Document each step you took during the installation process, including any issues you encountered and how you resolved them.

2.   Basic Application Setup:

o    Create a new Laravel project named student-directory.

o    Configure the .env file for database access (use a test database if necessary).

o    Run the migrations and ensure that the necessary tables are created in your database.


Assignment 3: Creating Routes and Views

1.   Routing Task:

o    Define three different routes in your Laravel application:

§  A route for the homepage (e.g., /) that returns a welcome message.

§  A route for an "About" page (e.g., /about) that displays information about the application.

§  A route for a "Contact" page (e.g., /contact) that returns a simple contact form (you don’t need to process the form in this assignment).

2.   Views:

o    Create a Blade view for each route you defined, and ensure that they display relevant content.

o    Style the views using basic HTML and CSS (you can link a CSS file or use inline styles).


Assignment 4: Eloquent ORM Basics

1.   Database Task:

o    Create a new database table called students with the following columns: id, name, email, created_at, and updated_at.

o    Use Laravel migrations to create this table.

2.   Eloquent Model:

o    Create an Eloquent model for the students table.

o    Write a function in a controller to retrieve all students from the database and pass them to a view.

3.   Display Students:

o    Create a Blade view to display the list of students in a table format.


Assignment 5: Security Features in Laravel

1.   Research Task:

o    Write a short report (1 page) discussing the security features built into Laravel.

o    Explain how these features can protect your web application from common vulnerabilities.

2.   Implementation Task:

o    Implement basic form validation in one of the routes you created earlier. Ensure that the form requires users to provide a valid email address and name.

o    Display appropriate error messages on the view if validation fails.


Assignment 6: Working with Laravel Blade Templates

1.   Template Inheritance:

o    Create a base Blade template called layout.blade.php that includes the common HTML structure (header, footer, and navigation menu).

o    Use this layout in at least two other views you created previously (e.g., "About" and "Contact" pages) to demonstrate template inheritance.

2.   Dynamic Content:

o    In the "About" page, add dynamic content by using Blade syntax to display the current date and time.


Assignment 7: Building a Simple CRUD Application

1.   CRUD Functionality:

o    Build a simple CRUD (Create, Read, Update, Delete) application for managing students using the students table you created earlier.

o    Implement the following features:

§  Create: A form to add new students to the database.

§  Read: A page to list all students with options to view details.

§  Update: A form to edit existing student records.

§  Delete: An option to delete student records.

2.   Routing and Controller:

o    Define routes for each of the CRUD operations in your web.php file.

o    Create a controller named StudentController to handle the logic for each operation.


Assignment 8: Implementing Authentication

1.   User Authentication:

o    Set up Laravel’s built-in authentication system using Laravel Breeze or Laravel Jetstream.

o    Create a registration page that allows new users to sign up and a login page for existing users.

2.   Authorization:

o    Restrict access to the student management routes (CRUD operations) so that only authenticated users can access them.

o    Redirect users to the login page if they are not authenticated.


Assignment 9: Using Laravel Artisan

1.   Artisan Commands:

o    Explore Laravel Artisan commands. Create a list of at least five useful Artisan commands and explain what each command does.

o    Use the php artisan make:model command to create a model for a new table you define (e.g., courses).

2.   Custom Artisan Command:

o    Create a simple custom Artisan command that outputs “Hello, World!” when executed. Use the command:

php artisan make:command HelloWorld

o    Implement the logic in the generated command file.


Assignment 10: API Development with Laravel

1.   RESTful API:

o    Develop a simple RESTful API for the student management system. Implement the following endpoints:

§  GET /api/students - Retrieve a list of students.

§  POST /api/students - Create a new student record.

§  PUT /api/students/{id} - Update an existing student record.

§  DELETE /api/students/{id} - Delete a student record.

2.   Using Postman:

o    Use Postman or a similar tool to test your API endpoints. Document the requests and responses for each endpoint.


Assignment 11: Deployment of Laravel Application

1.   Deployment Plan:

o    Write a short report (1-2 pages) outlining the steps necessary to deploy your Laravel application to a web server (like shared hosting or a cloud provider).

o    Include details about environment configuration and database migration in the deployment process.

2.   Demo Application:

o    Deploy your CRUD application to a live server (if possible) or a cloud platform like Heroku or Vercel. Provide the URL to your instructor for review.


Assignment 12: Testing in Laravel

1.   Unit Testing:

o    Write unit tests for the functions in your StudentController to ensure they are working as expected. Use the built-in testing features of Laravel to create and run your tests.

o    Document how to run the tests and what results you expect.

2.   Feature Testing:

o    Create feature tests for the authentication process (registration and login) to ensure users can successfully register and log in.



Assignment 1: Exploring PHP Frameworks

Research Task Solution:

1.   Research Three PHP Frameworks:

o    Laravel:

§  Features: Eloquent ORM, Blade templating, Artisan command line.

§  Advantages: Great community support, extensive documentation, easy routing, built-in security features.

§  Use Cases: Web applications, RESTful APIs, e-commerce sites.

o    CodeIgniter:

§  Features: Lightweight, fast performance, simple installation.

§  Advantages: Minimal configuration, easy to learn, suitable for small projects.

§  Use Cases: Small to medium-sized applications, prototyping.

o    Symfony:

§  Features: Modular components, built-in testing support, high flexibility.

§  Advantages: Robust architecture, suitable for enterprise-level applications, extensive documentation.

§  Use Cases: Large-scale applications, complex projects requiring custom solutions.

2.   Questions:

o    Differences: Frameworks provide structure and reusable code, making development faster and more efficient compared to plain PHP, which requires writing everything from scratch.

o    Benefits of Frameworks: Frameworks enforce coding standards, making it easier for teams to collaborate, and they often include security features that protect against common vulnerabilities.


Assignment 2: Setting Up Laravel

Installation Task Solution:

1.   Install Laravel:

o    Open the terminal and run the following command:

composer create-project --prefer-dist laravel/laravel student-directory

o    Explanation: This command installs a new Laravel project in a folder named student-directory.

2.   Document Installation Steps:

o    Note down each step you performed:

§  Installed Composer.

§  Created a new Laravel project.

§  Navigated into the project directory.

Basic Application Setup:

1.   Navigate to Project Folder:

cd student-directory

2.   Configure Database:

o    Open the .env file in a text editor and update the database settings:

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=student_db

DB_USERNAME=root

DB_PASSWORD=

3.   Run Migrations:

php artisan migrate

o    Explanation: This command runs the default migrations, creating necessary tables in your database.


Assignment 3: Creating Routes and Views

Routing Task Solution:

1.   Define Routes:

o    Open the routes/web.php file and add the following routes:

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

    return view('welcome');

});

 

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

    return view('about');

});

 

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

    return view('contact');

});

2.   Create Views:

o    Create a new directory for views:

mkdir resources/views

o    Create about.blade.php and contact.blade.php files in resources/views/.

3.   About Page Content (about.blade.php):

<!DOCTYPE html>

<html>

<head>

    <title>About</title>

</head>

<body>

    <h1>About Us</h1>

    <p>This application manages student data.</p>

    <p>Current date and time: {{ date('Y-m-d H:i:s') }}</p>

</body>

</html>

4.   Contact Page Content (contact.blade.php):

<!DOCTYPE html>

<html>

<head>

    <title>Contact</title>

</head>

<body>

    <h1>Contact Us</h1>

    <form>

        <label>Name:</label>

        <input type="text" name="name" required>

        <label>Email:</label>

        <input type="email" name="email" required>

        <input type="submit" value="Submit">

    </form>

</body>

</html>


Assignment 4: Eloquent ORM Basics

Database Task Solution:

1.   Create Migration for students Table:

o    Run the following command to create a migration:

php artisan make:migration create_students_table

o    Open the generated migration file in database/migrations and modify it:

public function up()

{

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

        $table->id();

        $table->string('name');

        $table->string('email')->unique();

        $table->timestamps();

    });

}

2.   Run Migrations:

php artisan migrate

Eloquent Model Solution:

1.   Create Eloquent Model:

php artisan make:model Student

2.   Controller for Students:

o    Create a controller:

php artisan make:controller StudentController

3.   Retrieve Students:

o    In StudentController.php, add:

public function index()

{

    $students = Student::all();

    return view('students.index', compact('students'));

}

4.   Display Students:

o    Create students/index.blade.php:

<!DOCTYPE html>

<html>

<head>

    <title>Students List</title>

</head>

<body>

    <h1>Students</h1>

    <table>

        <tr>

            <th>Name</th>

            <th>Email</th>

        </tr>

        @foreach ($students as $student)

            <tr>

                <td>{{ $student->name }}</td>

                <td>{{ $student->email }}</td>

            </tr>

        @endforeach

    </table>

</body>

</html>


Assignment 5: Security Features in Laravel

Research Task Solution:

1.   Laravel Security Features:

o    CSRF Protection: Automatically protects against cross-site request forgery attacks.

o    XSS Protection: Escapes output to prevent cross-site scripting.

o    Validation: Provides built-in validation methods to ensure user inputs are correct.

Implementation Task Solution:

1.   Implement Basic Form Validation:

o    In StudentController.php, add:

public function store(Request $request)

{

    $request->validate([

        'name' => 'required|max:255',

        'email' => 'required|email|unique:students,email',

    ]);

 

    Student::create($request->all());

    return redirect()->route('students.index');

}

2.   Display Error Messages:

o    Update your form in the Blade view to show errors:

@if ($errors->any())

    <div>

        <ul>

            @foreach ($errors->all() as $error)

                <li>{{ $error }}</li>

            @endforeach

        </ul>

    </div>

@endif


Assignment 6: Working with Laravel Blade Templates

Template Inheritance Solution:

1.   Create Base Layout (layout.blade.php):

<!DOCTYPE html>

<html>

<head>

    <title>@yield('title')</title>

</head>

<body>

    <header>

        <nav>

            <a href="/">Home</a>

            <a href="/about">About</a>

            <a href="/contact">Contact</a>

        </nav>

    </header>

 

    <main>

        @yield('content')

    </main>

 

    <footer>

        <p>&copy; 2024 Student Directory</p>

    </footer>

</body>

</html>

2.   Update Other Views:

o    Modify about.blade.php:

@extends('layout')

 

@section('title', 'About Us')

 

@section('content')

    <h1>About Us</h1>

    <p>This application manages student data.</p>

    <p>Current date and time: {{ date('Y-m-d H:i:s') }}</p>

@endsection

o    Modify contact.blade.php similarly to use the layout.


Assignment 7: Building a Simple CRUD Application

CRUD Functionality Solution:

1.   Create CRUD Routes:

Route::resource('students', StudentController::class);

2.   Update StudentController:

o    Add methods for each CRUD operation:

public function create()

{

    return view('students.create');

}

 

public function store(Request $request)

{

    // Validation and storing logic

}

 

public function edit($id)

{

    $student = Student::find($id);

    return view('students.edit', compact('student'));

}

 

public function update(Request $request, $id)

{

    // Validation and update logic

}

 

public function destroy($id)

{

    Student::destroy($id);

    return redirect()->route('students.index');

}

3.   Create Views for Create and Edit:

o    Create View (students/create.blade.php):

@extends('layout')

 

@section('title', 'Add Student')

 

@section('content')

    <h1>Add Student</h1>

    <form action="{{ route('students.store') }}" method="POST">

        @csrf

        <label>Name:</label>

        <input type="text" name="name" required>

        <label>Email:</label>

        <input type="email" name="email" required>

        <input type="submit" value="Add">

    </form>

@endsection

o    Edit View (students/edit.blade.php):

@extends('layout')

 

@section('title', 'Edit Student')

 

@section('content')

    <h1>Edit Student</h1>

    <form action="{{ route('students.update', $student->id) }}" method="POST">

        @csrf

        @method('PUT')

        <label>Name:</label>

        <input type="text" name="name" value="{{ $student->name }}" required>

        <label>Email:</label>

        <input type="email" name="email" value="{{ $student->email }}" required>

        <input type="submit" value="Update">

    </form>

@endsection


Assignment 8: Deploying Laravel Application

Deployment Task Solution:

1.   Prepare for Deployment:

o    Ensure the application is production-ready:

§  Set the APP_ENV to production in the .env file.

§  Set the APP_DEBUG to false.

2.   Deploying to a Server:

o    Use shared hosting or VPS to upload files:

§  Zip the project files and upload them via FTP.

§  Ensure Composer is installed on the server and run:

composer install --optimize-autoloader --no-dev

3.   Configure Web Server:

o    Ensure the server points to the public directory of the Laravel application.

o    Set up the appropriate database connection.


Assignment 1: Exploring PHP Frameworks

Research Task Solutions

1.   Research Three PHP Frameworks:

o    Laravel:

§  Features:

§  Eloquent ORM: An object-relational mapper that allows interaction with the database using an elegant syntax.

§  Blade Templating Engine: A powerful templating engine that allows for dynamic content creation in views.

§  Artisan Command Line Interface: A built-in tool for running various tasks like migrations, database seeding, and running tests.

§  Advantages:

§  Strong community support and extensive documentation.

§  Built-in features for security (CSRF protection, validation).

§  Easy routing and middleware support.

§  Use Cases:

§  Suitable for building web applications, RESTful APIs, and e-commerce sites.

o    CodeIgniter:

§  Features:

§  Lightweight and fast performance.

§  Simple installation with minimal configuration required.

§  Supports MVC architecture.

§  Advantages:

§  Ideal for small to medium-sized applications.

§  Easy to learn and get started with.

§  Use Cases:

§  Best for small projects, rapid prototyping, and projects with simple requirements.

o    Symfony:

§  Features:

§  Modular components that can be used independently or together.

§  Built-in testing support and a powerful form builder.

§  Highly flexible architecture.

§  Advantages:

§  Suitable for enterprise-level applications due to its robustness.

§  Extensive documentation and a strong community.

§  Use Cases:

§  Large-scale applications, complex projects requiring customization, and API development.

2.   Questions:

o    Differences Between Using a Framework and Plain PHP:

§  Frameworks provide a structured way to build applications with reusable components, making development faster and easier compared to plain PHP, where everything must be coded from scratch.

o    Benefits of Frameworks:

§  Frameworks enforce best practices, improve code quality, and often include security features to protect applications from common vulnerabilities.


Assignment 2: Setting Up Laravel

Installation Task Solutions

1.   Install Laravel:

o    Open your terminal and run the following command:

composer create-project --prefer-dist laravel/laravel student-directory

o    Explanation: This command creates a new Laravel project in a folder named student-directory, downloading all necessary files and dependencies.

2.   Document Installation Steps:

o    Step 1: Ensure Composer is installed on your machine.

o    Step 2: Create a new Laravel project by running the above command.

o    Step 3: Navigate into the project directory:

cd student-directory

Basic Application Setup

1.   Configure Database:

o    Open the .env file in a text editor and update the database connection settings:

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=student_db

DB_USERNAME=root

DB_PASSWORD=

o    Ensure you create the database student_db in your MySQL server.

2.   Run Migrations:

o    Run the following command to create default tables:

php artisan migrate

o    Explanation: This command applies migrations, which create the necessary tables in your database.


Assignment 3: Creating Routes and Views

Routing Task Solutions

1.   Define Routes:

o    Open the routes/web.php file and add the following routes:

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

    return view('welcome');

});

 

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

    return view('about');

});

 

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

    return view('contact');

});

2.   Create Views:

o    Create a new directory for views:

mkdir resources/views

o    Create about.blade.php and contact.blade.php files in resources/views/.

3.   About Page Content (about.blade.php):

<!DOCTYPE html>

<html>

<head>

    <title>About</title>

</head>

<body>

    <h1>About Us</h1>

    <p>This application manages student data.</p>

    <p>Current date and time: {{ date('Y-m-d H:i:s') }}</p>

</body>

</html>

4.   Contact Page Content (contact.blade.php):

<!DOCTYPE html>

<html>

<head>

    <title>Contact</title>

</head>

<body>

    <h1>Contact Us</h1>

    <form>

        <label>Name:</label>

        <input type="text" name="name" required>

        <label>Email:</label>

        <input type="email" name="email" required>

        <input type="submit" value="Submit">

    </form>

</body>

</html>


Assignment 4: Eloquent ORM Basics

Database Task Solutions

1.   Create Migration for students Table:

o    Run the following command to create a migration:

php artisan make:migration create_students_table

o    Open the generated migration file in database/migrations and modify it:

public function up()

{

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

        $table->id();

        $table->string('name');

        $table->string('email')->unique();

        $table->timestamps();

    });

}

2.   Run Migrations:



php artisan migrate

Eloquent Model Solution

1.   Create Eloquent Model:

php artisan make:model Student

2.   Controller for Students:

o    Create a controller:

php artisan make:controller StudentController

3.   Retrieve Students:

o    In StudentController.php, add:

public function index()

{

    $students = Student::all();

    return view('students.index', compact('students'));

}

4.   Display Students:

o    Create students/index.blade.php:


<!DOCTYPE html>

<html>

<head>

    <title>Students List</title>

</head>

<body>

    <h1>Students</h1>

    <table>

        <tr>

            <th>Name</th>

            <th>Email</th>

        </tr>

        @foreach ($students as $student)

            <tr>

                <td>{{ $student->name }}</td>

                <td>{{ $student->email }}</td>

            </tr>

        @endforeach

    </table>

</body>

</html>


Assignment 5: Security Features in Laravel

Research Task Solution

1.   Laravel Security Features:

o    CSRF Protection: Automatically protects against cross-site request forgery attacks by generating a token for forms.

o    XSS Protection: Escapes output to prevent cross-site scripting, ensuring that user input is safe to display.

o    Validation: Provides built-in validation methods to ensure user inputs are correct and secure.

Implementation Task Solution

1.   Implement Basic Form Validation:

o    In StudentController.php, add:

public function store(Request $request)

{

    $request->validate([

        'name' => 'required|max:255',

        'email' => 'required|email|unique:students,email',

    ]);

 

    Student::create($request->all());

    return redirect()->route('students.index');

}

2.   Display Error Messages:

o    Update your form in the Blade view to show errors:

@if ($errors->any())

    <div>

        <ul>

            @foreach ($errors->all() as $error)

                <li>{{ $error }}</li>

            @endforeach

        </ul>

    </div>

@endif


Assignment 6: Working with Laravel Blade Templates

Template Inheritance Solution

1.   Create Base Layout (layout.blade.php):

<!DOCTYPE html>

<html>

<head>

    <title>@yield('title')</title>

</head>

<body>

    <header>

        <nav>

            <a href="/">Home</a>

            <a href="/about">About</a>

            <a href="/contact">Contact</a>

        </nav>

    </header>

 

    <main>

        @yield('content')

    </main>

 

    <footer>

        <p>&copy; 2024 Student Directory</p>

    </footer>

</body>

</html>

2.   Update Other Views:

o    Modify about.blade.php:

@extends('layout')

 

@section('title', 'About Us')

 

@section('content')

    <h1>About Us</h1>

    <p>This application manages student data.</p>

@endsection


Assignment 7: CRUD Operations for Students

Complete CRUD Solution

1.   Create Routes:

o    Update routes/web.php:

Route::resource('students', StudentController::class);

2.   Create Views for CRUD Operations:

o    Create View (students/create.blade.php):

@extends('layout')

 

@section('title', 'Add Student')

 

@section('content')

    <h1>Add Student</h1>

    <form action="{{ route('students.store') }}" method="POST">

        @csrf

        <label>Name:</label>

        <input type="text" name="name" required>

        <label>Email:</label>

        <input type="email" name="email" required>

        <input type="submit" value="Add">

    </form>

@endsection

o    Edit View (students/edit.blade.php):

@extends('layout')

 

@section('title', 'Edit Student')

 

@section('content')

    <h1>Edit Student</h1>

    <form action="{{ route('students.update', $student->id) }}" method="POST">

        @csrf

        @method('PUT')

        <label>Name:</label>

        <input type="text" name="name" value="{{ $student->name }}" required>

        <label>Email:</label>

        <input type="email" name="email" value="{{ $student->email }}" required>

        <input type="submit" value="Update">

    </form>

@endsection

3.   Controller Methods:

o    Update StudentController.php:

public function create()

{

    return view('students.create');

}

 

public function store(Request $request)

{

    $request->validate([

        'name' => 'required|max:255',

        'email' => 'required|email|unique:students,email',

    ]);

 

    Student::create($request->all());

    return redirect()->route('students.index');

}

 

public function edit($id)

{

    $student = Student::findOrFail($id);

    return view('students.edit', compact('student'));

}

 

public function update(Request $request, $id)

{

    $request->validate([

        'name' => 'required|max:255',

        'email' => 'required|email|unique:students,email,' . $id,

    ]);

 

    $student = Student::findOrFail($id);

    $student->update($request->all());

    return redirect()->route('students.index');

}

 

public function destroy($id)

{

    $student = Student::findOrFail($id);

    $student->delete();

    return redirect()->route('students.index');

}


Assignment 8: Deploying Laravel Application

Deployment Task Solution

1.   Prepare for Deployment:

o    Set environment variables in the .env file:

APP_ENV=production

APP_DEBUG=false

2.   Deploying to a Server:

o    Zip your project files and upload them to your server via FTP.

o    Ensure Composer is installed on the server and run:

composer install --optimize-autoloader --no-dev

3.   Configure Web Server:

o    Ensure your web server is pointing to the public directory of your Laravel application.

4.   Run Migrations on the server:

php artisan migrate --force



Post a Comment

0Comments

Post a Comment (0)