Skip to content
lera2od edited this page Apr 21, 2023 · 1 revision

How to Use Leravel Router

Leravel Router is a powerful tool that allows you to easily define routes for your web application. It is an essential component of the Leravel framework that helps you to manage the URLs of your web application.

Defining Routes

The basic syntax for defining a route in Leravel is:

    $Router->{METHOD}('{URI}', {CALLBACK});
  • {METHOD}: HTTP method (GET, POST, PUT, DELETE, etc.) to respond to.
  • {URI}: Uniform Resource Identifier (URI) of the route.
  • {CALLBACK}: Callback function that will be called when the route is matched.

Here is an example of how to define a simple route:

    $Router->get('/', function () {
        template("index.php");
    });

This will define a route that responds to the GET method with a URI of / and calls the template() function with the index.php file.

Defining Route Parameters

You can define parameters in the URI of a route by enclosing them in curly braces {}. For example:

    $Router->get('/dynamic/{id}/{xd}', function($args) {
        echo $args["id"] . " " . $args["xd"];
    });

This will define a route that responds to the GET method with a URI of /dynamic/{id}/{xd} and outputs the id and xd values from the $args array.

Serving Assets

You can serve static assets using the Leravel Router by defining a route that maps to a specific file, and then using the Asset class to serve the file:

    $Router->get("/media/{id}", function($args) {
        $media = new Asset($args["id"]);
        $media->serve();
    });

This will define a route that responds to the GET method with a URI of /media/{id} and serves the file with the specified ID using the Asset class.

Running the Router

Once you have defined your routes, you can run the Leravel Router using the run() method:

    $Router->run();

This will match the current URL to the defined routes and call the appropriate callback function.