Laravel route

How laravel route work

when the user navigates to the website he sends a request to a specific page like homepage then the response will load the home screen this how the route works.

in laravel the default route files are located in the routes directory wich all routes located. the default file is web.php where you register all project routes

Write routes in laravel

Route::get('home', function () {
    return view('home');
});

in this example when the user navigates to /home then the response will load the view called a (home).

The view is an HTML page located in the resources directory, there a lot of ways to make a response to the request:

  • View function - example return view();
  • string - the laravel will automatically make a response example return 'A string .. ';
  • JSON - return ['userID'=>5] - the laravel will automatically make a JSON response, it's useful when building an API

How to Pass Data to Views

in laravel, you can fetch the URL var using query data or wildcard 

Fetch the URL query

example request http://www.localhost.com?id=1

and this how you can get the id parameter

Route::get('/', function () {
    return request('id');
});

 

now to send the var to the view, you need to add the var as the second argument to the view

app/routes/web.php

Route::get('/', function () {
    $id= request('id');
    return view('home',['id'=>$id])
});

now in your home view, you can use the $id var 

resources/view/home.blade.php

your id is:{{id}}

wildcard value

the wildcard is available in a closer function

example request http://www.localhost.com/id/1

app/routes/web.php

Route::get('/id/{id}', function ($id) {
    return view('home',['id'=>$id])
});

now in your home view, you can use the $id var 

resources/view/home.blade.php

your id is:{{id}}