Assignments Of Day 13 Laravel API Development

 Assignments Of Day 13 

Laravel API Development

Assignments on Laravel API Development

Assignment 1: Create a Category API

1.  Create a new model, migration, and controller for a Category resource.

2.  Define the schema in the migration with fields:

o    id

o    name (string)

o    description (text)

3.  Implement CRUD operations in the CategoryController.

4.  Use Route::apiResource to define routes.

5.  Test the APIs using Postman.

Solution for Assignment 1:

1.  Create the Model and Migration:

bash

Copy code

php artisan make:model Category -m

2.  Define the Schema in Migration:
Open the migration file in database/migrations and update the up() method:

php

Copy code

public function up()

{

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

        $table->id();

        $table->string('name');

        $table->text('description')->nullable();

        $table->timestamps();

    });

}

3.  Run Migrations:

bash

Copy code

php artisan migrate

4.  Generate the Controller:

bash

Copy code

php artisan make:controller CategoryController --api

5.  Define Routes:
Add the following in routes/api.php:

php

Copy code

Route::apiResource('categories', CategoryController::class);

6.  Implement CRUD Operations in CategoryController:

o    Index Method:

php

Copy code

public function index()

{

    return Category::all();

}

o    Store Method:

php

Copy code

public function store(Request $request)

{

    $validated = $request->validate([

        'name' => 'required',

        'description' => 'nullable',

    ]);

 

    return Category::create($validated);

}

o    Show Method:

php

Copy code

public function show($id)

{

    return Category::findOrFail($id);

}

o    Update Method:

php

Copy code

public function update(Request $request, $id)

{

    $category = Category::findOrFail($id);

    $validated = $request->validate([

        'name' => 'required',

        'description' => 'nullable',

    ]);

 

    $category->update($validated);

    return $category;

}

o    Destroy Method:

php

Copy code

public function destroy($id)

{

    $category = Category::findOrFail($id);

    $category->delete();

 

    return response()->json(['message' => 'Category deleted successfully']);

}

7.  Test the API in Postman:
Use the following endpoints:

o    GET /categories: Fetch all categories.

o    POST /categories: Create a new category (send JSON body).

o    GET /categories/{id}: Fetch a specific category.

o    PUT /categories/{id}: Update a specific category (send JSON body).

o    DELETE /categories/{id}: Delete a category.


Assignment 2: Add Validation Rules to the Product API

1.  Modify the ProductController to ensure:

o    name must be required and unique.

o    description must have a minimum length of 10 characters.

o    price must be numeric and greater than 0.

2.  Test the validation rules using Postman.

Solution for Assignment 2:

Update the store and update methods in ProductController:

  • Store Method:

php

Copy code

public function store(Request $request)

{

    $validated = $request->validate([

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

        'description' => 'required|min:10',

        'price' => 'required|numeric|min:0.01',

    ]);

 

    return Product::create($validated);

}

  • Update Method:

php

Copy code

public function update(Request $request, $id)

{

    $product = Product::findOrFail($id);

    $validated = $request->validate([

        'name' => 'required|unique:products,name,' . $id . '|max:255',

        'description' => 'required|min:10',

        'price' => 'required|numeric|min:0.01',

    ]);

 

    $product->update($validated);

    return $product;

}

Test validation in Postman:

  • Try submitting invalid data (e.g., empty name, short description, or non-numeric price).
  • Verify that Laravel returns proper validation error messages.

Assignment 3: Implement Pagination for the Product API

1.  Modify the index method of the ProductController to support pagination (10 items per page).

2.  Test the paginated results using Postman.

Solution for Assignment 3:

Update the index method:

php

Copy code

public function index()

{

    return Product::paginate(10);

}

Test in Postman:

  • Use the endpoint GET /products.
  • Observe the paginated response with links and meta fields.
  • Add query parameters like ?page=2 to navigate between pages.

Assignment 4: Add Search Functionality to the Product API

1.  Modify the index method to allow searching for products by name.

2.  Test the search feature using query parameters (e.g., GET /products?search=laptop).

Solution for Assignment 4:

Update the index method:

php

Copy code

public function index(Request $request)

{

    $query = Product::query();

 

    if ($request->has('search')) {

        $query->where('name', 'like', '%' . $request->search . '%');

    }

 

    return $query->paginate(10);

}

Test in Postman:

  • Use the endpoint GET /products?search=laptop.
  • Verify that only products matching the search term are returned.

These assignments cover real-world scenarios, enhancing students' understanding of Laravel API development.

4o

You said:

more

ChatGPT said:

ChatGPT

Here are a few more assignments based on Laravel API Development that will help deepen students' understanding of key concepts:


