jeudi 30 décembre 2021

Laravel 5.8 scheduler is not running commands

This question is asked before but non of the answers work for me. This is the Kernel.php

<?php

namespace App\Console;

use App\Console\Commands\TestRunKernel;
use App\Log;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;


class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        TestRunKernel::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        Log::create([
            'body' => 'test for log'
        ]);
        $schedule->call(function () {
           Log::create([
               'body' => 'test2 for log'
           ]);
        })->everyMinute();
        $schedule->command('test:run')->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}

and this is the command

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Modules\User\Entities\User;

class TestRunKernel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $user = User::find(1);
        $user->update([
            'file' => 1
        ]);
    }
}

The Kernel.php is running by cron job and test for log message is written in Log model. Hence I am sure the file is running by server. But when I use $schedule it doesn't work and non of the commands work. How can I fix this?

Thanks in advance.



via Chebli Mohamed

mercredi 29 décembre 2021

include script in header for get params laravel

I´m traying to include in my blade other blade that contain script js to get any configuration parameters. But when load my page return this:

Uncaught SyntaxError: Invalid hexadecimal escape sequence

and

Uncaught ReferenceError: phpToJs is not defined

i´m inclining into my blade like this:


        @include('layouts.php_to_js')

and my blade contain this:

<script type="text/javascript">
    // global app configuration object
    var phpToJs = {
        url: {
            app_path: '{!! app_path() !!}',
            base_path: '{!! base_path() !!}',
            config_path: '{!! config_path() !!}',
            database_path: '{!! database_path() !!}',
            public_path: '{!! public_path() !!}',
            resource_path: '{!! resource_path() !!}',
            storage_path: '{!! storage_path() !!}',
            base_url: '{!! config("app.url") !!}',
            base_url_admin: '{!! config("app.url") !!}admin/',
            currentName: '{!! Route::currentRouteName() !!}',
            currentFull: '{!! Request::fullUrl() !!}',
            currentUrl: '{!! URL::current() !!}',
        },
        csrf: '{!! csrf_token() !!}',
        language: '{!! session()->get("language") !!}',
    };

</script>

i´m using this for to can use name routes in external files js (external to blade).If i show code for my website, it´s result:

<script type="text/javascript">
    // global app configuration object
    var phpToJs = {
        url: {
            app_path: 'C:\xampp\htdocs\gdsRepository\app',
            base_path: 'C:\xampp\htdocs\gdsRepository',
            config_path: 'C:\xampp\htdocs\gdsRepository\config',
            database_path: 'C:\xampp\htdocs\gdsRepository\database',
            public_path: 'C:\xampp\htdocs\gdsRepository\public',
            resource_path: 'C:\xampp\htdocs\gdsRepository\resources',
            storage_path: 'C:\xampp\htdocs\gdsRepository\storage',
            base_url: 'http://localhost/gdsRepository/public/',
            base_url_admin: 'http://localhost/gdsRepository/public/admin/',
            currentName: 'admin.precontratos.create',
            currentFull: 'https://localhost/gdsRepository/public/index.php/admin/precontratos/create',
            currentUrl: 'https://localhost/gdsRepository/public/index.php/admin/precontratos/create',
        },
        csrf: 'eoEE6xbNUQu53ze90x7dr1pCSE5lrEGugXsQldia',
        language: '',
    };

</script>    </head>

my script it´s there, but i can´t use it... any idea to solve my problems?

Thanks for read and help me. Sorry for my english



via Chebli Mohamed

Laravel Date Mutators Nested Object

Person Collection

    {
      name: 'Jack',
      dateOfBirth: ISODate("1975-12-29T00:00:00.000Z")
      club: {
         name: 'A Club',
         joinedAt: ISODate("2020-10-29T14:12:01.309Z")
      }
    }

Person Model

protected $dates = ['dateOfBirth'];

How can I add the date fields in nested objects to this array?



via Chebli Mohamed

mardi 28 décembre 2021

Laravel 5.4: Installation failed, reverting ./composer.json and ./composer.lock to their original content while trying to install a package [duplicate]

I'm working with Laravel 5.4 and I wanted to install Laravel Sluggable package but I got this error on the Terminal:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - cviebrock/eloquent-sluggable[8.0.0, ..., 8.0.8] require illuminate/config ^8.0 -> found illuminate/config[v8.0.0, ..., v8.77.1] but these were not loaded, li
kely because it conflicts with another require.
    - Root composer.json requires cviebrock/eloquent-sluggable ^8.0 -> satisfiable by cviebrock/eloquent-sluggable[8.0.0, ..., 8.0.8].

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

And here is my Composer.json file:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.7"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    }
}

I don't know really what's going wrong here and how can I fix this issue.. So if you know please let me know, cause I really need it.



via Chebli Mohamed

lundi 27 décembre 2021

why is the user being able to submit the POST even if the captcha is not verified?

I'm trying to set the google recaptcha, but whenever the user submits the form it gets verified, even if the captcha is not verified. Why can that be due to? I think everything is set up correctly with required and everything:

This is my registraton controller: I think the frontend is fine, as I can see and the captcha is interactive

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/login';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone' => ['required', 'string', 'regex:/^([0-9\s\-\+\(\)]*)$/', 'min:8'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'g-recaptcha-response' => ['required', function ($attribute, $value, $fail) {
                $secretKey = "6LfGStAdAAAAAOQZWvjtATtnjmGc48YoMTtfrxPc";
                $response = $value;
                $userIP = $_SERVER['REMOTE_ADDR'];
                 $url = 'https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$userIP';
                 $response = \file_get_contents($url);
                 $response = json_decode($response);
                 if (!$response->success) {
                     Session::flash("g-recaptcha-response", "Please check the the captcha form.");
                     Session::flash("alert-class", "alert-danger");
                     $fail('The recaptcha is not valid');
                 } 
             }
            ],
        ];
        if (config('settings.enable_birth_date_on_register') && config('settings.minimum_years_to_register')) {
            $rules['birth_date'] = 'required|date|date_format:Y-m-d|before:-'.config('settings.minimum_years_to_register').' years';
        }
        //dd($rules);
        return Validator::make($data, $rules);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        /*return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'password' => Hash::make($data['password']),
            'api_token' => Str::random(80)
        ]);*/

        //dd($data);

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'password' => Hash::make($data['password']),
            'api_token' => Str::random(80),
            'birth_date' => isset($data['birth_date']) ? $data['birth_date'] : ''
        ]);

        $user->assignRole('client');

        //Send welcome email
        //$user->notify(new WelcomeNotification($user));

        return $user;
    }

    protected function registered(Request $request, User $user)
    {
        if (config('settings.enable_sms_verification')) {
            // $user->callToVerify();
        }

        return redirect($this->redirectPath());
    }
}


via Chebli Mohamed

dimanche 26 décembre 2021

LaraCSV export error ( Because of big data)

I have this code in my laravel project which creates and downloads CSV from Laravel Query $csvExporter->build($example_users, $example_headers, array('header'=>true))->download($fileName); But i am getting internal error because the $example_users table is too big. I know that there is some way to do it with chunks e.c (LaraCSV Repo) But can't configure out how. Please help



via Chebli Mohamed

How to use old Laravel routing style in Laravel 8

I just installed Laravel 8 and in this version, I have to type my routes like this:

Route::get('/admin/panel', [App\Http\Controllers\Admin\PanelController::class, 'index']);

But I got used to Laravel 5 routes which looked like this:

Route::namespace('Admin')->prefix('admin')->group(function () {
    Route::get('/panel', 'Admin/PanelController@index');
});

So how can I use this Laravel 5 routing inside Laravel 8 version?



via Chebli Mohamed

samedi 25 décembre 2021

Eloquent relationship give [ticket_id] does not exist on this collection instance laravel

I am have some issue with eloquent relationship my first time working with it, after selecting and displaying list of selected events, I want to also select the ticket_id base on the event_id common between both(events and events_ticket) table, thanks for the help

Error Showing -> Trying to get property 'ticket_id' of non-object (View: C:\wamp64\www\mahive\resources\views\tickets\index.blade.php)

Both Model

class EventsTicket extends Model
{
    public $table = "events_ticket";
    use HasFactory;
    protected $fillable = [
        'event_id',
        'ticket_id',
        'ticket_name',
        'ticket_amount',
        'ticket_sold',
    ];

    public function event() {
        return $this->belongsTo('App\Models\Event');
    }
}

