Laravel: How to Create route with controller?

To create a route with a controller in Laravel, follow these steps:

  1. Generate a Controller (if not already created):

    If you haven't already created the controller you want to associate with a route, you can generate one using the Artisan command-line tool. Replace YourControllerName with your desired controller name:

    bash
  • php artisan make:controller YourControllerName

    This will create a new controller file in the app/Http/Controllers directory.

  • Define a Route in routes/web.php:

    Open the routes/web.php file and define a route that points to a controller method. You can use the get, post, put, delete, or other route methods depending on your use case. Here's an example using the get method:

    php
  • use App\Http\Controllers\YourControllerName; Route::get('/your-route', [YourControllerName::class, 'yourControllerMethod']);
    • YourControllerName: Replace this with the actual name of your controller.
    • 'your-route': Replace this with the URL path you want to associate with your route.
    • 'yourControllerMethod': Replace this with the method name within your controller that you want to be executed when the route is accessed.
  • Create the Controller Method:

    In your controller (e.g., YourControllerName.php), create the method that corresponds to the route. For example:

    php
    1. // app/Http/Controllers/YourControllerName.php namespace App\Http\Controllers; use Illuminate\Http\Request; class YourControllerName extends Controller { public function yourControllerMethod() { // Your controller logic here return view('your-view-name'); } }

      Replace 'your-view-name' with the actual name of the Blade view you want to render or any other logic you want to execute in the controller method.

    2. Access the Route:

      With the route defined and the controller method created, you can now access the route by visiting its URL in your web browser. For example, if you defined the route as /your-route, you can access it at http://yourdomain.com/your-route.

    That's it! You have successfully created a route with a controller in Laravel. When you access the specified URL, Laravel will execute the associated controller method and return the result, which could be a view, JSON response, or any other response based on your controller logic.

    Comments