Skip to content

Instantly share code, notes, and snippets.

@iifast2
Last active August 14, 2024 09:47
Show Gist options
  • Save iifast2/2f5aa29de85106550a8d50d1d9dfe472 to your computer and use it in GitHub Desktop.
Save iifast2/2f5aa29de85106550a8d50d1d9dfe472 to your computer and use it in GitHub Desktop.
APP_NAME=Elearny
APP_ENV=local
APP_KEY=base64:F3lX2XiWbULtR5SwZnR4TNVn/E93S1Fg/lMepg6vxWg=
APP_DEBUG=true
APP_URL=https://elearning.theteam.com.tn
FRONTEND_URL=https://cool-napier.85-215-138-217.plesk.page
#https://elearning.theteam.com.tn
#http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=admin-db
DB_PASSWORD=Azerty123456%
#BROADCAST_DRIVER=log
#CACHE_DRIVER=file
#FILESYSTEM_DISK=local
#QUEUE_CONNECTION=sync
#SESSION_DRIVER=file
#SESSION_LIFETIME=120
MODEL_CACHE_STORE=array
BROADCAST_DRIVER=log
CACHE_DRIVER=array
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
#127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=ssl0.ovh.net
MAIL_PORT=465
MAIL_USERNAME=razi.fertani@theteam.com.tn
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=razi.fertani@theteam.com.tn
MAIL_FROM_NAME="${APP_NAME}"
#MAIL_MAILER=smtp
#MAIL_HOST=mailpit
#MAIL_PORT=1025
#MAIL_USERNAME=null
#MAIL_PASSWORD=null
#MAIL_ENCRYPTION=null
#MAIL_FROM_ADDRESS="hello@example.com"
#MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
# new 12-06-24
JWT_SECRET=J85WDsrFxwPyfSX8AK3JGumGLIVQ6gJsB2YK4khx8AvsElt5JmLhfybklkDKgEq0
RESPONSE_CACHE_DRIVER=array|redis|memcached

Laravel

Commands

composer install
composer dump-autoload
composer update

Database Schema Generation

php artisan serve --port=8020
php artisan migrate
php artisan migrate --seed
php artisan migrate:refresh
php artisan migrate:refresh --seed



.env server theteam :

php artisan serve --port=8020 --host=0.0.0.0




When quizzes table is deleted :

php artisan make:migration create_quizzes_table
php artisan migrate

  • To Double Check :
    • Migration Status: You can check the status of your migrations using the command:
    • Rollback & Re-migrate: If needed, you can rollback the last batch of migrations (which will drop the tables) and then re-run them.
php artisan migrate:status
php artisan migrate:rollback
composer require barryvdh/laravel-ide-helper





https://stackoverflow.com/questions/68515548/phpstorm-says-find-method-not-found

https://techvblogs.com/blog/laravel-10-crud-example-tutorial-for-beginners

@iifast2
Copy link
Author

iifast2 commented Feb 13, 2024

https://getbootstrap.com/docs/5.3/components/carousel/

Installation Instructions

Follow these steps to install and deploy the application.

Deployment

  1. Extract the archive and place it in the desired folder.

  2. Run cp .env.example.env file to copy example file to .env

    Then edit your .env file with database credentials and other settings.

  3. Install dependencies using the following command:

composer install
  1. Run the following command to migrate and seed the database:

php artisan serve --port=8020

php artisan migrate --seed

Notice: seed is important, because it will create the first admin user for you.

  1. Run the following command to generate an application key:
php artisan key:generate
  1. If you have file/photo fields, run the following command:
php artisan storage:link

Check this config before I start :

https://stackoverflow.com/a/65464353/10216101

php artisan route:clear
php artisan route:clear;
php artisan optimize:clear
  1. That's it! Visit your domain and log in.
php artisan serve --port=8020

Default Credentials

Use the following credentials for the initial login:

  • Username: admin@admin.com
  • Password: password





Modify the Controller:

Each method in the controller (typically index, store, show, update, destroy) should return a JSON response.
Ensure that each method handles data validation, business logic, and error handling appropriately.
Testing with Postman:

For each method in the controller, create a corresponding request in Postman.

Test the index method (GET request) to list all permissions.

Test the store method (POST request) to create a new permission.

Test the show method (GET request) to display a specific permission.

Test the update method (PUT/PATCH request) to update a permission.

Test the destroy method (DELETE request) to delete a permission.

Ensure you handle authentication in Postman, possibly using the token obtained from the login API.
Consider Pagination and Filtering:

For the index method, consider implementing pagination and filtering if your application expects a large number of records.
Error Handling:

Ensure that your API endpoints return meaningful error messages and appropriate HTTP status codes.




POSTMAN PREREQUEST that I used to do :