class Event extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'event_id',
        'event_name',
        'event_category',
        'event_type',
        'event_mode',
        'event_description',
        'event_image'
    ];

    public function userModel() {
        return $this->belongsTo('App\Models\User');
    }

    public function eticket() {
        return $this->hasMany('App\Models\EventsTicket');
    }
}

Controller

public function index()
{
    $events = Event::where('ticket_statue', 'active')->with('eticket')->get();
    return view('tickets.index', ['event_data' => $events]); 
}

View

@foreach($event_data as $event)
    
    
@endforeach


via Chebli Mohamed

MongoDB Class 'MongoDB\Driver\Manager' not found" in Laravel 5.7, php 7.3 (on Ubuntu 20.4 and Apache)

I am running a laravel 5.7 app on apache server which i have tried on the different php versions(7.2, 7.3) i have installed on my ubuntu system. Upon hitting the apps url in the browser i get this error Class 'MongoDB\Driver\Manager' not found I have been battling with this for a while now and have tried so many solutions out there but it still persists. I have mongodb extension installed on all the php distributions. Funny enough, When i tried getting a record from the db using tinker it works very fine.



via Chebli Mohamed

vendredi 24 décembre 2021

Handling token expired in Laravel JWT

I'm using tymondesigns/jwt-auth in Laravel and angular application, this is the code i'm using i'm getting token expired error from laravel end in my network tab when idle time is more than 20-30 min but my ttl value is 1440, and front end user should get message in popup that their session expire rather than getting 500 error in console.

jwt.php

<?php

/*
 * This file is part of jwt-auth.
 *
 * (c) Sean Tymon <tymon148@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

return [

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Secret
    |--------------------------------------------------------------------------
    |
    | Don't forget to set this in your .env file, as it will be used to sign
    | your tokens. A helper command is provided for this:
    | `php artisan jwt:secret`
    |
    | Note: This will be used for Symmetric algorithms only (HMAC),
    | since RSA and ECDSA use a private/public key combo (See below).
    |
    */

    'secret' => env('JWT_SECRET'),

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Keys
    |--------------------------------------------------------------------------
    |
    | The algorithm you are using, will determine whether your tokens are
    | signed with a random string (defined in `JWT_SECRET`) or using the
    | following public & private keys.
    |
    | Symmetric Algorithms:
    | HS256, HS384 & HS512 will use `JWT_SECRET`.
    |
    | Asymmetric Algorithms:
    | RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
    |
    */

    'keys' => [

        /*
        |--------------------------------------------------------------------------
        | Public Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your public key.
        |
        | E.g. 'file://path/to/public/key'
        |
        */

        'public' => env('JWT_PUBLIC_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Private Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your private key.
        |
        | E.g. 'file://path/to/private/key'
        |
        */

        'private' => env('JWT_PRIVATE_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Passphrase
        |--------------------------------------------------------------------------
        |
        | The passphrase for your private key. Can be null if none set.
        |
        */

        'passphrase' => env('JWT_PASSPHRASE'),

    ],

    /*
    |--------------------------------------------------------------------------
    | JWT time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token will be valid for.
    | Defaults to 1 hour.
    |
    | You can also set this to null, to yield a never expiring token.
    | Some people may want this behaviour for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    | Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
    |
    */

    'ttl' => env('JWT_TTL',1440),

    /*
    |--------------------------------------------------------------------------
    | Refresh time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token can be refreshed
    | within. I.E. The user can refresh their token within a 2 week window of
    | the original token being created until they must re-authenticate.
    | Defaults to 2 weeks.
    |
    | You can also set this to null, to yield an infinite refresh time.
    | Some may want this instead of never expiring tokens for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    |
    */

    'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),

    /*
    |--------------------------------------------------------------------------
    | JWT hashing algorithm
    |--------------------------------------------------------------------------
    |
    | Specify the hashing algorithm that will be used to sign the token.
    |
    | See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL
    | for possible values.
    |
    */

    'algo' => env('JWT_ALGO', 'HS256'),

    /*
    |--------------------------------------------------------------------------
    | Required Claims
    |--------------------------------------------------------------------------
    |
    | Specify the required claims that must exist in any token.
    | A TokenInvalidException will be thrown if any of these claims are not
    | present in the payload.
    |
    */

    'required_claims' => [
        'iss',
        'iat',
        'exp',
        'nbf',
        'sub',
        'jti',
    ],

    /*
    |--------------------------------------------------------------------------
    | Persistent Claims
    |--------------------------------------------------------------------------
    |
    | Specify the claim keys to be persisted when refreshing a token.
    | `sub` and `iat` will automatically be persisted, in
    | addition to the these claims.
    |
    | Note: If a claim does not exist then it will be ignored.
    |
    */

    'persistent_claims' => [
        // 'foo',
        // 'bar',
    ],

    /*
    |--------------------------------------------------------------------------
    | Lock Subject
    |--------------------------------------------------------------------------
    |
    | This will determine whether a `prv` claim is automatically added to
    | the token. The purpose of this is to ensure that if you have multiple
    | authentication models e.g. `App\User` & `App\OtherPerson`, then we
    | should prevent one authentication request from impersonating another,
    | if 2 tokens happen to have the same id across the 2 different models.
    |
    | Under specific circumstances, you may want to disable this behaviour
    | e.g. if you only have one authentication model, then you would save
    | a little on token size.
    |
    */

    'lock_subject' => true,

    /*
    |--------------------------------------------------------------------------
    | Leeway
    |--------------------------------------------------------------------------
    |
    | This property gives the jwt timestamp claims some "leeway".
    | Meaning that if you have any unavoidable slight clock skew on
    | any of your servers then this will afford you some level of cushioning.
    |
    | This applies to the claims `iat`, `nbf` and `exp`.
    |
    | Specify in seconds - only if you know you need it.
    |
    */

    'leeway' => env('JWT_LEEWAY', 0),

    /*
    |--------------------------------------------------------------------------
    | Blacklist Enabled
    |--------------------------------------------------------------------------
    |
    | In order to invalidate tokens, you must have the blacklist enabled.
    | If you do not want or need this functionality, then set this to false.
    |
    */

    'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),

    /*
    | -------------------------------------------------------------------------
    | Blacklist Grace Period
    | -------------------------------------------------------------------------
    |
    | When multiple concurrent requests are made with the same JWT,
    | it is possible that some of them fail, due to token regeneration
    | on every request.
    |
    | Set grace period in seconds to prevent parallel request failure.
    |
    */

    'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),

    /*
    |--------------------------------------------------------------------------
    | Cookies encryption
    |--------------------------------------------------------------------------
    |
    | By default Laravel encrypt cookies for security reason.
    | If you decide to not decrypt cookies, you will have to configure Laravel
    | to not encrypt your cookie token by adding its name into the $except
    | array available in the middleware "EncryptCookies" provided by Laravel.
    | see https://laravel.com/docs/master/responses#cookies-and-encryption
    | for details.
    |
    | Set it to true if you want to decrypt cookies.
    |
    */

    'decrypt_cookies' => false,

    /*
    |--------------------------------------------------------------------------
    | Providers
    |--------------------------------------------------------------------------
    |
    | Specify the various providers used throughout the package.
    |
    */

    'providers' => [

        /*
        |--------------------------------------------------------------------------
        | JWT Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to create and decode the tokens.
        |
        */

        'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,

        /*
        |--------------------------------------------------------------------------
        | Authentication Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to authenticate users.
        |
        */

        'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,

        /*
        |--------------------------------------------------------------------------
        | Storage Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to store tokens in the blacklist.
        |
        */

        'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,

    ],

];

Auth Controller.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;

class AuthController extends Controller
{
   
    public function __construct() {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

     /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        if (! $token = auth()->attempt($validator->validated())) {
            return response()->json(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
        }

        return $this->createNewToken($token);
    }

      /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request) {
        $messages = [
            'password.confirmed' => 'Password Confirmation should match the Password',
            'password.min' => ' Password should be minimum 6 digits',
        ];
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ],$messages);

        if($validator->fails()){
            return response()->json($validator->errors(), 422);
        }

        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)]
                ));

        return response()->json([
            'message' => 'Successfully registered',
        ], 201);
    }

      /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout() {
        auth()->logout();

        return response()->json(['message' => 'User successfully signed out']);
    }

      /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh() {
        return $this->createNewToken(auth()->refresh());
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userProfile() {
        return response()->json(auth()->user());
    }

     /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function createNewToken($token){
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60,
            'user' => auth()->user()
        ]);
    }
}

api.php

Route::group([
    'middleware' => ['api'],
    'prefix' => 'auth'

], function ($router) {
    Route::post('/login', [AuthController::class, 'login'])->name('login');
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/logout', [AuthController::class, 'logout']);
    ..
});

