Laravel 11 Call API Project Example with Template
Prerequisites:* Git: Git is a version control system used for tracking changes in source code during software development. Make sure Git is installed on your system. You can download Git from https://git-scm.com/ and follow the installation instructions for your operating system.
* PHP: Laravel requires PHP to be installed on your system. You need PHP version 7.3 or higher. You can check your PHP version by running php -v in your terminal.
* Composer: Composer is a dependency manager for PHP and is used to install Laravel and its dependencies. You can download Composer from https://getcomposer.org/ and follow the installation instructions for your operating system.
* Web Server: You'll need a web server to serve your Laravel application. While Laravel comes with a built-in development server, it's recommended that Apache or Nginx be used for production deployments.
* Database: If the cloned project uses a database, make sure you have the required database management system (e.g., MySQL, PostgreSQL, SQLite) installed on your system.
* Postman: is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs faster. Can download https://postman.com/
* Git: Git is a version control system used for tracking changes in source code during software development. Make sure Git is installed on your system. You can download Git from https://git-scm.com/ and follow the installation instructions for your operating system.
* PHP: Laravel requires PHP to be installed on your system. You need PHP version 7.3 or higher. You can check your PHP version by running php -v in your terminal.
* Composer: Composer is a dependency manager for PHP and is used to install Laravel and its dependencies. You can download Composer from https://getcomposer.org/ and follow the installation instructions for your operating system.
* Web Server: You'll need a web server to serve your Laravel application. While Laravel comes with a built-in development server, it's recommended that Apache or Nginx be used for production deployments.
* Database: If the cloned project uses a database, make sure you have the required database management system (e.g., MySQL, PostgreSQL, SQLite) installed on your system.
* Postman: is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs faster. Can download https://postman.com/
Web Routes
Next, define the routes for your Web endpoints. Open your web.php
file located at routes/web.php
and define your routes:
<?php
use Illuminate\Support\Facades\Route;
/** for side bar menu active */
function set_active($route) {
if (is_array($route )){
return in_array(Request::path(), $route) ? 'active' : '';
}
return Request::path() == $route ? 'active' : '';
}
Route::get('/', function () {
return view('authentication.login');
});
Route::group(['namespace' => 'App\Http\Controllers'],function()
{
Route::controller(AuthenticationController::class)->group(function () {
// ---------------------login----------------------//
Route::get('login', 'login')->name('login');
Route::post('login/account', 'loginAccount')->name('login/account');
// ---------------------register--------------------//
Route::get('register', 'register')->name('register');
Route::post('register/account', 'registerAccount')->name('register/account');
// ---------------------logout----------------------//
Route::get('logout', 'logoutAccount')->name('logout');
});
});
Route::group(['namespace' => 'App\Http\Controllers'],function()
{
// -------------------------- main dashboard ----------------------//
Route::controller(HomeController::class)->group(function () {
Route::get('/home', 'index')->name('home');
});
});
<?php
use Illuminate\Support\Facades\Route;
/** for side bar menu active */
function set_active($route) {
if (is_array($route )){
return in_array(Request::path(), $route) ? 'active' : '';
}
return Request::path() == $route ? 'active' : '';
}
Route::get('/', function () {
return view('authentication.login');
});
Route::group(['namespace' => 'App\Http\Controllers'],function()
{
Route::controller(AuthenticationController::class)->group(function () {
// ---------------------login----------------------//
Route::get('login', 'login')->name('login');
Route::post('login/account', 'loginAccount')->name('login/account');
// ---------------------register--------------------//
Route::get('register', 'register')->name('register');
Route::post('register/account', 'registerAccount')->name('register/account');
// ---------------------logout----------------------//
Route::get('logout', 'logoutAccount')->name('logout');
});
});
Route::group(['namespace' => 'App\Http\Controllers'],function()
{
// -------------------------- main dashboard ----------------------//
Route::controller(HomeController::class)->group(function () {
Route::get('/home', 'index')->name('home');
});
});
Controller [AuthenticationController]
Now implement authentication methods into it to handle login, registration, and user detail functionality from the database:
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
class AuthenticationController extends Controller
{
/** register page */
public function register()
{
return view('authentication.register');
}
/** register account post */
public function registerAccount(Request $request)
{
$request->validate([
'name' => 'required|min:4',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|min:8',
'privacy_policy' => 'required',
]);
try {
$dt = Carbon::now();
$join_date = $dt->toDayDateTimeString();
$url = env('APP_URL') . '/api/register';
// Make a POST request to the register API endpoint
$response = Http::withOptions(['verify' => false])->withHeaders([
'X-Requested-With' => 'XMLHttpRequest',
'Content-Type' => 'application/json',
])->post($url, [
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
]);
$responseData = json_decode($response->getBody(), true);
if (isset($responseData['errors'])) {
// Handle the error
if (isset($responseData['errors']['email'])) {
// Email already taken
Toastr::error('The email has already been taken. Please use a different email.', 'Error');
} else {
Toastr::error('Registration failed. Please try again.', 'Error');
}
return redirect()->back();
} else {
Toastr::success('Registration Successful :)', 'Success');
return redirect()->intended('login');
}
} catch (Exception $e) {
// Handle the exception
\Log::error('Registration error: ' . $e->getMessage());
Toastr::error('An error occurred during registration. Please try again later.');
return redirect()->back();
}
}
/** index login page */
public function login()
{
return view('authentication.login');
}
/** login account post */
public function loginAccount(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
try {
$url = env('APP_URL') . '/api/login';
// Make a POST request to the login API endpoint
$response = Http::withOptions(['verify' => false])->withHeaders([
'X-Requested-With' => 'XMLHttpRequest',
'Content-Type' => 'application/json',
])->post($url, [
'email' => $request->email,
'password' => $request->password,
]);
$responseData = json_decode($response->getBody(), true);
if ($responseData['response_code'] == 200) {
// Store the token in the session or a cookie
$request->session()->put('token', $responseData['token']);
Toastr::success('Login Successfully :)','Success');
return redirect()->intended('home');
} else {
// Handle the error
Toastr::error('fail, WRONG USERNAME OR PASSWORD :)','Error');
return redirect()->back();
}
} catch (Exception $e) {
// Handle the exception
\Log::error('Login error: ' . $e->getMessage());
Toastr::error('An error occurred while logging in.');
return redirect()->back();
}
}
/** logout */
public function logoutAccount(Request $request)
{
try {
// Fetch the token from the session or cookie
$token = $request->session()->get('token');
$url = env('APP_URL') . '/api/login/out';
// Make a POST request to the logout API endpoint
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $token,
'X-Requested-With' => 'XMLHttpRequest',
'Content-Type' => 'application/json',
])->post($url);
// Check the response status
if ($response->status() == 200) {
// If the logout was successful, clear the token from the session or cookie
$request->session()->forget('token');
$request->cookies->clear();
// Redirect the user to the login page or any other desired route
Toastr::success('Logout Successfully :)','Success');
return redirect()->route('login');
} else {
// If the logout was unsuccessful, display an error message
Toastr::error('There was a problem logging out. Please try again.');
return redirect()->back();
}
} catch (\Exception $e) {
// Log the exception and display a generic error message
Toastr::error('An unexpected error occurred. Please try again later.');
\Log::error('Logout error: ' . $e->getMessage());
return redirect()->back();
}
}
}
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
class AuthenticationController extends Controller
{
/** register page */
public function register()
{
return view('authentication.register');
}
/** register account post */
public function registerAccount(Request $request)
{
$request->validate([
'name' => 'required|min:4',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|min:8',
'privacy_policy' => 'required',
]);
try {
$dt = Carbon::now();
$join_date = $dt->toDayDateTimeString();
$url = env('APP_URL') . '/api/register';
// Make a POST request to the register API endpoint
$response = Http::withOptions(['verify' => false])->withHeaders([
'X-Requested-With' => 'XMLHttpRequest',
'Content-Type' => 'application/json',
])->post($url, [
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
]);
$responseData = json_decode($response->getBody(), true);
if (isset($responseData['errors'])) {
// Handle the error
if (isset($responseData['errors']['email'])) {
// Email already taken
Toastr::error('The email has already been taken. Please use a different email.', 'Error');
} else {
Toastr::error('Registration failed. Please try again.', 'Error');
}
return redirect()->back();
} else {
Toastr::success('Registration Successful :)', 'Success');
return redirect()->intended('login');
}
} catch (Exception $e) {
// Handle the exception
\Log::error('Registration error: ' . $e->getMessage());
Toastr::error('An error occurred during registration. Please try again later.');
return redirect()->back();
}
}
/** index login page */
public function login()
{
return view('authentication.login');
}
/** login account post */
public function loginAccount(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
try {
$url = env('APP_URL') . '/api/login';
// Make a POST request to the login API endpoint
$response = Http::withOptions(['verify' => false])->withHeaders([
'X-Requested-With' => 'XMLHttpRequest',
'Content-Type' => 'application/json',
])->post($url, [
'email' => $request->email,
'password' => $request->password,
]);
$responseData = json_decode($response->getBody(), true);
if ($responseData['response_code'] == 200) {
// Store the token in the session or a cookie
$request->session()->put('token', $responseData['token']);
Toastr::success('Login Successfully :)','Success');
return redirect()->intended('home');
} else {
// Handle the error
Toastr::error('fail, WRONG USERNAME OR PASSWORD :)','Error');
return redirect()->back();
}
} catch (Exception $e) {
// Handle the exception
\Log::error('Login error: ' . $e->getMessage());
Toastr::error('An error occurred while logging in.');
return redirect()->back();
}
}
/** logout */
public function logoutAccount(Request $request)
{
try {
// Fetch the token from the session or cookie
$token = $request->session()->get('token');
$url = env('APP_URL') . '/api/login/out';
// Make a POST request to the logout API endpoint
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $token,
'X-Requested-With' => 'XMLHttpRequest',
'Content-Type' => 'application/json',
])->post($url);
// Check the response status
if ($response->status() == 200) {
// If the logout was successful, clear the token from the session or cookie
$request->session()->forget('token');
$request->cookies->clear();
// Redirect the user to the login page or any other desired route
Toastr::success('Logout Successfully :)','Success');
return redirect()->route('login');
} else {
// If the logout was unsuccessful, display an error message
Toastr::error('There was a problem logging out. Please try again.');
return redirect()->back();
}
} catch (\Exception $e) {
// Log the exception and display a generic error message
Toastr::error('An unexpected error occurred. Please try again later.');
\Log::error('Logout error: ' . $e->getMessage());
return redirect()->back();
}
}
}
Steps to Clone and Set Up the Project:
Steps to Clone and Set Up the Project:
Open a terminal or command prompt and navigate to the directory where you want to clone your Laravel project. Then, run the following command:
Open a terminal or command prompt and navigate to the directory where you want to clone your Laravel project. Then, run the following command:
https://gitlab.com/SoengSouy/laravel-11-front-end-dashboard-premium.git
https://gitlab.com/SoengSouy/laravel-11-front-end-dashboard-premium.git
Replace <repository-url>
with the URL of your Laravel project's Git repository. You can find this URL on your Git hosting service (GitHub, GitLab, Bitbucket, etc.).
<repository-url>
with the URL of your Laravel project's Git repository. You can find this URL on your Git hosting service (GitHub, GitLab, Bitbucket, etc.).Navigate to the Project Directory:
Change into the project directory using the following command:
cd <project-directory>
cd <project-directory>
Replace <project-directory>
with the name of your project directory.
Install Composer Dependencies:
Laravel uses Composer to manage its dependencies. Run the following command to install the necessary dependencies:
Laravel uses Composer to manage its dependencies. Run the following command to install the necessary dependencies:
composer install
composer install
Create a Copy of the Environment File:
Laravel requires an .env
file for configuration. Create a copy of the .env.example
file and name it .env
:
Laravel requires an .env
file for configuration. Create a copy of the .env.example
file and name it .env
:
cp .env.example .env
cp .env.example .env
Edit the .env
file to set up your database connection and other configuration settings.
Edit the .env
file to set up your database connection and other configuration settings.
Generate Application Key:
Run the following command to generate the application key:
php artisan key:generate
php artisan key:generate
Update Your Database Credentials
After that update your database credentials in your .env file in your project root.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_db
DB_USERNAME=root
DB_PASSWORD=#your database password
Migrate Database:
Run the database migrations to create the necessary tables in your database:
php artisan migrate
php artisan migrate
Personal:
To create a personal access client in Laravel, you can use the following Artisan command:
php artisan passport:client --personal
php artisan passport:client --personal
Serve the Application:
Finally, you can use the following command to start the Laravel development server:
php artisan serve
php artisan serve
This will make your application accessible at http://localhost:8000
by default.
This will make your application accessible at http://localhost:8000
by default.
0 Comments
CAN FEEDBACK
Emoji