pm.test("Setting xsrf_token env vairable", function () {
    let cookie = pm.response.cookies.get('XSRF-TOKEN');
    if(cookie) pm.environment.set('xsrf-token',cookie);
    else {
        let header = pm.response.headers.find(h => h.key == 'Set-Cookie' && h.value.startsWith('XSRF-TOKEN'));
        cookie = header?.value.substring(header?.value.indexOf("=") + 1, header?.value.indexOf("%3D"));
        pm.environment.set('xsrf-token',cookie);
    }
});




.env.example :

################# 2 :

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:OnTnXD0biFyP0lKGgAjLqUJa++cCcul+VNn+MAKKzaQ=
APP_DEBUG=true
APP_URL=http://localhost:8000

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

#### mine : https://laracasts.com/discuss/channels/laravel/sanctum-spa-csrf-token-mismatch-via-postman

SESSION_DOMAIN=http://localhost:8000
SANCTUM_STATEFUL_DOMAINS=http://localhost:8000
SESSION_SECURE_COOKIE=false


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-elearny-2
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"


@iifast2
Copy link
Author

iifast2 commented Jun 4, 2024

Issue when I used the /auth/login

// HTTPS Status : 500 - Internal Server Error !

// HTTP Response : 

{  
 "message": "This cache store does not support tagging." 
 }

To Solve this issue :

https://onlinecode.org/this-cache-store-does-not-support-tagging-in-laravel/


Step A: Generate the JWT Secret Key
Run the artisan command to generate a JWT secret key:

php artisan jwt:secret

This command will generate a secret key and add it to your .env file as JWT_SECRET.

Step B: Manually Edit the .env File (if necessary)

If you need to add or update the JWT secret key manually, you can do so by editing the .env file directly.

Open the File Manager in Plesk.

Navigate to your Laravel project's root directory.

Locate and open the .env file.

Add or update the following line with the generated key:

JWT_SECRET=your_generated_secret_key

Replace your_generated_secret_key with the actual key you generated.

Step C: Ensure Proper Permissions

Make sure that the .env file has the correct permissions so that your Laravel application can read it. You can set the permissions using the Plesk File Manager or via the terminal:

chmod 644 .env

Step D: Clear Configuration Cache

After updating the .env file, clear the configuration cache to ensure Laravel uses the latest environment variables:

php artisan config:cache

@iifast2
Copy link
Author

iifast2 commented Jun 4, 2024

latest in onos team :

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:/MhDbqjItvDxB1aUEpnyMMz0uW4OGiYrrnhc3gva7JQ=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-db
DB_USERNAME=admindb
DB_PASSWORD=Azerty123456%

# https://onlinecode.org/this-cache-store-does-not-support-tagging-in-laravel/
MODEL_CACHE_STORE=array
BROADCAST_DRIVER=log
CACHE_DRIVER=array
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120


MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

#JWT_SECRET=

#JWT_SECRET=KEMN0sZTCW0UWjrEtCg3OejYbZqjTJAF1bwxzlTXDmm0FDC7IrqynKdKqfmsgOiq
# I added this : https://stackoverflow.com/a/58790885/10216101
RESPONSE_CACHE_DRIVER=array|redis|memcached

# 

JWT_ALGO=RS512

JWT_PRIVATE_KEY=file://../storage/certs/jwt-rsa-4096-private.pem

JWT_PUBLIC_KEY=file://../storage/certs/jwt-rsa-4096-public.pem

JWT_PASSPHRASE=

@iifast2
Copy link
Author

iifast2 commented Jun 4, 2024

issue in plesk :

# composer update
Execution /opt/plesk/php/8.2/bin/php has failed with exit code 1, stdout: , stderr: 
In PluginManager.php line 752:
                                                                               
  plesk/composer-command-info (installed globally) contains a Composer plugin  
   which is blocked by your allow-plugins config. You may add it to the list   
  if you consider it safe.                                                     
  You can run "composer global config --no-plugins allow-plugins.plesk/compos  
  er-command-info [true|false]" to enable it (true) or disable it explicitly   
  and suppress this exception (false)                                          
  See https://getcomposer.org/allow-plugins
composer global config --no-plugins allow-plugins.plesk/composer-command-info true



related links :




@iifast2
Copy link
Author

iifast2 commented Jun 12, 2024

I removed the commented kernel file (to make images work ) :

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array<int, class-string|string>
     */
    protected $middleware = [
        \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            \Illuminate\Routing\Middleware\ThrottleRequests::class . ':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's middleware aliases.
     *
     * Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
     *
     * @var array<string, class-string|string>
     */
    protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
        'signed' => \App\Http\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,

        'check_if_user_is_blocked' => \App\Http\Middleware\CheckIfUserIsBlockedMiddleware::class,
    ];
}

@iifast2
Copy link
Author

iifast2 commented Jun 12, 2024

