Laravel for Beginners – Learn to Build Full-Stack Web Apps

Loading video...

Challenge

Problem

Generate a controller with 2 methods: sum and subtract. Define routes /sum and /subtract which will be associated to the controller corresponding methods.

Both methods will accept two arguments, both arguments should be numbers. When accessing /sum route it should print the sum of arguments and when accessing /subtract method it should print the difference.

Solution

Execute the following artisan command to create MathController

php artisan make:controller MathController

Then open generated MathController and add the following methods: sum and subtract

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MathController extends Controller
{
    public function sum(float $a, float $b)
    {
        return $a + $b;
    }

    public function subtract(float $a, float $b)
    {
        return $a - $b;
    }
}

Then open routes/web.php and define routes

Route::get('/sum/{a}/{b}', [MathController::class, 'sum'])
    ->whereNumber(['a', 'b']);
Route::get('/subtract/{a}/{b}', [MathController::class, 'subtract'])
    ->whereNumber(['a', 'b']);

Now open the browser and access http://localhost:8000/sum/5/8. You should see 13.

Then change sum into subtract in URL: http://localhost:8000/subtract/5/8. You should see -3.

Now try to access: http://localhost:8000/sum/5/abc. You should see 404 Not Found Page.

Discussion

Sign in to join the discussion.

No comments yet. Be the first to start the discussion!