Friday, August 9, 2024

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide

If you're looking to host a Laravel project on Hostinger’s hPanel, you’re in the right place! This guide will walk you through each step, from uploading your project to configuring it for a smooth deployment.

1. Prepare Your Laravel Project

Before uploading, ensure that your Laravel project is ready to go:

  • Run composer install to install all dependencies.

  • If you're using front-end assets (like Vue.js or React), make sure to run npm run production.

  • Configure your .env file with the correct environment variables, such as database credentials and the application URL.

2. Upload Your Laravel Files

You have two options when uploading your files:

  • Option 1: Upload the Entire Project
    Upload your entire Laravel project to the root directory (one level above public_html). Then, move the contents of the public folder to the public_html folder.

  • Option 2: Upload Only the Necessary Files
    Create a directory called society in the root directory. Upload everything except the public folder into this directory. Then, move the contents of the public folder into the public_html directory.

3. Update the index.php File

After uploading your files, you need to update the paths in your index.php file, which is now located in the public_html directory.

Here’s how your updated index.php file ould look:

php


<?php


use Illuminate\Http\Request;


define('LARAVEL_START', microtime(true));


// Determine if the application is in maintenance mode...

if (file_exists($maintenance = __DIR__.'/../society/storage/framework/maintenance.php')) {

    require $maintenance;

}


// Register the Composer autoloader...

require __DIR__.'/../society/vendor/autoload.php';


// Bootstrap Laravel and handle the request...

(require_once __DIR__.'/../society/bootstrap/app.php')

    ->handleRequest(Request::capture());


  • Update the Paths: Ensure the paths point to the correct directories inside your society folder.

4. Set File Permissions

It’s essential that your Laravel project has the correct permissions:

Run the following command to ensure that the storage and bootstrap/cache directories are writable:


chmod -R 775 storage bootstrap/cache


5. Configure Your Environment Variables

Double-check the .env file in your society directory. Ensure all environment variables, such as APP_URL, DB_HOST, DB_DATABASE, DB_USERNAME, and DB_PASSWORD, are correctly set.

6. Database Setup

Using Hostinger’s hPanel, create a MySQL database:

Update the .env file with the new database credentials:
env

DB_HOST=your_database_host

DB_DATABASE=your_database_name

DB_USERNAME=your_database_username

DB_PASSWORD=your_database_password


7. Run Migrations

Access your site via S or use the web-based terminal in hPanel to run your migrations:



php artisan migrate --force


8. Configure Your Domain

Ensure your domain is pointing to the public_html directory. This ould be set up by default, but you can verify it in hPanel under “Domains” > “Manage.”

9. Set Up Cron Jobs (If Needed)

If your Laravel project requires scheduled tasks, set up cron jobs via hPanel.

10. Test Your Deployment

Finally, visit your domain to check if your Laravel project is running correctly. If you encounter any issues, review the logs in the storage/logs directory.



Wednesday, August 7, 2024

How to Create Custom Middleware in Laravel 11

 

Create Middleware

Now, we’ll create middleware using the following command.

php artisan make:middleware IsAdmin

app/Http/Middleware/IsAdmin.php

<?php


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;
class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check() && Auth::user()->role != 'superadmin') {
            //return response()->json('Oops! You do not have permission to access.');
            return response()->view('errors.error', [], 403);
        }

        return $next($request);
    }
}





Step 3: Register Middleware

In this step, we will register our custom middleware in the app.php file, as illustrated in the code snippet below:

bootstrap/app.php