# sudo -s
# cd /var/www/vhosts/elearning.theteam.com.tn/httpdocs
php artisan storage:link
sudo chmod -R 775 storage/app/public

@iifast2
Copy link
Author

iifast2 commented Jun 12, 2024

The error you're seeing indicates that the request to fetch the image from https://elearning.theteam.com.tn/storage/files/4here_we_go.jpg is being blocked by the browser's CORS policy. This means the server at elearning.theteam.com.tn is not allowing requests from the domain https://cool-napier.85-215-138-217.plesk.page.

To fix this issue, you need to configure your Laravel backend to include the Access-Control-Allow-Origin header in its responses. Here’s how to do it:

Step 1: Update CORS Configuration

Update your config/cors.php file to allow requests from your frontend domain:

<?php

return [

    'paths' => ['api/*', 'storage/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['<https://cool-napier.85-215-138-217.plesk.page>'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => ['Authorization', 'Content-Type'],

    'max_age' => 0,

    'supports_credentials' => false,

];

Step 2: Install Laravel CORS Package (If Not Installed)

If you haven't already installed the Laravel CORS package, you can do so using Composer:

composer require fruitcake/laravel-cors

Step 3: Clear Configuration Cache

After updating the CORS configuration, clear the configuration cache to ensure Laravel uses the updated settings:

php artisan config:clear
php artisan cache:clear

@iifast2
Copy link
Author

iifast2 commented Jun 12, 2024

php artisan vendor:publish --provider="Fruitcake\Cors\CorsServiceProvider"

@iifast2
Copy link
Author

iifast2 commented Jun 12, 2024

To ensure that files uploaded through your application have the correct permissions, you need to configure your Laravel application to set the appropriate permissions when saving files. Additionally, resolving the CORS issue is crucial.

Step 1: Ensure Correct File Permissions on Upload

You can set the file permissions when saving files in Laravel. Here’s how you can do it:

  1. Open your file upload logic:
    If you have a controller or service handling file uploads, you can set the permissions there. For example:

    // Assuming you're using the default storage disk
    $path = $request->file('your_file_input')->store('public/files');
    
    // Get the full path to the file
    $fullPath = storage_path('app/' . $path);
    
    // Set the file permissions to 0644 (readable by everyone)
    chmod($fullPath, 0644);
  2. Example in Controller:

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    class FileUploadController extends Controller
    {
        public function upload(Request $request)
        {
            // Validate the request...
            $validated = $request->validate([
                'file' => 'required|file|mimes:jpg,jpeg,png,gif',
            ]);
    
            // Store the file
            $path = $request->file('file')->store('public/files');
    
            // Set permissions to be readable by everyone
            $fullPath = storage_path('app/' . $path);
            chmod($fullPath, 0644);
    
            return response()->json(['path' => $path], 200);
        }
    }

Step 2: Fix CORS Issue

Ensure the fruitcake/laravel-cors package is correctly configured and headers are set properly.

  1. Install the package:

    composer require fruitcake/laravel-cors
  2. Publish the configuration:

    php artisan vendor:publish --provider="Fruitcake\Cors\CorsServiceProvider"
  3. Configure config/cors.php:

    return [
    
        'paths' => ['api/*', 'storage/*'],
    
        'allowed_methods' => ['*'],
    
        'allowed_origins' => ['https://cool-napier.85-215-138-217.plesk.page'],
    
        'allowed_origins_patterns' => [],
    
        'allowed_headers' => ['*'],
    
        'exposed_headers' => ['Authorization', 'Content-Type'],
    
        'max_age' => 0,
    
        'supports_credentials' => false,
    
    ];
  4. Ensure the middleware is registered in app/Http/Kernel.php:

    protected $middleware = [
        // other middleware
        \Fruitcake\Cors\HandleCors::class,
    ];
  5. Clear configuration cache:

    php artisan config:clear
    php artisan cache:clear

Step 3: Verify Web Server Configuration

Ensure that your web server is configured to allow CORS headers:

  • For Nginx:

    Add the following in your server block:

    server {
        // other configurations
    
        location / {
            add_header 'Access-Control-Allow-Origin' 'https://cool-napier.85-215-138-217.plesk.page';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
        }
    }
  • For Apache:

    Add this in your .htaccess file:

    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "https://cool-napier.85-215-138-217.plesk.page"
        Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
        Header set Access-Control-Allow-Headers "Content-Type, Authorization"
    </IfModule>

Step 4: Test the Configuration

After making these changes, upload a new file through your application and verify that:

  1. The file has the correct permissions (0644).
  2. The file is accessible via its URL.
  3. The CORS headers are correctly set and no errors are shown in the console.

By following these steps, you should be able to ensure that files uploaded through your application have the correct permissions and are accessible from your frontend app without CORS issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment