DEV Community

Cover image for Laravel for Beginners : a Quick Guide - 8
Kartik Bhat
Kartik Bhat

Posted on

Laravel for Beginners : a Quick Guide - 8

Laravel Routes

I hope you understood the concept of adding data from user interface and receiving it response back to user interface,

Let's revisit concept of 'routes'...

what is 'route' ?

simply, route is a key word that connects user interface to the backend - Controller; :)

Ok in my previous articles you saw these kinds of routes ;

Route::get('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode

right ?

(revisit web.php file and verify it once)

this will connect to addData() function present under DataController Class, correct ?

Hope you observed that you are using Route Object to define new route ;

this Route object is actually defined under this class (you can notice this at the top section of the file align with use keyword)

Illuminate\Support\Facades\Route;
Enter fullscreen mode Exit fullscreen mode

then after that you observe key word get; it is nothing but HTTP method; yes exactly,

it will catch a type of request using a HTTP method that you used while calling that route,

HTTP method is a way request rises to the application's backend ;

What are different types of HTTP methods ?

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE
  • OPTIONS

for a time being lets concentrate on GET and POST methods only, and these are the methods we frequently use in our laravel applications.

Laravel support all these kinds of methods; like

Route::get('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode
Route::post('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode
Route::put('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode
Route::patch('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode
Route::delete('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode
Route::options('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode

along with above mentioned HTTP method routes laravel also provides another route type, it is any , it catches any kind of HTTP method

Route::any('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode

Mistyped routes/requests

laravel matches incoming requests HTTP method first, then it finds suitable route in web.php file, if it found then control moves to controller's method; else you can observe 404 page

let try this,
You know we have a route called,

Route::get('addData', [DataController::class,'addData']);
Enter fullscreen mode Exit fullscreen mode

hit this route from browser; (hope you are running laravel app)

http://127.0.0.1:8000/addData

you can observe this
Alt Text

right ?

now just alter keyword addData to addData--1 present in the url; Ok

now hit that url again;
(Do verify that we don't have any route defined called addData--1 in our web.php file)

http://127.0.0.1:8000/addData--1

since we don't have any such route; laravel manages to load 404 page;

Alt Text

So, no need to worry about mistyped routes/requests from browser, laravel manages it by itself, seems interesting right ? :)

Routes and Form submit

whenever the form submit happens, some that will be passed to the backend from our user interface(say frontend), right ?

Open addData.blade.php file located under resources->views folder

<html>
    <body>
        <div>
            <h3>Add Data</h3>
            <form method="GET" action="{{ url('saveFormData') }}">
                <label>Name</label>
                <input type="text" name="name" />
                <label>Age</label>
                <input type="number" name="age" />
                <button type="submit">Save</button>
            </form>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

you can observe method and action mentioned with form element

method - GET
action - route saveFormData

here form is submitting data to the route saveFormData via GET http method; you know it I suppose :)

Now open DataController class and go to the function returned by 'saveFormData' route; it is saveForm(), add dd() of $request after entering the function.

public function saveForm(Request $request) {
        dd($request);
        $data = [
            'name' => $request->name,
            'age' => $request->age
        ];
        $insertData = Data::create($data);

        if(isset($insertData['id'])) {
            $message = "Success";
        } else {
            $message = "Failed";
        }

        $response = [
            'message'=>$message
        ];

        return view('response',$response);
 }
Enter fullscreen mode Exit fullscreen mode

Ok, then hit the route 'addData' from your browser;

http://127.0.0.1:8000/addData

then fill the form and submit;
Alt Text

You can see this window right ?
Now,, just observe URL bar;

Alt Text

you can see those form input data; those are passing as a url parameters to the backend(Controller); right ?

now, lets change form method from GET to POST present in the file addData.blade.php

<form method="POST" action="{{ url('saveFormData') }}">
Enter fullscreen mode Exit fullscreen mode

Again, hit the addData route and fill the form ; then submit.

What you are seeing ?

this error right ?
Alt Text

Why ?

Observe web.php file; there is no route with a method post having keyword 'saveFormData' ; Observed ?

what you got ?
route catches an http method that request is coming from; through form you are sending data through POST method for 'saveFormData' route; it actually doesn't exist;

Route::get('saveFormData', [DataController::class,'saveForm']);
Enter fullscreen mode Exit fullscreen mode

it is a get route with a key word 'saveFormData' , it doesn't catches request with POST method; then how to catch it ?

Simple, create a similar route with post method; like

Route::post('saveFormData', [DataController::class,'saveForm']);
Enter fullscreen mode Exit fullscreen mode

that too returning same controller's same method; no issues.

now again hit the url : ####http://127.0.0.1:8000/addData####

and fill the form and submit again;

what you are seeing now ?

Alt Text

you are seeing dd() response of $request; right ?

Observe URL bar now; there is no url parameters exist but still Controller is receiving form data; right ?

Alt Text

This is what the main difference between GET and POST http methods :)

POST method doesn't shows form submitted data as an URL parameters where as GET method clearly shows;

There is a limitation of data length that can be passed through GET method, where POST method hasn't any such;

Even though both the method has there own features; primarily we can prefer form data should be submitted through POST method, a secure approach we believe;

While sending FORM data through POST we need add another constraint to the form i.e CSRF token (Cross-Site Request Forgery)
is a way our application identifies that request is coming / data is submitting from known/authenticated source, Laravel automatically generates this CSRF token and just we need to add it within our form element

within form element of the addData blade file we just need to mention

@csrf
Enter fullscreen mode Exit fullscreen mode
<html>
    <body>
        <div>
            <h3>Add Data</h3>
            <form method="POST" action="{{ url('saveFormData') }}">
                @csrf
                <label>Name</label>
                <input type="text" name="name" />
                <label>Age</label>
                <input type="number" name="age" />
                <button type="submit">Save</button>
            </form>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

it will be automatically verified by laravel while receiving the request at backend;

this is all about brief explanation on Laravel Routes; Hope you understood about it;

Bye ;)

Top comments (0)