Angular Code:

Auth Interceptor.ts

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler } from "@angular/common/http";
import { TokenService } from "../shared/token.service";

@Injectable()

export class AuthInterceptor implements HttpInterceptor {
    constructor(private tokenService: TokenService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const accessToken = this.tokenService.getToken();
        req = req.clone({
            setHeaders: {
                Authorization: "Bearer " + accessToken
            }
        });
        return next.handle(req);
    }
}

token_service.ts

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})

export class TokenService {
  baseUrl = environment.baseUrl;

  private issuer = {
    login: this.baseUrl+'api/auth/login',
    register: this.baseUrl+'api/auth/register'
  } 

  constructor() { }

  handleData(token  : any){
    localStorage.setItem('auth_token', token);
  }

  getToken(){
    return localStorage.getItem('auth_token');
  }

  // Verify the token
  isValidToken(){
     const token = this.getToken();

     if(token){
       const payload = this.payload(token);
       if(payload){
         return Object.values(this.issuer).indexOf(payload.iss) > -1 ? true : false;
       }
     } else {
        return false;
     }
  }

  payload(token  : any) {
    const jwtPayload = token.split('.')[1];
    return JSON.parse(atob(jwtPayload));
  }

  // User state based on valid token
  isLoggedIn() {
    return this.isValidToken();
  }

  // Remove token
  removeToken(){
    localStorage.removeItem('auth_token');
  }

}

Error: enter image description hereAny Solution Thanks



via Chebli Mohamed

jeudi 23 décembre 2021

problem with session in iOS Safari - laravel

I have a problem with iOS devices, i working with laravel and sessions,

i using a payment module, the answer that the process gives me but is Null

in other browsers with Android system it does not lose the session

public function invoke(Request $request) {
    
      $payment_id = $request->get('payment_id');
    
    
      $response = Http::get("https://api.mercadopago.com/v1/payments/$payment_id" . "?access_token=TEST-CODEX-349463544506SADSA7");
      
      $response = json_decode($response);
    
      $request->session()->put('order', $response->order->id);
      $request->session()->put('ingreso', $response->transaction_details->net_received_amount);
      $request->session()->put('monto', $response->transaction_details->total_paid_amount);
      $request->session()->put('metodo', $response->payment_type_id); 
     $status = $response->status;
    
    
     if($status == 'approved') {
    
    
      Ingresosmp::insert([
        'user_id'       => Session::get('user_id'),
        'evento_id'       => Session::get('variableName'),
        'mp_id'  => Session::get('order'),
        'metodo'        => Session::get('metodo'),
        'monto'        => Session::get('monto'),
        'ingreso'        => Session::get('ingreso'),
    
    
      ]);
    
     
      
    
      return redirect('success')->with('success', 'okAY!');
    
    
    }

Image with problem:

https://i.imgur.com/nNUrhSL.png

help pls



via Chebli Mohamed

mercredi 22 décembre 2021

How to automatically reorder/sort div according to highest id

I want to automatically reorder/sort a div according to the highest vote count once an ajax call is done, I have tried many thing codes and none seems to be working. Below is the code.

@foreach($candidates->sortByDesc("voteCount") as $candidate) 
                <div class="col-md-6" id="">// this is the div I want to reorder
        <div class="card">
        <div class="card-header">
                    <h4 class="card-title" id="heading-multiple-thumbnails"> </h4>
                    <a class="heading-elements-toggle">
                        <i class="la la-ellipsis-v font-medium-3"></i>
                    </a>
                    
                </div>
        </div>
    </div>
            @endforeach

The Javascript

  
         $('.castVoteForCandidateButton').on('click', function (e) {
             $("#voteCofirmStatus").hide();
             $("#voteProccessStatus").show();
             $.ajax({
                    type:'POST',
                    url:'/vote',
                    data:{candidateId : candidateId, _token: "<?php echo csrf_token(); ?>",name:name ,position:position},
                    success:function(data){
                         if(data.status =='ok' ){
                             setTimeout(function() {$('#voteProcessingModal').modal('hide');}, 500);
                            $("#voteProccessStatus").hide();
                            $("#voteSuccessStatus").show().text('Nice job!,you have successfully voted for '+ data.name);
                            $("#voteCount"+data.id).text(parseFloat(data.voteCount)+" Votes");
                            $("#confirmCandidateVoteButton"+data.id).hide();
                            var div = $("#voteCount"+data.id);
                            div.animate({fontSize: "30px"}, "slow");
                            div.animate({fontSize: "17px"}, "slow");


         const main = document.querySelector('#main');// this
        const divs = [...main.children];// is
        divs.sort((a, b) => a.id - b.id);// the 
        divs.forEach(div => main.appendChild(div));// Latest code I tried and its not working
                             }else{
                                 $("#voteErrorStatus").show().text(data);
                                 
                             }
                       }
                     });  
         } );


via Chebli Mohamed

Can I use a Models scope with Laravel's 5.5 Query Builder Join method?

I am trying to use Laravel 5.5 Query Builders Join method with a scope method from the CommercialCoupon Model but when I try to apply this scope I get this error:

[2021-12-22 23:18:16] lumen.ERROR: BadMethodCallException: Call to undefined method Illuminate\Database\Query\JoinClause::filterBlockedCoupons() in /var/www/new-api/vendor/illuminate/database/Query/Builder.php:2483

My CommercialCoupon Model has this scope:

public function scopeFilterBlockedCoupons($query, $channelPartnerId){
    $query->whereNotIn('discount_provider_id', function($subquery) use ($channelPartnerId)
        {
            $subquery->select('discount_providers.id')
            ->from('discount_providers')
            ->join('discount_provider_permissions', function($join)
            {
                $join->on('discount_provider_permissions.discount_provider_id', '=', 'discount_providers.id' );
                $join->on('discount_providers.block_type', '=', \DB::raw(Config::get('systemtype.discount_provider_block_types.deny')));
            })
            ->where('discount_provider_permissions.channel_partner_id', '=', \DB::raw($channelPartnerId));
        })
    ->whereNotIn('discount_provider_id',  function($subquery) use ($channelPartnerId)
        {
            $subquery->select(\DB::raw('
                CASE WHEN COUNT(discount_provider_permissions.id) > 0 then
                    -1
                ELSE
                    discount_providers.id
                END
                AS excludedDiscountProviderId'))
            ->from('discount_providers')
            ->leftJoin('discount_provider_permissions', function($join) use ($channelPartnerId)
            {
                $join->on('discount_provider_permissions.discount_provider_id', '=', 'discount_providers.id' );
                $join->on('discount_provider_permissions.channel_partner_id', '=', \DB::raw($channelPartnerId) );
            })
        ->where('discount_providers.block_type', '=', \DB::raw(Config::get('systemtype.discount_provider_block_types.allow')))
        ->groupBy('discount_providers.id');
    });
}

This scope works perfectly if I'm calling the CommercialCoupon Model directly.

When I try to use this scope inside of a join displayed in the code below I get the error above:

$coupons = Carousel::where('carousels.channel_partner_id', '=', $selectedChannelPartnerId)
    ->join('carousel_contents', 'carousels.id', '=', 'carousel_contents.carousel_id')
    ->join('commercial_coupons', function ($join) use ($channelPartnerId) {
        $join->on('commercial_coupons.id', '=', 'carousel_contents.table_id')
            ->filterBlockedCoupons($channelPartnerId);
    })
    ->join('discount_providers', 'discount_providers.id', '=', 'commercial_coupons.discount_provider_id')
    ->where('carousel_contents.table_name', '=', \DB::raw("'commercial_coupons'"))
    ->select("commercial_coupons.logo_image AS marketing_image", "commercial_coupons.id AS coupon_id", "discount_providers.name as discount_provider_name", "commercial_coupons.coupon_org_name as coupon_title", "commercial_coupons.discount_provider_id")
    ->orderBy('carousel_contents.order')
    ->get();

Am I able to use the scope on the Model or do I just have to copy and paste the code inside the scope this specific join?



via Chebli Mohamed

mardi 21 décembre 2021

upload and minimize several images with livewire in a sails container

I am working on a laravel project with docker containers. The project therefore uses a sails container. I have an input in a form for uploading photos with livewire. But I have a problem as soon as the total of uploaded images exceeds 100MB. I have 2 questions: the blocking beyond 100MB depends on sails or livewire and how to configure it?

with livewire, if I want to use a third party API like tinyPNG to minimize images can I do this between when livewire creates temporary files and when it permanently stores the files? or when it creates the temporary files, I am already limited by the global maximum size of the upload?

thanks.



via Chebli Mohamed

laravel dynamic drop down not giving value

im using ajax for laravel dropdown it was working but when i tiring to submit form it was giving id number

im getting right input in dropdown field when i try to submit page it was giving id number instead of dropdown value i what to get value of MS OFFICE AND 1000 BUT IT STORING IN DATA BASCE {COURES TYPE C_1402:} { COURSE PRICE C_1402:}

my view enter image description here

my network tab showing this id enter image description here my view page

 <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="location1">Course Type  :<span class="danger">*</span> </label>
                                            <select class="custom-select form-control required" name="student_course" id="student_courses" name="location" required>
                                            <option value="">Select Course</option>
                                                @foreach ($course_name as $key => $value)
                                                    <option value=""></option>
                                                @endforeach
                                          
                                            </select>  
                                        </div>
                                    </div>

  <div class="col-md-3">
                                            <div class="form-group">
                                                <label for="videoUrl1">Course Price :</label>
                                                <select name="course_Price" id="course_Prices" class="form-control dynamic" data-dependent="course_Price">
                                                <option value=""></option>
                                                </select>
                                            </div>
                                        </div>

ajax

 <script type="text/javascript">
    $(document).ready(function() {
        $('#student_courses').on('change', function() {
            var stateID = $(this).val();
            if(stateID) {
                $.ajax({
                    url: '/Student_Course_get_price/'+stateID,
                    type: "GET",
                    dataType: "json",
                    success:function(data) {                      
                        $('#course_Prices').empty();
                        $.each(data, function(key, value) {
                        $('#course_Prices').append('<option value="'+ key +'">'+ value +'</option>');
                        });
                    }
                });
            }else{
                $('#course_Prices').empty();
            }
        });
    });
</script>

my controller

   public function Student_Course_get()
    {
        $course_name = DB::table("courses")->pluck('COURSE_NAME','COURSE_NAME_id');        
        return view('Admin/Student.Student_enrollment',compact('course_name'));
    }

    public function Student_Course_get_price($COURSE_NAME_id)
    {
        $cities = DB::table("courses")
                    ->where("C_id",$COURSE_NAME_id)
                    ->pluck('COURSE_AMOUNT','C_id');
        return json_encode($cities);
    }


via Chebli Mohamed

lundi 20 décembre 2021

Custom Form Request Validation with unique validation not working on update

I'm not sure what I'm doing wrong, but I have a custm form request validation that I'm using in for Create and Update record with unique column validation. It working fine for create creating new record, but not in updating.

Custome Form Request

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ServiceTypeRequest extends FormRequest
{

public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'service_name'        => ['required', Rule::unique('service_type', 'Service')->ignore($this->service_type) ],
        'type'                => ['required', 'string'],
        'view_availability'   => ['required', 'boolean'],

    ];
 }
}

Controller Update

public function update(ServiceTypeRequest $request, ServiceType $serviceType)
{
    $validated = $request->validated();

    $service_type = ServiceType::update([
        'Service'               => $validated['service_name'],
        'type'                  => $validated['type'],
        'view_availability'     => $validated['view_availability'],
    ]);

    return redirect()
            ->route('service_type.index')
            ->with('status', 'Service type updated!');
}

Error Getting when I submit the update form with PUT method It's complain about the $this I have inside the custom form validation for service_name.

Error
Using $this when not in object context
http://localhost:8021/service_type/58 


via Chebli Mohamed

dimanche 19 décembre 2021

Limit the rate of emails sent with Laravel

I am creating a forum with Laravel and as soon as a new private message or a new message in a thread where the user has participated, an email is sent. However, I have a problem: if a user receives 60 private message within an hour then he will receive 60 private message to notify him that he has a new message.

Is it possible to limit the number of emails sent per hour for example ? Is there a attribute to change somewhere ?

Here is an example of the function to find the recipient + send the private message in the MessagesController:

public function newPrivateMessage(Thread $thread, $urlToAccess){
        /* We retrieve the ID of the person connected */
        $userId = Auth::id();//auth()->user()->id
        /* We get the other user from the discussion. */
        $user = $thread->participants->where('user_id', '<>', $userId)->first();
        $userName = User::find($user->user_id);
        /* For the recipient, send an email */
        Mail::to($userName->email)->send(new NewPrivateMessageMail($user,$urlToAccess));
    }

And I've created a NewPrivateMessage inside my http folder with this artisan command php artisan make:mail NewPrivateMessage.

public function __construct($user,$urlToAccess)
{
    $this->data = $user;
    $this->url = $urlToAccess;
}

public function build()
{
    return $this
       ->subject('New private message')
       ->markdown('emails.markdown-newPrivateMessage');
}
```

Cordially


via Chebli Mohamed

samedi 18 décembre 2021

Fetch and display table data in angular and laravel

I'm trying to display data fetched from laravel api in angular table code is :

public function fetchQuestions(Request $request)
{  
  $questions = Questions::where('status',$request->status)->get();
  return response()->json($questions, 200);
}

angular code:

 questions = [];
  ...
  this.http.post(this.baseUrl+'api/auth/question', formData).subscribe(result  => {
  this.questions.push(result);

This does not display any data

i have to use

  this.questions.push(result[0]);
  this.questions.push(result[1]);
  ..
  ..
  this.questions.push(result[n]);

to push all the data. How can i push all array data.

and display data using loop

<ng-container *ngFor="let img of questions; let i=index">


via Chebli Mohamed

vendredi 17 décembre 2021

Access denied for user 'user'@'localhost' Laravel 5.8

I have this project running on Laravel 5.8 and Database on Mysql using XAMPP server.

This is my .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

This is my config/database.php file:

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => false,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

and also created a Database in Xampp named homestead.

this error is showing: SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES) (SQL: select * from userswhereemail = test@gmail.com



via Chebli Mohamed

jeudi 16 décembre 2021

Laravel 5 - Form not appearing on page

So I created a form in a blade file, that looks like this: student.blade.php My Controller looks like this: StudentController.php And my route looks like this: web.php Here is the output I get, missing the form: enter image description here

I am wondering if I am missing something? Or what is going wrong here?



via Chebli Mohamed

Property [image] does not exist on this collection instance. / Laravel - with() Method

I get data with relations from controller but can't use in blade

Controller..

$employees = Post::where('user_id', $user_id)->with('people')->get();

Blade, I use in foreach like ..

$employee->people->image

But it gives error

Property [image] does not exist on this collection instance.

When I dd($employees)

enter image description here



via Chebli Mohamed

Case statement sum time difference return zero with multiple conditions

I am working with laravel eloquent query with this case statement structure (sum time difference between start and end time, if records created within a current week in timelogs table and project is billable in projects table)result return always zero. please help I don't understand.

$billable_data = Project::where(['active' => 1, 'company_id' => session('company_id'), 'is_deleted' => 0])
        ->join('timelogs','timelogs.project_id','=','projects.id')
        ->select(DB::raw('CASE WHEN (billable = 1 AND timelogs.created_at BETWEEN "'.$monday.' 00:00:00" AND "'.$friday.' 23:59:59") THEN SUM(TIMESTAMPDIFF(second, timelogs.start_time, timelogs.end_time))  ELSE 0 END as billable_hours,
            CASE WHEN (billable = 0 AND timelogs.created_at BETWEEN "'.$monday.' 00:00:00" AND "'.$friday.' 23:59:59") THEN SUM(TIMESTAMPDIFF(second, timelogs.start_time, timelogs.end_time))  ELSE 0 END as non_billable_hours'))
        ->first()->toArray();

dd result of $billable_data :

array:3 [▼
"billable_hours" => "0"
"non_billable_hours" => "0"
]

But when I used this raw query within DB::raw everything worked fine (return time sum correctly within a week).

$billable_data = Project::where(['active' => 1, 'company_id' => session('company_id'), 'is_deleted' => 0])
        ->join('timelogs','timelogs.project_id','=','projects.id')
        ->select(DB::raw('(SELECT SUM(TIMESTAMPDIFF(second, start_time, end_time))  FROM timelogs WHERE timelogs.created_at BETWEEN "'.$monday.' 00:00:00" AND "'.$friday.' 23:59:59" AND  projects.billable = 0 GROUP BY projects.id) as non_billable_hours,
            (SELECT SUM(TIMESTAMPDIFF(second, start_time, end_time))  FROM timelogs WHERE timelogs.created_at BETWEEN "'.$monday.' 00:00:00" AND "'.$friday.' 23:59:59" AND  projects.billable = 1 GROUP BY projects.id) as billable_hours'))
        ->first()->toArray();


via Chebli Mohamed

mercredi 15 décembre 2021

laravel and firebird connection

I'm traying to connecto to database with firebird and laravel 5.6. My firebird version is 2.5

I'm using this library:

https://github.com/harrygulliford/laravel-firebird

I can connect with flamebird. My database on the same lan network but in another server.

In library say that use env variables:

#FIREBIRD_HOST=OMEGA
#FIREBIRD_DATABASE=EMPRE001
#FIREBIRD_PORT=3050
#FIREBIRD_USERNAME=Grupo17
#FIREBIRD_PASSWORD=5468
#DB_FIREBIRD_CHARSET=ISO8859_1
#DB_VERSION=2.5

In my database.php file y have this:

'firebird' => [
            'driver'   => 'firebird',
            'host'     => env('FIREBIRD_HOST', 'localhost'),
            'port'     => env('FIREBIRD_PORT', '3050'),
            'database' => env('FIREBIRD_DATABASE', '/path_to/database.fdb'),
            'username' => env('FIREBIRD_USERNAME', 'sysdba'),
            'password' => env('FIREBIRD_PASSWORD', 'masterkey'),
            'charset'  => env('DB_FIREBIRD_CHARSET', 'UTF8'),
            'version'  => env('DB_VERSION', '2.5'), // Supported versions: 2.5, 1.5
            'role'     => null,
        ],

But I can't connect to my database and I don't know why. I'm trying to connect directly with:

'firebird'  => [
            'driver'    => 'firebird',
            'host'      => 'OMEGA',
            'port'      => '3050',
            'database'  => 'EMPRE001',
            'username'  => 'Grupo17',
            'password'  => '5468',
            'charset'   => 'ISO8859_1',
            'version'   => '2.5',
        ],

And I always get this return message:

[2021-12-15 15:57:56] local.ERROR: could not find driver (SQL: select

The model that I'm using to connect to firebird database is this:

protected $connection = 'firebird';

    protected $table = 'CONTRATOS';

    public $dateFormat = 'Y-m-d';

    public $incrementing = false;

    protected $dates = [
        'FECHA'
    ];

    protected $primaryKey = 'ID_CONTRATOS';

But it always returns this message and I don't know how I can continue.

Thanks for reading my question and helping.



via Chebli Mohamed

mardi 14 décembre 2021

Javascript POST via fetch() not being received by Laravel Request?

I have a Javascript POST in the browser sending data to a Laravel (v5.4) backend. Network tab in the browser shows data sent successfully. Laravel logs show no data received. Can't see why...

Client:

fetch('saveloaddata', {
    method: 'POST',
    headers: { 'X-CSRF-TOKEN': $('#IDform > input[name="_token"]').val() },
    body: JSON.stringify(sendData),
    keepalive: true // Ensures data gets sent even after the page closed, see https://web.dev/disallow-synchronous-xhr/#fetch-keepalive
    });

Server: web.php

Route::post('saveloaddata', ['middleware' => 'auth', 'uses' => 'MainController@saveloaddata']);

MyController.php

public function saveloaddata(Request $request)
    {
    Log::info($request->all());

Log output is: local.INFO: array ()

Data being sent is just a short JSON string. On the client in the fetch() block I've also tried without JSON.stringify, so body: sendData, - same result.

POST requests to the same URL using JQuery $.ajax() work fine. I need to use fetch() for this though because this call is to send a small amount of data (~1 - 2 Kb) when the user closes the browser, so I'm following accepted practices (responding to a visibilitychange event in the browser and I would be using navigator.sendBeacon but that uses fetch() and I needed to set keepalive:true so am just using fetch() directly).

The request is clearly getting through Laravel's auth layer as the receiving function is triggered and the logging command runs (as do others in the same code, e.g. logging the user is fine). So, what has happened to the POST data!?

Thanks



via Chebli Mohamed

Upgrade to Laravel 6 - Uncaught Error: Class 'Request' not found in app/Exceptions/Handler.php

I am currently upgrading from L5.8 to L6. I have read over the upgrade docs and made changes where necessary, if any. Once I changed the composer.json version to ^6.0 and ran composer update, I am getting the following stack trace.

This is on macOS running php 7.4

composer update
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Package jakub-onderka/php-console-color is abandoned, you should avoid using it. Use php-parallel-lint/php-console-color instead.
Package jakub-onderka/php-console-highlighter is abandoned, you should avoid using it. Use php-parallel-lint/php-console-highlighter instead.
Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
Package fzaninotto/faker is abandoned, you should avoid using it. No replacement was suggested.
Package phpunit/php-token-stream is abandoned, you should avoid using it. No replacement was suggested.
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
PHP Fatal error:  Uncaught Error: Class 'Request' not found in /Users/ryahn/Public/Sites/alphacoder/rework/app/Exceptions/Handler.php:43
Stack trace:
#0 /Users/ryahn/Public/Sites/alphacoder/rework/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(376): App\Exceptions\Handler->report(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#1 /Users/ryahn/Public/Sites/alphacoder/rework/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(141): Illuminate\Foundation\Console\Kernel->reportException(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#2 /Users/ryahn/Public/Sites/alphacoder/rework/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 {main}
  thrown in /Users/ryahn/Public/Sites/alphacoder/rework/app/Exceptions/Handler.php on line 43

Fatal error: Uncaught Error: Class 'Request' not found in /Users/ryahn/Public/Sites/alphacoder/rework/app/Exceptions/Handler.php:43
Stack trace:
#0 /Users/ryahn/Public/Sites/alphacoder/rework/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(376): App\Exceptions\Handler->report(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#1 /Users/ryahn/Public/Sites/alphacoder/rework/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(141): Illuminate\Foundation\Console\Kernel->reportException(Object(Symfony\Component\Debug\Exception\FatalThrowableError))
#2 /Users/ryahn/Public/Sites/alphacoder/rework/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 {main}
  thrown in /Users/ryahn/Public/Sites/alphacoder/rework/app/Exceptions/Handler.php on line 43
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255

This is the Handler.php file its referencing to

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Request;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        if ($exception instanceof HttpException === false) {
            $request = Request::all();
            Log::info("Error on page: " . Request::url());
            Log::info("Request data: " . htmlspecialchars(json_encode($request)));
        }

        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
}

line 43: $request = Request::all();

I have tried to run php artisan config:cache and php artisan config:clear but still get the following stack trace.

I am most likely focusing on the wrong part of the stack trace. Hopefully its not something obvious I am over looking.



via Chebli Mohamed

Upload file recorded by Record RTC in angular and laravel

I'm using Record RTC using angular and laravel

Angular Code:

sanitize(url: string) {
  return this.domSanitizer.bypassSecurityTrustUrl(url);
}

startTimer() {
  this.interval = setInterval(() => {
    if (this.timeLeft > 0) {
      this.timeLeft--;
      if (this.timeLeft == 0) {
        this.pauseTimer();
        this.stopRecording();
      }
    } else {
      this.timeLeft = 30;
    }
  }, 1000);
}

pauseTimer() {
  clearInterval(this.interval);
}
/**
 * Start recording.
 */
initiateRecording() {
  this.startTimer();
  this.recording = true;
  let mediaConstraints = {
    video: false,
    audio: true,
  };
  navigator.mediaDevices
    .getUserMedia(mediaConstraints)
    .then(this.successCallback.bind(this), this.errorCallback.bind(this));
}
/**
 * Will be called automatically.
 */
successCallback(stream) {
  var options = {
    mimeType: "audio/wav",
    numberOfAudioChannels: 1,
    sampleRate: 16000,
  };
  //Start Actuall Recording
  var StereoAudioRecorder = RecordRTC.StereoAudioRecorder;
  this.record = new StereoAudioRecorder(stream, options);
  this.record.record();
}
/**
 * Stop recording.
 */
stopRecording() {
  this.recording = false;
  this.record.stop(this.processRecording.bind(this));
}
/**
 * processRecording Do what ever you want with blob
 * @param  {any} blob Blog
 */
processRecording(blob) {
  this.url = URL.createObjectURL(blob);

  var fd = new FormData();
  fd.append("audio_data", blob);
  fd.append("audio_url", this.url);
  return this.http.post(this.baseUrl + "api/auth/post-audio", fd).subscribe(
    result => {},
    error => {},
  );
}

/**
 * Process Error.
 */
errorCallback(error) {
  this.error = "Can not play audio in your browser";
}

I have to save recorded file in wav format using laravel on server for that i'm using this code:

 public function uploadAudio(Request $request)
    {  
       $blobInput = $request->file('audio_data');  
       Storage::put('audio/test.wav', file_get_contents($blobInput));
        return response()->json([
            'message' => 'Saved',
           ], 200);
    }

No file is being created in storage folder

Any suggestion to solve this issue, Thanks



via Chebli Mohamed

php - How can I check if the sentence consists of a single word?

For example;

"Real Madrid" -> false
"Barcelona  " -> true

with what functions can I solve this in laravel?



via Chebli Mohamed

I can't start laravel application after update php to 7.4.26 [duplicate]

I was using Laravel 5.4 with PHP 5.6 and the application was working fine, but then I updated the PHP version to 7.4.26 and now the application only shows me a PHP file:

<?php

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;

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

/*
|--------------------------------------------------------------------------
| Check If The Application Is Under Maintenance
|--------------------------------------------------------------------------
|
| If the application is in maintenance / demo mode via the "down" command
| we will load this file so that any pre-rendered content can be shown
| instead of starting the framework, which could cause an exception.
|
*/

if (file_exists(__DIR__.'/../storage/framework/maintenance.php')) {
    require __DIR__.'/../storage/framework/maintenance.php';
}

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/

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

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

$kernel = $app->make(Kernel::class);

$response = $kernel->handle(
$request = Request::capture()
)->send();

$kernel->terminate($request, $response);

I have tried some settings from the .htaccess and composer.json file but have not been successful. I have also updated with composer update but it has not worked.

In addition, I created a clean Laravel application to know if at least the page that Laravel brings by default would appear, but a PHP file always appears (In other attempts to configure it, it has shown me the content of the server.php file).



via Chebli Mohamed

How to write correct way of sql query in php laravel

I want to fetch all data from this table for that i am using query :

      $emp = Employee::where('user_id', '=', $user->id)->first();

    $holidays = Holiday::orderBy('holidays.id', 'desc')->take(5)->where('holidays.id', '=', $emp->id)->get();

It is not giving me any result. I am new to php can anyone help me out yrr?

Holiday Table



via Chebli Mohamed

lundi 13 décembre 2021

When i run the site in subdomain, i need to declare that subdomain in the .env file

Install is ok. But looks like you are running the site under subdomain. When you run the site in subdomain, you need to declare that subdomain in the .env file

IGNORE_SUBDOMAINS="www,menu"

iam using Larvel and my .env looks like this

APP_LOG_LEVEL=debug
APP_URL=https://menu.bethello.com/
APP_LOCALE=en
IGNORE_SUBDOMAINS=menu.bethello.com
TIME_ZONE="America/New_York"
CASHIER_CURRENCY=USD


via Chebli Mohamed

yarn don't build public folder correctly

Recently I created a new Branch and when I was installing dependencies and building the project this error occurs:
enter image description here
My public folder was not builded correctly(I'm using yarn watch). Soo what I should do? I don't touch in my public folder and my webpack it wasn't too.



via Chebli Mohamed

samedi 11 décembre 2021

Cant get proper data in Controller Laravel belongsToMany Relation - Laravel / Eloquent

A user(employer) have many posts and many user(employee) can apply these posts . Point is employer should get which users applied for each its posts.

I tried $employees = Post::find(//anyNumber//)->people; it gives proper applicants infos but it should be dynamic for each employer user .

Tables..

applies   ->  | users_id(employee) | posts_id |
posts     ->  | id                 | user_id(employer)  | (other posts cols ... )
user_info ->  | id                 | (name col  etc... for employee)

Post Model..

public function people()
{
   return $this->belongsToMany(Info::class , 'applies', 'user_id' , 'posts_id');
}

Controller..

public function index()
{
    $user_id = Auth::id();
    $myPosts = Post::where('user_id',$user_id)->get();
    $employees = Post::find(//anyNumber//)->people; // this line

    dd($employees);
}


via Chebli Mohamed

vendredi 10 décembre 2021

Laravel Storage File not downloading (File not found)

in my laravel project i have uploads folder from where i am trying to download file.

Folder Hierarchy:

-Project
--Public
---Storage (created using php artisan storage:link)
----uploads
-----file.jpg ( i am trying to download)

Controller:

public function getdata(Request $request)
    {
        return Storage::download('/storage/uploads'.$image_name);
    //image name is file.jpg
      }

Error:

File not found at path: storage/uploads["file.jpg"]


via Chebli Mohamed

Laravel SFTP Connection Using Passphrase

       This is the stand way that I have been using to place a file in SFTP 

Storage::disk()->put($fileName, file_get_contents($storagePath . $fileName));

But I am facing a situation where for connection first I need pass the key-phrase and post that only SFTP will askfor user_id and password,

How can Is set this up for Jobs in Laravel, Using Laravel 5.1 (due to some issues cant upgrade but that's not the concern as of now)

My Configuration in Filesystem

'new_sftp' => [
        'driver'     => 'sftp',
        'host'       => 'homestead',
        'port'       => 22,
        'username'   => 'myuser',
        'password'   => 'mypass',
        'root'       => /myroot/folder,
        'privateKey' => '/home/myroot/myfile.pem',
        'password'   => 'mypassprase',
        'timeout'    => '300',
        'visibility' => 'public',
        'permPublic' => 0766,
    ],


via Chebli Mohamed

jeudi 9 décembre 2021

Route is working when referred but when I go to that provided link it will not find the controller function in laravel

I have added a custom function to save pictures and added the route as well and when I reference the route it does work but when visiting it gives error that the function can not be found with reflectionexception error ReflectionException

Function () does not exist

Controller ----------------------

/**
*    show the form for uploading profile picture 
*    
*   @return \Illuminate\Http\Response 
*/
public function changePicture()
{

    return view('usersinformation.profilepicture');
}

route web.php ---------------------------

Route::get('usersinformation/changePicture',[usersinformationController::class, 'changePicture'])->name('usersinformation.changePicture');

Route::post('usersinformation/savePicture', 'usersinformationController@savePicture');



via Chebli Mohamed

Route issue in Laravel with several controllers and different route with same name

I have added below routes in web.php but it's not working.

Route::post('show', [
'as' => 'usersinformation.show',
'uses' => 'usersinformationController@show'


 ]);



 Route::post('store', [
    'as' => 'usersinformation.store',
    'uses' => 'usersinformationController@store'
  ]);



 Route::get('store',[usersController::class, 'store'])->name('usersinformation.store');
    Route::post('/store', 'usersController@store');
    Route::post('store',[usersController::class, 'store'])->name('users.store');
    Route::get('/index', 'usersController@index');

my controller is as below and I am using Ajax to send data but the error I receive is Method not allowed exception.

public function store(Request $request)
{
    //
    $fname = $request -> fname;
    $lname = $request -> lname;
    $pnumber = $request -> pnumber; 

    
}

Ajax Code ----------------

data = {
    _token: $('input#usersinformation-token').val(),
    'fname': $('input#first_name').val(), 
    'lname': $('input#last_name').val(),
    'pnumber': $('input#phonenumber').val()

};
$.post(url, data, function(data, status){
    alert('working' + data + "    " + status );
    $('div#load-content').html(data);
} );


via Chebli Mohamed

mercredi 8 décembre 2021

Primary Key is different from the default id that laravel searches for

I have added a custom primary key within the table and now the Laravel is not even finding the result at all. giving error that the page could not be found.

NotFoundHttpException

No query results for model [App\usersinformation].

Controller --------------------

public function show(usersinformation $usersinformation)
{
    //
  //  $users =  $user = usersinformation::where('user-id','=',$usersinformation) -> first();
    
        return view('usersinformation.show');

}

Model -------------------

class usersinformation extends Model
{
    //

    public $table = "usersinformation";
    public $incrementing = false;
    
    protected $fillable = [

        'fname','lname', 'user-picture', 'phone-number', 'user-id', 'place-id'

    ];
    protected $primaryKey = 'user-info-id';

    public function users(){
        $this -> belongsTo('App\users');
    }

route ---- web.php

Route::post('/show','App\Http\Controllers\usersinformationController@show');

Still facing the same issue, if I comment the primary key, it will give error that the id field is not found within the table when I add the custom primary key in the model, it will give error page not found.



via Chebli Mohamed

How to join Multiple databases from different hosts in Laravel

Is there any way to use join query with Multiple databases from different servers?

my database.php is

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'db1'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            ...
        ],

        'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST_2', '192.233.****.*'),
            'port' => env('DB_PORT_2', '3306'),
            'database' => env('DB_DATABASE_2', 'db2'),
            'username' => env('DB_USERNAME_2', 'root'),
            'password' => env('DB_PASSWORD_2', ''),
         ...
        ]

and i need to implement it in join query.

My controller function is

public function function1(){
$db1 = DB::connection('mysql2');
$result = TABLE1::join($db1 . '.' . 'table2', 'table2.id','=','table1.table2_id');

return Datatables::of($result);

}


via Chebli Mohamed

mardi 7 décembre 2021

How to set the primary key itself as a foreign key in laravel?

This sounds nooby but I wanted to know if I can make the primary key work as a foreign key in Laravel, and I'am new to Laravel.

So, I have two migrations 'User' and 'Student' as Shown below: User :

 Schema::create('users', function (Blueprint $table) {
            $table->string('uniqueId', 30)->primary();
            $table->text('password');
            $table->string('userType');
            $table->timestamps();
        });

and Student :

Schema::create('students', function (Blueprint $table) {
            $table->string('uniqueId', 30)->primary();
            $table->text('name');
            $table->text('fName');
            $table->text('mName');
            $table->text('addr');
            $table->string('image');
            $table->integer('class');
            $table->integer('roll');
            $table->string('year');
            $table->timestamps();
        });

So, all I wanted was that the primary key in Student (uniqueId) also work as a foreign key that references the 'uniqueId' column from the User table.

Thanks in advance.



via Chebli Mohamed

Laravel 5.2 New schedule entries not running on production

I have three command AAA, BBB and CCC.

CCC is the latest command that I have entered in this schedule, strange scenario is that AAA and BBB are still running as they were, but not CCC.

This laravel schedular runs all okay on local, but on production it is not showing any effect for CCC. Even doing php artisan ccc on production terminal works, but scheduler is showing no effect, no error for CCC.

Any idea what's causing it ? Is there any sort of cache or similar thing that is causing it ?

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\AAA::class,
        \App\Console\Commands\BBB::class,
        \App\Console\Commands\CCC::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('aaa')
                 ->hourly();

        $schedule->command('bbb')
                 ->everyTenMinutes();

        $schedule->command('ccc')
                ->everyTenMinutes();

    }

}


via Chebli Mohamed

lundi 6 décembre 2021

Laravel command file output not updating

I updating Laravel command file.

File code updated on server but when I run command no changes in output.

how to update Laravel command file for new changes?



via Chebli Mohamed

Pass a laravel variable into a jquery array

I am trying to pass a variable into a jquery autocomplete script check this url (https://jsfiddle.net/duoc5bbh/1/) I found.

Laravel

@foreach($data as $value)
   
   
@endforeach

Jquery

$(function() {
  let users = [{
      "email": "marie@gmail.com",
      "name": "marie"
      }, 
      {
       "email": "miss@gmail.com",
       "name": "miss"
     }];
});

what I did

$(function() {
  let users = [{
      "email": ,
      "name": 
      }];
});

I am new in using laravel with jquery I need your help in this Thanks.



via Chebli Mohamed

Laravel route group and middlewares

i am working on a laravel project with users who can have status verified (email verified).

on the other hand, users can have a subscription which is verified by a "subscriptions" middleware.

So I have several groups of routes including 2 of which the only difference is the presence of subscription or not

group 1:

Route::group(['middleware' => ["auth:sanctum", "verified"]], function () {}

group 2

Route::group(['middleware' => ["auth:sanctum", "verified", "subscriptions"]], function () {}

my question is about the order laravel uses for routes in these groups. for example if the user satisfies all the middleware of the first group, does laravel test the middleware of the second? Does a user verified have a chance to enter the second group of routes with subscription?

conversely, if the user does not have a subscription, he will not pass the subscription middleware. but I have the impression that the user is redirected by the subscription middleware which fails while laravel could find the right route in the group without this middleware (group 1)

what I would like is that it just tests for the presence of a subscription and that if it does not find one it looks for the route in group1.

Does the order of the groups in the code have an impact on the processing?

thanks.



via Chebli Mohamed

dimanche 5 décembre 2021

Executing python file within another python file using Laravel

I'm currently calling the main python file in larval function, and inside that main python file I'm calling another 2 files ( PowerShell and sub python file) the problem is when the Laravel function is triggered it only call the main python file, however when I call the main python file using terminal all the files are executed like below:

Laravel function:

public function initialize(Request $request)
{
    $store_name = $request->get('store_name', 1);
    if (empty($store_name)) {
        return 'Missing store name';
    } else {
        $processes = File::get("/root/flask/android_api/processes.txt");
            File::put('/root/flask/android_api/url.txt', $store_name );
            $process = new Process(['python3.6', '/root/flask/android_api/buildAPK.py']);
            $process->run();
            if (!$process->isSuccessful()) {
                    throw new ProcessFailedException($process);
            } else {
                    return 'Starting the processes to build';
            }   
    } 
}

and within the main python file I have:

try:
    p = subprocess.Popen(["/usr/bin/pwsh", 
            "/root/flask/android_api/set_apk_builder.ps1", '-ExecutionPolicy',
                        'Unrestricted',
                        './buildxml.ps1'], 
            stdout=sys.stdout)
    p.communicate()

except:
    file = open ("/root/flask/android_api/log.txt", "w")
    file.write ("fail")
    file.close()


import slack
call(["python", "/root/flask/flask.py"])
os.system('python3.7 /root/flask/flask.py')


via Chebli Mohamed

samedi 4 décembre 2021

How to do user tracking for rollbar on laravel?

I did the laravel integration by following the document.

I have looked at the user tracking in this document, but it is not very descriptive. Can anyone help us?



via Chebli Mohamed

Catch an error while importing huge CSV in queue using laravel excel

I am using ShouldQueue method to have the large CSV into Queue but the errors of validations I am not able to catch them!

public function registerEvents(): array
{
    return [
        ImportFailed::class => function(ImportFailed $event) {
            dd($event); // This I will write into the FILE or send EMAIL but the job runs successfully but validation errors keep empty.
            $this->importedBy->notify(new ImportHasFailedNotification);
        },
    ];
}

My code looks like below

public function registerEvents(): array
    {
        return [
            ImportFailed::class => function(ImportFailed $event) {
            $filename = public_path('tmp').'/validation_error.txt';
            $myfile = fopen($filename, "w");
            fwrite($myfile, "domo");
            fclose($myfile);
            },
        ];
    }

I am in hope that if there is any error validation_error.txt file will have "Demo" inside it.

Also, I have crossed verify by removing ShouldQueue it gives me proper errors for email already exists a kind of.

Please help if you have any ideas! Thanks!



via Chebli Mohamed

vendredi 3 décembre 2021

How to do newline email body in laravel?

I want to send some information on mail body. When I try its works but Google shows trimmed content(...).

My code is like this:

$name = $e->name;
$code=$request->code;
 $mes2="loretmtext,";
        $mes3="loremtext";
        $mes4="Code:".$code;
        $mes5="e:".$name;
$mes6="text"


//and i send mail function
$msg= $mes2."<br />".$mes3."<br />".$mes4."<br />".$mes5."<br />".$mes6."<br />";

How can i solve?



via Chebli Mohamed

custom sound doesn't work using fcm in flutter

I am working with laravel as a server and flutter as a frontend, I am using fcm, I get the notifications but with the default android sound and I cannot make them custom. in flutter I create a file in main / res / raw / notification.wav and This is my code in laravel

public function toFcm($notifiable)
    {
        $message = new FcmMessage();
        $notification = [
            'title'        => "Nueva Orden #".$this->order->id." para ".$this->order->restaurant->name,
            'body'         => $this->order->user->name,
            'icon'         => $this->order->foodOrders[0]->food->restaurant->getFirstMediaUrl('image', 'thumb'),
            'sound'        => "notification",
            'click_action' => "FLUTTER_NOTIFICATION_CLICK",
            'id' => '1',
            'status' => 'done',
        ];
        $message->content($notification)->data($notification)->priority(FcmMessage::PRIORITY_HIGH);

        return $message;
    }


via Chebli Mohamed

Laravel constrain eager loading - apply limit if relationship column != 1

Am building a system that works similar to the popular flashcard software called "Anki" and am trying to eager load some answers that belong to a user study, but with some modifications.

Model relationships

  • User has many Study
  • Study has many Answer

Here is the code snippet. (Take a look at the second section below)

$user_query = User::with([
    'studies.answers' => function ( $query_answer ) use ( $args ) {
        $query_answer
            ->where( 'grade', '=', 'hold' )
            ->groupBy( 'card_id' )
            ->orderByDesc( 'id' );

            if ( $args['no_date_limit'] ) {
                $query_answer = $query_answer->where( 'next_due_at', '>', $args['start_date'] );
            } else {
                $query_answer = $query_answer->whereBetween( 'next_due_at', [ $args['start_date'], $args['end_date'] ] );
            }

            if ( ! empty( $args['card_ids_in'] ) ) {
                $query_answer = $query_answer->whereIn( 'card_id', $args['card_ids_in'] );
            }
            if ( ! empty( $args['card_ids_not_in'] ) ) {
                $query_answer = $query_answer->whereNotIn( 'card_id', $args['card_ids_not_in'] );
            }

Below, I want to apply the limit if study.answer_all_on_hold ($study_all_on_hold) != 1 And also read the $no_on_hold value from study.no_on_hold

            // Here, I want to apply the limit ($study_all_on_hold ) if study.answer_all_on_hold != 1
            if ( ! $study_all_on_hold ) {
                // And also read the $no_on_hold value from study.no_on_hold
                $query_answer = $query_answer->limit( $no_on_hold );
            }
        },
    ])
    ->where( 'ID', '=', $user_id );

As you can see am trying to apply the limit from the column value of the study. Is this currently possible ?



via Chebli Mohamed

jeudi 2 décembre 2021

How can I Update my app to theme app extensions in shopify

I want to update my app to a theme app extension and I am using backend laravel. For integrating Laravel with Shopify I am using oseintow/laravel-shopify addon in Laravel.



via Chebli Mohamed

how to compare number (0,1,2, -1, -1.5) and text values ​in php

I have a form to fill in the examination data. The form is filled in by a doctor, the data to be filled can also be numbers or text and I store this type of data in the table ex: 0 for numeric data types and 1 for text. when the form is saved, I will compare the data results with the specified standard value, so if the inspection result is greater than the standard value, it will produce a critical value or vice versa. for now I'm comparing the values ​​using the if else condition. is there a more efficient way than using the if else condition because the method I use currently still has bugs, ex: if the value is minus then the result that comes out doesn't match or if the text contains characters (+) or (-) then error result.

if( ($data_type== 0) || is_numeric($standart_value->MIN_VALUE) && is_numeric($standart_value->MAX_VALUE) ){

  if( ( floatval($v['result']) >= floatval($standart_value->MIN_VALUE) ) && ( floatval($v['result']) <= floatval($standart_value->MAX_VALUE) ) ){

    $is_normal = 1;

   }else{

    $is_normal = 0;

  }
  
}elseif( ($data_type== 1) || !is_numeric($standart_value->MIN_VALUE) && !is_numeric($standart_value->MAX_VALUE) ){

  $min = strtoupper($standart_value->MIN_VALUE);
  $max = strtoupper($standart_value->MAX_VALUE);
  $value = strtoupper($v['result']);

  if( ( preg_match_all("|$min|i", $value ) ) || ( preg_match_all("|$max|i", $value ) ) ){
                        
       $is_normal = 1;
         
  }else{
                        
       $is_normal = 0;
      
   }

}


via Chebli Mohamed

How can I skill the current php artisan serve session before start a new one?

I often find myself open uo so many port when running php artisan serve

Laravel development server started: <http://127.0.0.1:8000>
[Thu Dec  2 19:56:23 2021] Failed to listen on 127.0.0.1:8000 (reason: Address already in use)
Laravel development server started: <http://127.0.0.1:8001>
[Thu Dec  2 19:56:23 2021] Failed to listen on 127.0.0.1:8001 (reason: Address already in use)
Laravel development server started: <http://127.0.0.1:8002>
[Thu Dec  2 19:56:23 2021] Failed to listen on 127.0.0.1:8002 (reason: Address already in use)
Laravel development server started: <http://127.0.0.1:8003>

Is there away to kill http://127.0.0.1:8000 before starting a new one ?

so my application will be at http://127.0.0.1:8000...

Any hint for on how to do that ?



via Chebli Mohamed

Laravel Timezone doesn't convert to the correct timezone in Laravel

I am trying to build a simple function where I want to fetch a DateTime from database that is stored in UTC format and display it to the user in their local timezone. I found heaps of solutions that works, but the timezone is not correct.

 $time = Carbon::createFromFormat('Y-m-d H:i:s', $user->created_at)->settings(['timezone' => 'Australia/Sydney']);

So this code takes in $user->created_at , "created_at": "2021-12-02T21:18:31.000000Z", which in UTC format created on 21:18, which is 8:18 am in Sydney, yet, when I run the code i get a wrong time zone, "2021-12-02T10:27:29.000000Z", which is 10:27 am.

I am not sure whats happening. Any Help will be greatly appreciated



via Chebli Mohamed

The image that i uploaded in my post is diplaying broken image i dont know why it is not working i crate public/storage /posts folder using the cmds

i am using laravel 5.8 and the image that i uploaded is displaying in broken format the is here

 public function store(createpostrequest $request)
    {
        $image=$request->image->store('posts');
       $post = post::create([
            'title'=>$request->title,
            'description'=>$request->description,
            'content'=>$request->content,
            'image'=>$image,
            'published_at'=>$request->published_at,
            'catagory_id'=>$request->catagory
        ]);

       if ($request->tags) {
           $post->tags()->attach($request->tags);
       }

        //flashing the message

        session()->flash('success','Post created successfully');
        return redirect(route('posts.index'));
    }   

and in the post index page

                    ```
image)}}"> ``` but the image is that displaying in the page is broken when i remove the asset() it displays the image that is store in public/storage/post .........but i cant open this folder ........

via Chebli Mohamed

Laravel project homepage loads perfectly. But other pages not

I have an issue with the inner pages. The homepage of the project works well. But when I click on the menu items which are dynamically generated by product categories, it prints ^ "ja" on every page.

The same project files are also stored in a dem folder under the parent directory. Homepage and other inner pages in this demo directory work well and every page loads completely. enter image description here

The output from the parent directory is as shown.

Tried editing the file in the following directory shows some changes.

public_html/vendor/symfony/var-dumper/Dumper/HtmlDumper.php

Does anyone who faced the same situation ever, help me to solve the issue.



via Chebli Mohamed

Override laravel Mailgun Transport for support multiple domain (Laravel 5.2)

We are sending email from our application by mailgun. We are using laravel 5.2.

But we have multiple mailgun domain created to sending email.

'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'business_domain' => env('MAILGUN_DOMAIN_FOR_BUSINESS'),
    'secret' => env('MAILGUN_SECRET')
],

Now we wants to send email like this.

  1. Mail::send() this methods sending email by default domain.

  2. But when we wants to create a different facade like MailByBusiness::send() with send email by business domain.

for archiving this functionality, how to override mailgun transport class and make a facade ?



via Chebli Mohamed

mercredi 1 décembre 2021

Laravel 5.x error install "Class ExpectedQPair.php doesn't comply with psr-4 autoloading standard "

I took a project that is in laravel 5.6, and did the usual... clone, composer-update, and I got this error message.

image error enter image description here

Class Egulias\EmailValidator\Exception\ExpectedQPair located in C:/laragon/www/spa-blog/vendor/egulias/email-validator/EmailValidator\Exception\ExpectingQPair.php does not comply with psr-4 autoloading standard. Skipping.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover


  [ErrorException]
  Undefined index: name


Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I created the .env and generated the key, but it didn't allow me to run composer install or update either. I did the typical clean cache and dump-autoload, but I still can't move forward with the project.

What can be happening, what do you recommend me to do to solve this error?

Thank you in advance



via Chebli Mohamed

csrf-token mismatch error in laravel on server

I'm using this code to submit data through ajax in laravel

$('#submit').submit(function (e) {
    e.preventDefault();

    let formData = new FormData(this);

    $.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        xhr: function() {
          var xhr = new window.XMLHttpRequest();
      
          xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
              var percentComplete = evt.loaded / evt.total;
              percentComplete = parseInt(percentComplete * 100);
             
      
              if (percentComplete === 100) {
               
              }
      
            }
          }, false);
      
          return xhr;
        },
        url: $(this).attr('action'),
        type: "POST",
        data:  formData,
        dataType:'JSON',
        contentType:false,
        cache: false,
        processData: false,

but getting csrf token mismatch when i upload my code on live server.

enter image description here

enter image description here

Any solution is highly appreciated Thanks



via Chebli Mohamed