Assignment 5: Create User API with Authentication

Objective: Build a RESTful API for managing users with authentication.

1.  Create a User model with fields:

o    name,

o    email,

o    password.

2.  Implement authentication using Laravel’s built-in Auth system.

3.  Implement CRUD operations for managing users.

4.  Use middleware to protect routes that require authentication.

5.  Test the User API with authentication in Postman.

Solution for Assignment 5:

1.  Create the User Model and Migration:

bash

Copy code

php artisan make:model User -m

2.  Define Schema in Migration:
In the migration file:

php

Copy code

public function up()

{

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

        $table->id();

        $table->string('name');

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

        $table->string('password');

        $table->timestamps();

    });

}

Run the migration:

bash

Copy code

php artisan migrate

3.  Controller for User CRUD Operations:

bash

Copy code

php artisan make:controller UserController --api

Implement methods for CRUD:

o    Index Method:

php

Copy code

public function index()

{

    return User::all();

}

o    Store Method:

php

Copy code

public function store(Request $request)

{

    $validated = $request->validate([

        'name' => 'required',

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

        'password' => 'required|min:8',

    ]);

 

    $validated['password'] = bcrypt($validated['password']);

    return User::create($validated);

}

o    Show Method:

php

Copy code

public function show($id)

{

    return User::findOrFail($id);

}

o    Update Method:

php

Copy code

public function update(Request $request, $id)

{

    $user = User::findOrFail($id);

    $validated = $request->validate([

        'name' => 'required',

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

        'password' => 'nullable|min:8',

    ]);

   

    if ($request->filled('password')) {

        $validated['password'] = bcrypt($validated['password']);

    }

 

    $user->update($validated);

    return $user;

}

o    Destroy Method:

php

Copy code

public function destroy($id)

{

    User::destroy($id);

    return response()->json(['message' => 'User deleted successfully']);

}

4.  Authentication Setup:

o    Use Laravel's Sanctum or Passport for API authentication.

o    Install Sanctum:

bash

Copy code

composer require laravel/sanctum

php artisan migrate

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

o    Add Sanctum middleware to api middleware group in app/Http/Kernel.php:

php

Copy code

'api' => [

    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

    'throttle:api',

    \Illuminate\Routing\Middleware\SubstituteBindings::class,

],

o    Protect Routes with Authentication:
In routes/api.php:

php

Copy code

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {

    return $request->user();

});

 

Route::apiResource('users', UserController::class)->middleware('auth:sanctum');

5.  Test Authentication and CRUD Operations:

o    POST /login: Authenticate user (obtain a token).

o    GET /users: Use Bearer token to access authenticated routes.


Assignment 6: Add Image Upload Functionality to Product API

Objective: Implement image upload functionality in the Product API for storing product images.

1.  Create a Product model if not created already.

2.  Implement image upload functionality during the create and update of products.

3.  Ensure only valid image types (JPEG, PNG) are allowed.

4.  Store the images in the public/products directory.

5.  Return the image URL in the API response.

Solution for Assignment 6:

1.  Update the ProductController Store and Update Methods:

o    Store Method with Image Upload:

php

Copy code

public function store(Request $request)

{

    $validated = $request->validate([

        'name' => 'required',

        'price' => 'required|numeric',

        'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',

    ]);

 

    if ($request->hasFile('image')) {

        $imageName = time() . '.' . $request->image->extension();

        $request->image->move(public_path('products'), $imageName);

        $validated['image'] = 'products/' . $imageName;

    }

 

    return Product::create($validated);

}

o    Update Method with Image Upload:

php

Copy code

public function update(Request $request, $id)

{

    $product = Product::findOrFail($id);

 

    $validated = $request->validate([

        'name' => 'required',

        'price' => 'required|numeric',

        'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',

    ]);

 

    if ($request->hasFile('image')) {

        $imageName = time() . '.' . $request->image->extension();

        $request->image->move(public_path('products'), $imageName);

        $validated['image'] = 'products/' . $imageName;

    }

 

    $product->update($validated);

    return $product;

}

2.  Testing:

o    Use Postman to test the image upload by sending a multipart/form-data request with an image file.


Assignment 7: Implement Soft Deletes in the Product API

Objective: Add the functionality to "soft delete" products so that they can be recovered if necessary.

1.  Add deleted_at timestamp column in the products table.

2.  Use Laravel’s built-in soft delete functionality.

3.  Implement restore method to undo soft deletes.

4.  Test soft delete functionality using Postman.

Solution for Assignment 7:

1.  Add Soft Deletes to the Product Model:
In the Product model, use the SoftDeletes trait:

php

Copy code

use Illuminate\Database\Eloquent\SoftDeletes;

 

class Product extends Model

{

    use SoftDeletes;

 

    protected $dates = ['deleted_at'];

}

2.  Update Migration for Soft Deletes:
Run a migration to add the deleted_at column:

bash

Copy code

php artisan make:migration add_deleted_at_to_products_table --table=products

In the migration file:

php

Copy code

public function up()

{

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

        $table->softDeletes();

    });

}

3.  Implement Soft Delete in ProductController:

o    Destroy Method for Soft Delete:

php

Copy code

public function destroy($id)

{

    $product = Product::findOrFail($id);

    $product->delete();

 

    return response()->json(['message' => 'Product soft deleted successfully']);

}

o    Restore Method for Soft Delete:

php

Copy code

public function restore($id)

{

    $product = Product::withTrashed()->findOrFail($id);

    $product->restore();

 

    return response()->json(['message' => 'Product restored successfully']);

}

4.  Testing:

o    Soft Delete: Use the DELETE /products/{id} API to soft delete a product.

o    Restore: Use the POST /products/{id}/restore API to restore a soft-deleted product.


Assignment 8: Rate Products via API

Objective: Implement product rating functionality.

1.  Create a Rating model with fields:

o    product_id,

o    user_id,

o    rating (integer, 1 to 5).

2.  Create an API to rate products (one user can rate a product only once).

3.  Allow users to update their rating.

4.  Test the rating functionality via Postman.

Solution for Assignment 8:

1.  Create the Rating Model and Migration:

bash

Copy code

php artisan make:model Rating -m

In the migration file:

php

Copy code

public function up()

{

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

        $table->id();

        $table->foreignId('product_id')->constrained();

        $table->foreignId('user_id')->constrained();

        $table->integer('rating');

        $table->timestamps();

    });

}

2.  Controller for Rating:
Implement store and update methods to manage product ratings.

o    Store Method: Add or update a user's rating for a product.

o    Update Method: Update the rating for a product by the user.

3.  Testing:

o    Use Postman to test the product rating API.


These assignments will allow students to understand core Laravel API features such as CRUD operations, authentication, file uploads, and soft deletes, providing a strong foundation for more complex applications.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are additional assignments based on Laravel API Development to further help students master the concept:


Assignment 9: Create Category API with CRUD Operations

Objective: Build a RESTful API for managing product categories.

1.  Create a Category model with fields:

o    name,

o    description.

2.  Implement CRUD operations for categories.

3.  Add validation to ensure category name is unique.

4.  Use the CategoryController to handle API requests.

5.  Test the Category API with Postman.

Solution for Assignment 9:

1.  Create the Category Model and Migration:

bash

Copy code

php artisan make:model Category -m

In the migration file:

php

Copy code

public function up()

{

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

        $table->id();

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

        $table->text('description');

        $table->timestamps();

    });

}

2.  Category Controller:
Generate the controller:

bash

Copy code

php artisan make:controller CategoryController --api

Implement the CRUD methods:

o    Store Method:

php

Copy code

public function store(Request $request)

{

    $validated = $request->validate([

        'name' => 'required|unique:categories',

        'description' => 'required',

    ]);

 

    return Category::create($validated);

}

o    Index Method:

php

Copy code

public function index()

{

    return Category::all();

}

o    Show Method:

php

Copy code

public function show($id)

{

    return Category::findOrFail($id);

}

o    Update Method:

php

Copy code

public function update(Request $request, $id)

{

    $category = Category::findOrFail($id);

 

    $validated = $request->validate([

        'name' => 'required|unique:categories,name,' . $category->id,

        'description' => 'required',

    ]);

 

    $category->update($validated);

 

    return $category;

}

o    Destroy Method:

php

Copy code

public function destroy($id)

{

    Category::destroy($id);

    return response()->json(['message' => 'Category deleted successfully']);

}

3.  Testing:
Use Postman to test:

o    Create a new category (POST /categories).

o    Get all categories (GET /categories).

o    Get a category by ID (GET /categories/{id}).

o    Update a category (PUT /categories/{id}).

o    Delete a category (DELETE /categories/{id}).


Assignment 10: Implement Pagination in the Product API

Objective: Implement pagination to limit the number of products returned in each API request.

1.  Modify the index method in the ProductController to return paginated results.

2.  Set the default number of products per page to 10.

3.  Test pagination by sending requests with page and per_page parameters in Postman.

Solution for Assignment 10:

1.  Update the ProductController Index Method:
Modify the index method to return paginated results:

php

Copy code

public function index(Request $request)

{

    $perPage = $request->input('per_page', 10); // Default to 10 products per page

    return Product::paginate($perPage);

}

