Create a Basic Calculator in Laravel

Here’s an example of how you could implement a calculator in Laravel:

1. First, create a new route in your routes/web.php file for the calculator:

Route::get('/calculator', 'CalculatorController@index');
Route::post('/calculator', 'CalculatorController@calculate');

2. Next, create a new controller using the command php artisan make:controller CalculatorController. This will create a new file app/Http/Controllers/CalculatorController.php.

3. Inside the CalculatorController.php, you can define two methods. index method to handle the get request, and calculate method to handle post request and perform the calculation.


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CalculatorController extends Controller
    public function index()
        return view('calculator');

    public function calculate(Request $request)
        $num1 = $request->input('num1');
        $num2 = $request->input('num2');
        $operator = $request->input('operator');

        switch ($operator) {
            case 'add':
                $result = $num1 + $num2;
            case 'subtract':
                $result = $num1 - $num2;
            case 'multiply':
                $result = $num1 * $num2;
            case 'divide':
                $result = $num1 / $num2;

        return view('calculator', ['result' => $result]);

4. Create a new view file resources/views/calculator.blade.php to display the calculator form and the result.

<form method="POST" action="/calculator">
    <input type="text" name="num1" placeholder="Number 1">
    <input type="text" name="num2" placeholder="Number 2">
    <select name="operator">
        <option value="add">Add</option>
        <option value="subtract">Subtract</option>
        <option value="multiply">Multiply</option>
        <option value="divide">Divide</option>
    <button type="submit">Calculate</button>

    <p>The result is: {{ $result }}</p>

5. Now if you start the local development server and hit the /calculator path in browser, it should display the calculator form. Once you submit the form, it will perform the calculation and display the result.

Please note that this is just an example, and if you plan on using it in a real-world scenario, you should add more error checking and validation to make sure that the input is valid and secure. You can use laravel’s built in validation for it.