<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Http\Middleware\SuperAdminMiddleware;
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {

        $middleware->alias([
            'isAdmin' => \App\Http\Middleware\IsAdmin::class,
        ]);
   
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();



routes/web.php

<?php

use Illuminate\Support\Facades\Route;

Route::middleware(['isAdmin'])->group(function () {
Route::get('/dashboard', function () {
return 'Dashboard';
});

Route::get('/users', function () {
return 'Users';
});
});

Wednesday, March 15, 2023

GitHub repository using Git Bash command

 To add a project to a GitHub repository using Git Bash command line, you can follow these steps:

  1. Create a new repository on GitHub by logging in and clicking on the "New repository" button on the main page.

  2. Once you have created a new repository, copy the HTTPS or SSH link to the repository.

  3. Open Git Bash and navigate to the folder where your project is located. You can do this using the "cd" command followed by the folder name, e.g. "cd my-project".

  4. Initialize a Git repository by running the command "git init".

  5. Add all the files in your project to the Git repository by running the command "git add ." (make sure to include the dot at the end).

  6. Commit your changes with a message by running the command "git commit -m 'Initial commit'".

  7. Set the remote repository URL using the command "git remote add origin [GitHub repository link]". Replace [GitHub repository link] with the HTTPS or SSH link you copied earlier.

  8. Push the code to the remote repository by running the command "git push -u origin master". This will upload all the files to the remote repository.

Once you have completed these steps, your project should now be available on GitHub.


error: remote origin already exists.


This error occurs when you try to set the remote origin URL for your Git repository, but the remote origin already exists. This can happen if you have already set the remote origin URL for your repository, or if you have cloned a repository from GitHub that already has a remote origin URL.

To resolve this error, you can either update the existing remote origin URL or remove it and add a new one. Here are the steps for each option:

Option 1: Update the existing remote origin URL

  1. Open Git Bash and navigate to the root directory of your local repository.
  2. Run the command git remote set-url origin [new-URL], where [new-URL] is the new remote origin URL that you want to set.
  3. Verify that the new remote origin URL has been set by running the command git remote -v.

Option 2: Remove the existing remote origin and add a new one

  1. Open Git Bash and navigate to the root directory of your local repository.
  2. Run the command git remote remove origin to remove the existing remote origin URL.
  3. Add a new remote origin URL by running the command git remote add origin [new-URL], where [new-URL] is the new remote origin URL that you want to set.
  4. Verify that the new remote origin URL has been set by running the command git remote -v.

After you have updated or added the remote origin URL, you should be able to push your changes to the remote repository without encountering the "remote origin already exists" error.

Tuesday, March 14, 2023

To add a new record to a database using Laravel, you can follow these steps:

 To add a new record to a database using Laravel, you can follow these steps:

  1. Create a new route in your routes/web.php file that points to a controller method:
css
Route::post('/add-record', 'RecordController@addRecord');
  1. Create a new controller by running the following command in your terminal:
go
php artisan make:controller RecordController
  1. In your RecordController, add a new method called addRecord that will handle the logic of adding a new record:
php
public function addRecord(Request $request) { $data = $request->validate([ 'field1' => 'required|unique:table_name', 'field2' => 'required', 'field3' => 'required' ]); // Insert the new record into the database DB::table('table_name')->insert($data); return redirect('/')->with('success', 'Record added successfully.'); }

In this method, we first validate the incoming request data to ensure that the field1 value is unique. If it's not unique, Laravel will throw a validation error. If the data is valid, we insert it into the database using the DB::table method. Finally, we redirect the user back to the homepage with a success message.

  1. In your view, you can add a JavaScript function that will check if the first field already exists and show a popup if it does. Here's an example using jQuery:
php
<script> $(document).ready(function() { $('#field1').change(function() { var field1_value = $(this).val(); $.ajax({ url: '/check-field1', type: 'POST', data: {field1: field1_value}, success: function(data) { if (data.exists) { alert('This value already exists!'); } } }); }); }); </script>

This JavaScript code listens for changes to the #field1 element and sends an AJAX request to a new endpoint called /check-field1. In your routes/web.php file, you can create a new route that points to a controller method that checks if the value already exists:

css
Route::post('/check-field1', 'RecordController@checkField1');

In your RecordController, add a new method called checkField1:

php
public function checkField1(Request $request) { $value = $request->input('field1'); $exists = DB::table('table_name')->where('field1', $value)->exists(); return response()->json(['exists' => $exists]); }

In this method, we check if the field1 value already exists in the database using the exists method. We return a JSON response that contains a boolean exists value.

Note: Replace table_name with the name of the table you are inserting the data into, and replace field1, field2, and field3 with the names of the fields in your table.

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide If you're looking to host a Laravel project on Hostinger’s hPa...