To call a controller method from a route in a Laravel application, you need to define the route in the routes/web.php file and specify the controller method that should be invoked when the route is accessed. Here's how you can do it:
1. Create a Controller: First, make sure you have a controller created. You can create one using the following Artisan command:
php artisan make:controller YourControllerName
2. Specify the Controller Method: Use the -> operator to specify the controller and the method that should handle the route. The controller method should be in the format [ControllerClassName::class ,'methodName'].
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ExampleController extends Controller
{
public function index()
{
return 'Hello from ExampleController index function';
}
}
3. Define a Route: Open the routes/web.php file and define your route using the Route facade. You can specify the HTTP method (e.g., GET, POST, PUT, DELETE) and the URL path for your route.
// routes/web.php
use App\Http\Controllers\ExampleController; // ExampleController replace with your controller name
Route::get('/your-route', [ExampleController::class, 'index']); // index replace with your function name
4. Access the Route: Now serve your application , after that you navigate to http://127.0.0.1:8000/your-route in your browser,
php artisan serve