CONTROLLER
The below will be a demonstration on how to create a Controller
which can be used by Vue.js to communicate with Laravel.
Firstly, open the backend folder in Visual Studio Code.

Making a Controller
Firstly, open a new terminal and run this command. HelloWorld
is the name of controller. It can be changed to any other name.
php artisan make:controller HelloWorld

You can find the HelloWorld.php
controller (which is the Controller
created previously), located at app/Http/

Inside HelloWorld.php
, make two simple functions that will return a sentence.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class HelloWorld extends Controller
{
public function helloWorld(){
return "Hi, helloWorld() function is called from the backend";
}
public function helloWorldAgain(){
return "Hi, helloWorldAgain() function is called from the backend";
}
}
Once you've created the controller with the necessary functions, you can proceed to set up routes in Laravel to make these functions accessible via HTTP requests.
Setting Up Routes
Open the web.php
OR api.php
file located in the "routes" directory, which is typically found at "routes/web.php" or "routes/api.php".
Inside them, you can define routes that map to the functions in your controller.
use App\Http\Controllers\HelloWorld;
// Define routes here
Route::post('/hello', [HelloWorld::class, 'helloWorld']);
Route::post('/hello-again', [HelloWorld::class, 'helloWorldAgain']);
Below is the screenshoot of web.php and api.php


So what is the different of web.php and api.php ???
Web.php
is primarily used for defining routes related to web pages and user interfaces. It typically includes routes for rendering views, handling form submissions, authentication, and other web-related tasks.
On the other hand, api.php
is used for defining routes specifically for API endpoints. These routes are typically used for serving JSON or XML responses to client applications such as mobile apps or single-page applications (SPAs).
In simple explaination, web.php
is used for traditional web applications, while api.php
is used for building APIs. They serve different purposes and often have different middleware and route configurations tailored to their respective use cases.
Testing Routes
Run the Laravel firstly,
php artisan serve
And to test these routes, you can either use a tool like Postman or simply navigate to these URLs in your web browser. For example:
Web.php
http://127.0.0.1:8000/hello
http://127.0.0.1:8000/api/hello-again
Api.php
http://127.0.0.1:8000/api/hello
http://127.0.0.1:8000/hello-again
and try to view these url and see what will happen.
Last updated