2.  Testing Pagination:

o    Send a request to GET /products?page=1&per_page=5 to retrieve the first 5 products.

o    Send a request to GET /products?page=2&per_page=5 to retrieve the next 5 products.


Assignment 11: Create API with Search Functionality for Products

Objective: Implement a search functionality in the Product API to allow users to filter products based on their name.

1.  Create a search feature in the ProductController that filters products based on a name query parameter.

2.  Return products that match the search query (case-insensitive).

3.  Test the search functionality in Postman.

Solution for Assignment 11:

1.  Update the ProductController to Add Search:
In the index method of the ProductController:

php

Copy code

public function index(Request $request)

{

    $query = $request->input('name'); // Get the search query

    if ($query) {

        return Product::where('name', 'like', '%' . $query . '%')->get();

    }

    return Product::all(); // Return all products if no query

}

2.  Testing the Search:

o    Send a GET request to GET /products?name=iphone to search for products containing "iphone" in their name.

o    Test with different search terms in Postman.


Assignment 12: Add Review API for Products

Objective: Implement a system to add and retrieve reviews for products.

1.  Create a Review model with fields:

o    product_id,

o    user_id,

o    review_text,

o    rating (integer, 1 to 5).

2.  Add functionality to add reviews to products.

3.  Allow users to fetch all reviews for a specific product.

4.  Test the review functionality in Postman.

Solution for Assignment 12:

1.  Create the Review Model and Migration:

bash

Copy code

php artisan make:model Review -m

In the migration file:

php

Copy code

public function up()

{

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

        $table->id();

        $table->foreignId('product_id')->constrained();

        $table->foreignId('user_id')->constrained();

        $table->text('review_text');

        $table->integer('rating');

        $table->timestamps();

    });

}

2.  Create the ReviewController:
Generate the controller:

bash

Copy code

php artisan make:controller ReviewController --api

Implement the store and index methods:

o    Store Method (to create reviews):

php

Copy code

public function store(Request $request, $productId)

{

    $validated = $request->validate([

        'review_text' => 'required|string',

        'rating' => 'required|integer|between:1,5',

    ]);

 

    $review = new Review();

    $review->product_id = $productId;

    $review->user_id = auth()->user()->id; // assuming authentication is set up

    $review->review_text = $validated['review_text'];

    $review->rating = $validated['rating'];

    $review->save();

 

    return response()->json($review, 201);

}

o    Index Method (to get reviews for a product):

php

Copy code

public function index($productId)

{

    return Review::where('product_id', $productId)->get();

}

3.  Testing Reviews API:

o    Use Postman to test:

§  POST /products/{productId}/reviews to add a review for a product.

§  GET /products/{productId}/reviews to retrieve all reviews for a specific product.


Assignment 13: Rate Product Reviews

Objective: Allow users to rate the reviews of products.

1.  Create a new table review_ratings with fields:

o    review_id,

o    user_id,

o    rating (integer 1 to 5).

2.  Implement an API to allow users to rate reviews (one rating per user per review).

3.  Prevent users from rating the same review multiple times.

4.  Test the rating system in Postman.

Solution for Assignment 13:

1.  Create the ReviewRating Model and Migration:

bash

Copy code

php artisan make:model ReviewRating -m

In the migration file:

php

Copy code

public function up()

{

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

        $table->id();

        $table->foreignId('review_id')->constrained();

        $table->foreignId('user_id')->constrained();

        $table->integer('rating');

        $table->timestamps();

    });

}

2.  Create the RatingController:
Generate the controller:

bash

Copy code

php artisan make:controller RatingController

Implement methods:

o    Store Method (to rate reviews):

php

Copy code

public function store(Request $request, $reviewId)

{

    $validated = $request->validate([

        'rating' => 'required|integer|between:1,5',

    ]);

 

    $userRating = ReviewRating::where('review_id', $reviewId)

        ->where('user_id', auth()->user()->id)

        ->first();

 

    if ($userRating) {

        return response()->json(['message' => 'You have already rated this review'], 400);

    }

 

    $rating = new ReviewRating();

    $rating->review_id = $reviewId;

    $rating->user_id = auth()->user()->id;

    $rating->rating = $validated['rating'];

    $rating->save();

 

    return response()->json($rating, 201);

}

3.  Testing the Rating API:

o    Use Postman to test the rating system:

§  POST /reviews/{reviewId}/rating to rate a review.

§  Ensure users can't rate the same review multiple times.


These additional assignments build upon CRUD functionality and introduce more advanced concepts like pagination, search, file handling, and relationships between models. They will help students deepen their understanding of building real-world RESTful APIs in Laravel.


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