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.

<?php

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;
                break;
            case 'subtract':
                $result = $num1 - $num2;
                break;
            case 'multiply':
                $result = $num1 * $num2;
                break;
            case 'divide':
                $result = $num1 / $num2;
                break;
        }

        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">
    @csrf
    <input type="text" name="num1" placeholder="Number 1">
    <br>
    <input type="text" name="num2" placeholder="Number 2">
    <br>
    <select name="operator">
        <option value="add">Add</option>
        <option value="subtract">Subtract</option>
        <option value="multiply">Multiply</option>
        <option value="divide">Divide</option>
    </select>
    <br>
    <button type="submit">Calculate</button>
</form>

@if(isset($result))
    <p>The result is: {{ $result }}</p>
@endif

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.