lundi 31 janvier 2022

Laravel 5.1 - Some pages are not found on production serveur - "Page you are looking for could not be found"

I have a problem with some "routes" in my old Laravel 5.1.46 project.

When I try to access to some routes, like admin/exercices/creer or admin/exercices/1928, I have this: "Sorry, the page you are looking for could not be found.". I can access to thoses pages when I work on the test or local serveur. But not on the production serveur. Other routes like admin/missions/creer are working properly.

I tried php artisan route:list to compare the routes on each serveur: it's the same everywhere. I also tried php artisan route:cache and php artisan route:clear. Nothing changed.

I can remember we changed the routes path (for example: "admin/modules/creer" became "admin/exercices/creer"). I think we did it manually, directly in the routes.php file. But it waas a long time ago and since then, it already worked properly. So I don't think it comes from that, but Idk.

I'm also not good at sysadmin, so maybe it's more about the config of the server than code and laravel... In this case, any idea here does it come from? I have no clue, and I might need help.

Thanks a lot for reading! And let me know if you have even a tiny idea!



via Chebli Mohamed

Opening one post instead of multiple posts

I've written a blog that's supposed to fetch data from the database. But when I click on the read more link, it keeps opening all the posts that are in the db instead of selecting only one specific post that I've clicked. Can some kindly assist me with this issue?

View

@foreach($data as $aboutus)
        <div class="col-lg">
            <img src="" class="img-fluid shadow-lg" style="">
            <p class="mt-3 text-success fw-bold fs-5 text-lg-start"></p>
            <p class="fs-6 text-lg-start"> </p>
            <p class="text-success fw-bold text-lg-start"><a href="" class="text-success text-decoration-none"></a></p>
            <!--<img src="images/hr-2.png" class="img-fluid float-start my-2">-->
        </div>
    @endforeach

Controller

public function show($id)
{
    //
    $data = AboutUs::find($id)->get();
    return view('about.show')->with(compact('data'));
    
}

Route

Route::get('/about.show/{id:title}','App\Http\Controllers\WelcomeController@show')->name('about.show');


via Chebli Mohamed

vendredi 28 janvier 2022

Found an 'Invalid payload' Error when decrypting using Laravel decryptSting function

When I am decrypting this value I am getting below error (This data is received from another service. So we have to decrypt it and store in our db)

$data - 'UeJOR76YHezWdjl6hxVV7Q=='

APP_KEY - [32 character key]

In config/app.php

'cipher' => 'AES-256-CBC'

Laravel version - Laravel Framework 5.6.39

In Encrypter.php line 191:

  [Illuminate\Contracts\Encryption\DecryptException]
  The payload is invalid.


Exception trace:
 () at /media/sf_vbshared/www/viaduct/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:191
 Illuminate\Encryption\Encrypter->getJsonPayload() at /media/sf_vbshared/www/viaduct/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:134
 Illuminate\Encryption\Encrypter->decrypt() at /media/sf_vbshared/www/viaduct/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:223
 Illuminate\Support\Facades\Facade::__callStatic() at /media/sf_vbshared/www/viaduct/app/Console/Commands/CleanPlayers.php:276
 App\Console\Commands\CleanPlayers->decrypt() at /media/sf_vbshared/www/viaduct/app/Console/Commands/CleanPlayers.php:81
 App\Console\Commands\CleanPlayers->cleanPlayer() at /media/sf_vbshared/www/viaduct/app/Console/Commands/CleanPlayers.php:65
 App\Console\Commands\CleanPlayers->handle() at n/a:n/a

Below is the laravel code I used to decrypt


#decrypted = Crypt::decryptString( $data );

I know laravel Crypt uses AES256 encryption algorithm. Is there any wrong with data here ? is this data is not compatible to AES256 algo?



via Chebli Mohamed

Is there a way to get Collection of a model and get only objects whose relationship rows exists?

I have three models User, Post and Comment

User
  -id
Post
  -user_id
Comment
  -post_id

My table has issues, for example, some posts are not there or some user rows are not there.

How can I be able to get only comments that have a post_id which exists and it also has a user_id of the user which exists using a scope most preferably global scope?



via Chebli Mohamed

jeudi 27 janvier 2022

Image upload 500 error Laravel on nginx server

I have nginx, php7.2-fpm installed on my server. When I try to upload image, I get a 500 error.

  • I don't see any errors in var/log/nginx/error.log.
  • There is no error in the log in Laravel storage.
  • My /storage and /public paths have 777 permissions.
  • I have "error_reporting = E_ALL" and "display_errors = On" in my php.ini file

When I run the project on Apache server in local environment, I don't get any error.



via Chebli Mohamed

whenever i logged off from my project and login again , first it will say "419: Page Expired" and after page refreshing i can login

.env

    DB_CONNECTION=mysql
    DB_HOST=host.docker.internal
    DB_PORT=3307

Whenever i switch from one module to another , sometimes it expires the page and sometimes it works totally fine .



via Chebli Mohamed

mercredi 26 janvier 2022

Get the value from 2 table on laravel

Schema::create('discounts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->dateTime('from', $precision =0);
            $table->dateTime('to', $precision =0);
            $table->enum('status', [0, 1, 2])->default(0)->comment('0:active 1:expired 2:scheduled');
            $table->timestamps();
            $table->softDeletes();
        });

Schema::create('discount_product', function (Blueprint $table) {
            $table->id();
            $table->string('code');
            $table->unsignedBigInteger('discount_id');
            $table->unsignedBigInteger('product_id');
            $table->foreign('discount_id')->references('id')->on('discounts')->onDelete('cascade');
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->float('rate');
            $table->timestamps();
            $table->softDeletes();
        });


Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->float('price');
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('brand_id');
            $table->string('image')->nullable();
            $table->text('description')->nullable();
            $table->integer('quantity');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade');
            $table->timestamps();
            $table->softDeletes();
        });

public function discountProducts()
    {
        return $this->hasMany(DiscountProduct::class);
    }


 public function discount()
    {
        return $this->belongsTo(Discount::class);
    }

    /**
     * Get product of discount
     */
    public function product()
    {
        return $this->hasMany(Product::class);
    }

I have 3 tables like this : discount, discount_product, product, in my detailProduct.blade.php, I want to get the product have the discount, but I don't know to do that. Can someone help me ? Thanks you very much

This is my : view detail function : I get the discount_products

 public function show($id)
    {
        $discount = $this->discountRepository->getDiscountById($id);
        $discount_products = $this->discountRepository->getDiscontProductOnDiscount($id);

        return view('user.discounts.detailDiscount', 
                   ['discount_products' => $discount_products, 'discount' => $discount]);
    }


via Chebli Mohamed

Composer update not run

I have a problem when I run composer update for any project in laravel. It give me this error: Your requirements could not be resolved to an installable set of packages.

Problem 1
    - Root composer.json requires php ^7.1.3 but your php version (8.1.0) does not satisfy that requirement.
  Problem 2
    - laravel/framework[v5.7.0, ..., 5.7.x-dev] require php ^7.1.3 -> your php version (8.1.0) does not satisfy that requirement.
    - Root composer.json requires laravel/framework 5.7.* -> satisfiable by laravel/framework[v5.7.0, ..., 5.7.x-dev].

I tried to change it from composer.json but still doesn't works also I tried to composer install --ignore-platform-reqs gives me other error which is :

Generating optimized autoload files
Class Egulias\EmailValidator\Exception\ExpectedQPair located in C:/laravel/job-portal-website-in-laravel-master/vendor/egulias/email-validator/EmailValidator\Exception\ExpectingQPair.php does not comply with psr-4 autoloading standard. Skipping.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
Deprecation Notice: Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php:1204
Deprecation Notice: Return type of Illuminate\Container\Container::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php:1215
Deprecation Notice: Return type of Illuminate\Container\Container::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php:1227
Deprecation Notice: Return type of Illuminate\Container\Container::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php:1240
> @php artisan package:discover

Deprecated: Return type of Illuminate\Container\Container::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 1204

Deprecated: Return type of Illuminate\Container\Container::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 1215

Deprecated: Return type of Illuminate\Container\Container::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 1227

Deprecated: Return type of Illuminate\Container\Container::offsetUnset($key) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 1240

Deprecated: Method ReflectionParameter::getClass() is deprecated in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 833

Deprecated: Method ReflectionParameter::getClass() is deprecated in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 907

Deprecated: Method ReflectionParameter::getClass() is deprecated in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 833

Deprecated: Method ReflectionParameter::getClass() is deprecated in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 907

Deprecated: Return type of Illuminate\Config\Repository::offsetExists($key) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Config\Repository.php on line 141

Deprecated: Return type of Illuminate\Config\Repository::offsetGet($key) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in C:\laravel\job-portal-website-in-laravel-master\vendor\laravel\framework\src\Illuminate\Config\Repository.php on line 152

Deprecated: Return type of Illuminate\Config\Repository::offsetSet($key, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute shou......ect.

so do you have idea how should I mage that error? can someone help???



via Chebli Mohamed

mardi 25 janvier 2022

Migrate lucadegasperi to laravel passport [closed]

I am currently upgrading a Laravel project from 5.1 onwards.

The problem here is that the lucadegasperi package does final migrations that I need to roll back before running the migration command after installing passport (because they share some table names, like oauth_clients).

I found a solution that is to manually create a migration that reverses the lucadegasperi migrations to run before the laravel passport migrations, but I don't think it's the most effective solution.

Any alternative?

Thanks!



via Chebli Mohamed

Display a page without log in laravel

I have a page that is supposed to be visible regardless of user log in. I've tried using $this->middleware('auth')->except('getStats') but it didn't work. I tried to pass url in Handler.php where it redirects unauthenticated users to login page, but it didn't work. Any suggestion would be appreciated as I've tried a lot of things but couldn't make it work.

Handler.php :

protected function unauthenticated($request, AuthenticationException $exception)  {
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }
    return redirect()->guest(route('login'));
}

PlanningController.php (where I passed the except):

public function __construct() {
    parent::__construct();
    $this->middleware('auth')->except('getStats');
}

RedirectIfAuthenticated.php

public function handle(Request $request, Closure $next, $guard = null)
    {
      // Teste si l'utilisateur est ok
      if (Auth::guard($guard)->check()) {
        // Redirige vers l'accueil
        return redirect('/');
      }
      return $next($request);
    }


via Chebli Mohamed

Problem having a route in different modes . LARAVEL

In this route:

Route::post('/doctor/{doctor}/service/bulk', 'ServiceController@bulkCreate');

I will send this request:

[
 {
   "service_id": 1,
   "time_taken": "01:30:00"
 }
]

And there is no problem in localhost and this response will be returned:

{
    "success": true
}

but in production state, I will receive this response:

{
    "success": false,
    "error": {
        "code": 0,
        "message": "The request is invalid.",
        "trace": [
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Validation/ValidatesWhenResolvedTrait.php",
                "line": 26,
                "function": "failedValidation",
                "class": "App\\Http\\Requests\\BaseRequest",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php",
                "line": 30,
                "function": "validateResolved",
                "class": "Illuminate\\Foundation\\Http\\FormRequest",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php",
                "line": 1084,
                "function": "Illuminate\\Foundation\\Providers\\{closure}",
                "class": "Illuminate\\Foundation\\Providers\\FormRequestServiceProvider",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php",
                "line": 1048,
                "function": "fireCallbackArray",
                "class": "Illuminate\\Container\\Container",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php",
                "line": 1033,
                "function": "fireAfterResolvingCallbacks",
                "class": "Illuminate\\Container\\Container",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php",
                "line": 687,
                "function": "fireResolvingCallbacks",
                "class": "Illuminate\\Container\\Container",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php",
                "line": 615,
                "function": "resolve",
                "class": "Illuminate\\Container\\Container",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Application.php",
                "line": 767,
                "function": "make",
                "class": "Illuminate\\Container\\Container",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php",
                "line": 79,
                "function": "make",
                "class": "Illuminate\\Foundation\\Application",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php",
                "line": 46,
                "function": "transformDependency",
                "class": "Illuminate\\Routing\\ControllerDispatcher",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/RouteDependencyResolverTrait.php",
                "line": 27,
                "function": "resolveMethodDependencies",
                "class": "Illuminate\\Routing\\ControllerDispatcher",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php",
                "line": 41,
                "function": "resolveClassMethodDependencies",
                "class": "Illuminate\\Routing\\ControllerDispatcher",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Route.php",
                "line": 219,
                "function": "dispatch",
                "class": "Illuminate\\Routing\\ControllerDispatcher",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Route.php",
                "line": 176,
                "function": "runController",
                "class": "Illuminate\\Routing\\Route",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
                "line": 680,
                "function": "run",
                "class": "Illuminate\\Routing\\Route",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 30,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Router",
                "type": "->"
            },
            {
                "file": "/var/www/html/app/Http/Middleware/ApiRole.php",
                "line": 30,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "App\\Http\\Middleware\\ApiRole",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php",
                "line": 41,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "Illuminate\\Routing\\Middleware\\SubstituteBindings",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php",
                "line": 43,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "Illuminate\\Auth\\Middleware\\Authenticate",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php",
                "line": 58,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "Illuminate\\Routing\\Middleware\\ThrottleRequests",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 104,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
                "line": 682,
                "function": "then",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
                "line": 657,
                "function": "runRouteWithinStack",
                "class": "Illuminate\\Routing\\Router",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
                "line": 623,
                "function": "runRoute",
                "class": "Illuminate\\Routing\\Router",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
                "line": 612,
                "function": "dispatchToRoute",
                "class": "Illuminate\\Routing\\Router",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
                "line": 176,
                "function": "dispatch",
                "class": "Illuminate\\Routing\\Router",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 30,
                "function": "Illuminate\\Foundation\\Http\\{closure}",
                "class": "Illuminate\\Foundation\\Http\\Kernel",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/fideloper/proxy/src/TrustProxies.php",
                "line": 57,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "Fideloper\\Proxy\\TrustProxies",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
                "line": 21,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
                "line": 21,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php",
                "line": 27,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php",
                "line": 62,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 163,
                "function": "handle",
                "class": "Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
                "line": 53,
                "function": "Illuminate\\Pipeline\\{closure}",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
                "line": 104,
                "function": "Illuminate\\Routing\\{closure}",
                "class": "Illuminate\\Routing\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
                "line": 151,
                "function": "then",
                "class": "Illuminate\\Pipeline\\Pipeline",
                "type": "->"
            },
            {
                "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
                "line": 116,
                "function": "sendRequestThroughRouter",
                "class": "Illuminate\\Foundation\\Http\\Kernel",
                "type": "->"
            },
            {
                "file": "/var/www/html/public/index.php",
                "line": 55,
                "function": "handle",
                "class": "Illuminate\\Foundation\\Http\\Kernel",
                "type": "->"
            }
        ]
    }
}

And here are my codes: bulkCreate:

  /**
     * @param DoctorServiceBulkCreateRequest $request
     * @param Doctor $doctor
     * @return JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function bulkCreate(DoctorServiceBulkCreateRequest $request, Doctor $doctor)
    {
        $this->authorize('bulkCreate', [ServiceDoctor::class, $doctor]);
        $doctor->serviceDoctors()->createMany($request->all());
        return $this->sendSuccess();
    }

DoctorServiceBulkCreateRequest, rules:

   public function rules()
    {
        return [
            '*.service_id' => 'required|integer|unique:service_doctor,service_id',
            '*.time_taken' => 'required|date_format:H:i:s'
        ];
    }

I am very confused and I do not know where the problem comes from. Nobody knows what the problem is?



via Chebli Mohamed

lundi 24 janvier 2022

Laravel display views stored in amazon s3

How to return view files (laravel blade) in the controller runtime that are stored on the amazon s3 bucket?

OR

How to set view folder path to amazon s3 bucket in runtime?



via Chebli Mohamed

how can i keep data generated by database seeder class so that cannot be deleted in laravel?

I am trying to keep doing roles and permission in Laravel, for permission and roles am using seeder to generate the first data. I need to keep those data generated by a seeder to be not deleted in database, but if a user enter new data can be deleted. permissionseeder

<?php 
namespace  Database\Seeders ; 
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Illuminate\Database\Eloquent\Model;
class PermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $permissions = [
           'role-list',
           'role-create',
           'role-edit',
           'role-delete',
           'List',
           'Create',
           'Edit',
           'Delete'
        ];     
        foreach ($permissions as $permission) {
             Permission::create(['name' => $permission]);
        }
    }
}

Role Seeder this seeder generate roles by using

 $role = Role::create(['name' => 'Admin']);

then after whole code look like:

    <?php
    namespace Database\Seeders;
    use Illuminate\Database\Seeder;
    use Spatie\Permission\Models\Permission;
    use Spatie\Permission\Models\Role;
    
    
    
    class RoleSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {       
            
            $role = Role::create(['name' => 'Admin']);
                      
            $permissions = Permission::pluck('id','id')->all();       
              $role->syncPermissions($permissions);
             
                 
        }
    }

This a permission migration where define all migration and relation between tables

    <?php
    
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    use Spatie\Permission\PermissionRegistrar;
    
    class CreatePermissionTables extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            $tableNames = config('permission.table_names');
            $columnNames = config('permission.column_names');
            $teams = config('permission.teams');
    
            if (empty($tableNames)) {
                throw new \Exception('Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
            }
            if ($teams && empty($columnNames['team_foreign_key'] ?? null)) {
                throw new \Exception('Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
            }
    
            Schema::create($tableNames['permissions'], function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');       // For MySQL 8.0 use string('name', 125);
                $table->string('guard_name'); // For MySQL 8.0 use string('guard_name', 125);
                $table->timestamps();
    
                $table->unique(['name', 'guard_name']);
            });
    
            Schema::create($tableNames['roles'], function (Blueprint $table) use ($teams, $columnNames) {
                $table->bigIncrements('id');
                if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
                    $table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
                    $table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
                }
                $table->string('name');       // For MySQL 8.0 use string('name', 125);
                $table->string('guard_name'); // For MySQL 8.0 use string('guard_name', 125);
                $table->timestamps();
                if ($teams || config('permission.testing')) {
                    $table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
                } else {
                    $table->unique(['name', 'guard_name']);
                }
            });
    
            Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames, $columnNames, $teams) {
                $table->unsignedBigInteger(PermissionRegistrar::$pivotPermission);
    
                $table->string('model_type');
                $table->unsignedBigInteger($columnNames['model_morph_key']);
                $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
    
                $table->foreign(PermissionRegistrar::$pivotPermission)
                    ->references('id')
                    ->on($tableNames['permissions'])
                    ->onDelete('cascade');
                if ($teams) {
                    $table->unsignedBigInteger($columnNames['team_foreign_key']);
                    $table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
    
                    $table->primary([$columnNames['team_foreign_key'], PermissionRegistrar::$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
                        'model_has_permissions_permission_model_type_primary');
                } else {
                    $table->primary([PermissionRegistrar::$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
                        'model_has_permissions_permission_model_type_primary');
                }
    
            });
    
            Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames, $teams) {
                $table->unsignedBigInteger(PermissionRegistrar::$pivotRole);
    
                $table->string('model_type');
                $table->unsignedBigInteger($columnNames['model_morph_key']);
                $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
    
                $table->foreign(PermissionRegistrar::$pivotRole)
                    ->references('id')
                    ->on($tableNames['roles'])
                    ->onDelete('cascade');
                if ($teams) {
                    $table->unsignedBigInteger($columnNames['team_foreign_key']);
                    $table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
    
                    $table->primary([$columnNames['team_foreign_key'], PermissionRegistrar::$pivotRole, $columnNames['model_morph_key'], 'model_type'],
                        'model_has_roles_role_model_type_primary');
                } else {
                    $table->primary([PermissionRegistrar::$pivotRole, $columnNames['model_morph_key'], 'model_type'],
                        'model_has_roles_role_model_type_primary');
                }
            });
    
            Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames) {
                $table->unsignedBigInteger(PermissionRegistrar::$pivotPermission);
                $table->unsignedBigInteger(PermissionRegistrar::$pivotRole);
    
                $table->foreign(PermissionRegistrar::$pivotPermission)
                    ->references('id')
                    ->on($tableNames['permissions'])
                    ->onDelete('cascade');
    
                $table->foreign(PermissionRegistrar::$pivotRole)
                    ->references('id')
                    ->on($tableNames['roles'])
                    ->onDelete('cascade');
    
                $table->primary([PermissionRegistrar::$pivotPermission, PermissionRegistrar::$pivotRole], 'role_has_permissions_permission_id_role_id_primary');
            });
    
            app('cache')
                ->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
                ->forget(config('permission.cache.key'));
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            $tableNames = config('permission.table_names');
    
            if (empty($tableNames)) {
                throw new \Exception('Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
            }
    
            Schema::drop($tableNames['role_has_permissions']);
            Schema::drop($tableNames['model_has_roles']);
            Schema::drop($tableNames['model_has_permissions']);
            Schema::drop($tableNames['roles']);
            Schema::drop($tableNames['permissions']);
        }
    }


via Chebli Mohamed

Delete button not work bootstrap modal and Laravel

I created one table that list items, and I added two buttons(edit and delete) so, the button edit is working, but the button delete is not working, and I'm making me carzy because I don't find the error. this is the table:

<table id="datatable" class="table align-items-center table-flush">
    <thead class="thead-light">
        <tr>
            <th>text</th>
            <th class="disabled-sorting" width="10%"></th>
            <th class="disabled-sorting" width="10%"></th>
        </tr>
    </thead>
    <tbody>
        @foreach($Items as $item)
            <tr>
                <td></td>
                <td><a href="" class="btn btn-primary btn-fab btn-icon btn-round" title="Edit">
                        <i class="fa fa-edit"></i></a>
                </td>
                <td>
                    <a href="#" class="btn btn-primary btn-fab btn-icon btn-round btn-delete" title="Delete" data-id="" data-toggle="modal"  data-target="#modal-default" data-route="" data-title="">
                        <i class="fa fa-trash"></i></a>
                </td>
            </tr>
        @endforeach
    </tbody>
</table>

the modal is:

<div class="modal fade" id="modal-default" tabindex="-1" role="dialog" aria-labelledby="modal-default" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Delete Item</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Delete?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <form class="" action="" method="post">
                    
                    
                    <button type="submit" class="btn btn-danger" name="button">yes, delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

javascript data:

<script>
    $(document).on('click', '.btn-delete', function(){
        $('.modal form').attr('action', $(this).data('route'));
        $('#ModalLabel').text($(this).data('title'));
    })
</script>

and controller function destroy

public function destroy(Items $item) {
    $item->delete();

    return redirect()->route('items.index')->with('success', 'Deleted Success');
}

I checked it line by line, and I don't know what I'm wrong, please help me

Many times thanks for getting into this.



via Chebli Mohamed

samedi 22 janvier 2022

How can I overwrite timestamp to save into the database base on specific timezone?

Right now my Laravel application save() any items into the database base on this timestamp. America/New_York because I configured it as 'timezone' => 'America/New_York', in config/app.php.

Goal

I wish to overwrite timestamp based on other tz instead, ex. America/Chicago

How do I do that?



via Chebli Mohamed

How can update Current Timezone in the main configuration?

config/app.php

'timezone' => 'America/New_York',

I'm trying to update my app.timezone base on clientTimeZone Asia/Kolkata

$date = new DateTime();
$timeZone = $date->getTimezone();
echo $timeZone->getName().PHP_EOL;

$timezone_offset_minutes = 330; 
$clientTimeZone = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
echo $clientTimeZone .PHP_EOL;

Session::put('clientTimeZone',$clientTimeZone);
config('app.timezone', $clientTimeZone);

$date = new DateTime();
$timeZone = $date->getTimezone();
echo $timeZone->getName() .PHP_EOL;

This is the result

America/New_York 
Asia/Kolkata 
America/New_York

I have a feeling that this

config('app.timezone', $clientTimeZone);

is not taking any effect



via Chebli Mohamed

client denied by server configuration:

Entering website url in browser gets a empty notepad file downloaded size 0 kb. Website stops automatically and starts automatically. I am confused how is this even possible. Can anyone help me out yrr.

Error :client denied by server configuration: /home/ki687495/public_html/vendor/laravel/.env



    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
            Options -MultiViews -Indexes
        </IfModule>
    
        <Files .env>
            Order Allow,Deny
            Deny from all
        </Files>
    
        RewriteEngine On
    
        # Handle Authorization Header
        RewriteCond %{HTTP:Authorization} .
        RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    
        # Redirect Trailing Slashes If Not A Folder...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} (.+)/$
        RewriteRule ^ %1 [L,R=301]
    
        # Handle Front Controller...
        RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ [NC]
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_URI} !^/public/
        RewriteRule ^(css|assets|landing|storage|installer|js)/(.*)$ public/$1/$2 [L,NC]
    </IfModule>
    
    # php -- BEGIN cPanel-generated handler, do not edit
    # Set the “ea-php73” package as the default “PHP” programming language.
    <IfModule mime_module>
      AddHandler application/x-httpd-ea-php73 .php .php7 .phtml
    </IfModule>
    # php -- END cPanel-generated handler, do not edit




via Chebli Mohamed

jeudi 20 janvier 2022

My laravel Yajra datatable does not render. It says invalid json response. However I can not read the error since the response is empty

Hello I have the following controller method to return data to my datatable in Laravel,

Controller Method

public function get(Request $request) {
    return Datatables::of(AppUser::all())
    ->addColumn('status', function ($user) {
        if ($user->status == 1) {
            return '<span class="label label-success">Active</span>';
        } else {
            return '<span class="label label-danger">Inactive</span>';
        }
    })
    ->addColumn('actions', function ($user) {
        return view('backend.appuser.actionButton', compact('user'))->render();
    })
    ->make(true);
}

Then in the view I render the datatable, I have the following code.

        <table id="users-table" class="table table-condensed table-hover">
            <thead>
                <tr>
                    <th>Username</th>
                    <th>NIC</th>
                    <th>Mobile</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
        </table>

Inside my script tag I have the below code

$(function() {
    $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '',
            type: 'get',
            data: {status: 1, trashed: false}
        },
        columns: [
            {data: 'email', name: 'email'},
            {data: 'nic', name: 'nic'},
            {data: 'mobile', name: 'mobile'},
            {data: 'status', name: 'status'},
            {data: 'actions', name: 'actions'}
        ],
        pageLength:25,
        lengthMenu:[[10,25,50,100,-1],[10,25,50,100,"All"]],
        order: [ [ 0, "desc" ] ],
        dom: "lBfrtip",
        buttons:
            [
                {extend: 'excel', footer: true, title: 'User Details'},
                {extend: 'pdf', footer: true, title: 'User Details', orientation: 'landscape', pageSize: 'LEGAL'},
                {extend: 'print', footer: true, title: 'User Details', orientation: 'landscape', pageSize: 'LEGAL'}
            ],

        searchDelay: 500
    });
});

The Error When I go to the index page that the datatable is loaded, it says, DataTables warning: table id=users-table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

What I tried

  1. I tried making a little syntax error in the above controller method to see if the application crashes. If the application crashes, it means that the request sent from the datatable must have hit my controller method. (App actually crashed, so the request from the datatable is coming to my controller method.)
  2. I went to the network tab in my developer tools and inspected the response for the request sent from the data-table. The response is empty. It just shows three empty lines. Since the response is empty, I can not figure out what the error is.

Below picture shows the response I got. Picture of the empty response

(I am using Laravel 5.4)



via Chebli Mohamed

($callback) must be a valid callback or null, function "myfunction" not found or invalid function name

I would like to do the array_map but it always show error not found the function,I checked the function name is same. How can I solve this?

 function myfunction($item){
            unset($item['key']);
            return $item;

         }
         print_r(array_map("myfunction",$request->data));


via Chebli Mohamed

mercredi 19 janvier 2022

Laravel - SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined

I'm trying to migrate databases, but my migration is failing on user_info table.

up function

   public function up()
    {
        Schema::table('user_info', function (Blueprint $table) {
            $table->dropColumn('id');
            $table->string('device_name')->nullable()->comment('device name like huawei mate 10 lite');
            $table->text('app_id')->comment('android package name or iOS bundle id');
            $table->string('platform')->nullable()->comment('Android or iOS');
            $table->string('platform_version')->nullable()->comment('Android api version or iOS version');
            $table->string('version_name')->nullable()->comment('Android version name or iOS BundleString');
            $table->integer('version_code')->nullable()->unsigned()->comment('Android version code or iOS BundleVersion');
            $table->string('token_id')->comment('user oauth_access_tokens table id');
            $table->primary(['user_id', 'token_id']);

            $table->foreign('token_id')->references('id')->on('oauth_access_tokens')->onDelete('cascade');
        });
    }

down function

  public function down()
    {
        Schema::table('user_info', function (Blueprint $table) {
            $table->dropPrimary('user_id');
            $table->dropPrimary('token_id');
            $table->dropColumn('device_name');
            $table->dropColumn('app_id');
            $table->dropColumn('platform');
            $table->dropColumn('platform_version');
            $table->dropColumn('version_name');
            $table->dropColumn('version_code');
            $table->dropColumn('token_id');
            $table->bigIncrements('id');
        });
    }

and receive this error:

   Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined (SQL: alter table `user_info` add `id` bigint unsigned not null auto_increment primary key)

What changes do you think I should make to these codes to fix the problem?



via Chebli Mohamed

mardi 18 janvier 2022

getRealPath() and path() return false

When uploading images on localhost, the path() method returns the file path correctly, but in production, it's returning always false. I also tried using getRealPath() but it's the same result. So I decided to use the getPathname() which is what worked.

Does anyone know why it does not work? It's a problem with some lib? I searched a lot but doesn't find anything.

getPathname() result:

string(27) "C:\Windows\Temp\phpA9AF.tmp"

$request->logo or $request->file('logo') dump result:

object(Illuminate\Http\UploadedFile)#305 (7) { ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> bool(false) ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(13) "Teste del.png" ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(9) "image/png" ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(0) ["hashName":protected]=> NULL ["pathName":"SplFileInfo":private]=> string(27) "C:\Windows\Temp\phpA9AF.tmp" ["fileName":"SplFileInfo":private]=> string(11) "phpA9AF.tmp" }

path() or getRealPath()result:

bool(false)



via Chebli Mohamed

lundi 17 janvier 2022

Get latest item in OneTomany relationship laravel 5.5

:)

I've a problem with a relationship in my project, this is the situation, I have two models "Sucursales" and "Checklist", this is the logic... one sucursal can have many checklist, but is one request I only need to get the most recent sucursal's checklist... the simple relation works fine when I call it, but when I'm trying to get the most recent checklist the result is empty, here is the code:

Sucursales Model

class Sucursales extends Model
{
    protected $table = 'db_sucursales';
    protected $primaryKey = 'id_sucursal';
    protected $fillable =['tipo_sucursal', 'no_sucursal', 'id_gcb', 'id_coordinacion', 'nombre_sucursal', 'id_estado', 'direccion_sucursal', 'telefono_sucursal', 'id_estatus'];
    public $timestamps = false;

    public function checkslist(){
        return $this->hasMany(ChecklistSucursal::class, 'id_sucursal','id_sucursal');
    }
}

Checklist model:

class ChecklistSucursal extends Model
{
    protected $table = 'db_checklist_sucursales';
    protected $primaryKey = 'id_checklist';
    protected $fillable = [
        'folio', 'id_sucursal', 'id_usuario', 'nombre_aplicador', 'encargado_sucursal', 'puesto_encargado_sucursal', 'fecha_aplicacion', 'checklist','estatus','comentarios'
    ];

    public function sucursal(){
        return $this->hasOne(Sucursales::class, 'id_sucursal', 'id_sucursal');
    }
    
}

When I call:

$sucursales = Sucursales::with('checkslist')->orderBy('no_sucursal', 'asc')->get();

works fine, but when I call the next code:

$sucursales = Sucursales::with(['checkslist' => function($query){
                return $query->latest('fecha_aplicacion');
            }])
                            ->orderBy('no_sucursal', 'asc')
                            ->get();

the result is empty...

Please someone can tell me what I'm doing wrong, this project is in laravel 5.5



via Chebli Mohamed

How to add HTTPS to this Laravel variable?

I'm trying to add HTTPS to my Laravel variable but to no avail, need help, any help will be highly appreciative!

$verifyurl = $eventName->event_url
    . '/verify-email/' . $event->verifyString 
    . '/' . $user['event_url_id'];
$content = "<b>verify email here  :</b>"
    . "<a href=" . $verifyurl . " target='_blank'>"
    . $eventName->event_url . "</a>"; 


via Chebli Mohamed

Laravel 5.8 sending email & blacklist

I am trying to make a blacklist for emails and I want to implement it upon every every email sending so I would check if users email is blacklisted or not.

At the moment I have.

use Illuminate\Support\Facades\Mail;
if(!EmailExceptionList::isMailBlacklisted($email))
{
    Mail::to($email)->send(new NewViewEmail($user));
}

Now the problem is that I'd have to manually do this everytime - call this function at every place where I have this, is there a way to extend the native laravel mail function and do something like this? Like we have middlewares but for something like this?

I thought about writting a fascade and then simply adding this but still that would take me a bit of time and in the future I'd have to call it and also fascade for a fascade..



via Chebli Mohamed

dimanche 16 janvier 2022

Using a model to access a collection instead of querying a bd Laravel

Normally in my controllers to access the data of a model I do

PaymentMethod::whereActive()->get();
PaymentMethod::all();

It happens that due to process optimization, this model can be handled directly in memory and not query the database for my clients.

$data = collect([...]); //data static

So I want to define a collection of data and through them continue to use the model to filter, when I do a Model::all() it returns the collection defined in $data, or a condition is applied to the collection to avoid accessing the db, in addition i want to avoid making a lot of changes as the model is used in multiple controllers



via Chebli Mohamed

laravel The attached file "VS37435-20211223.xls" seems to be infected with virus / malware

I tried to upload excel from laravel, I am getting below error

The attached file "VS37435-20211223.xls" seems to be infected with virus / malware.

please help



via Chebli Mohamed

samedi 15 janvier 2022

ImageMagick module not available with this PHP installation on MacOS Big Sur

i have installed ImageMagick in my mac book by using home brew, when i search that imageMagick is available in my mac book, the below are search results screenshot. enter image description here

i am using image intervention package when i store my picture in my server, getting error code explain below

// Store a copy
    if($request->hasFile('profilepicture'))
    {
        $image_org = Image::make($request->file('profilepicture'))->encode('png');
        dd($image_org); // getting error
        try {
            // $image_org = Image::make($request->file('profilepicture'))->encode('png');
            // Storage::disk('ppics')->put($viewPortOrg, $image_org);
            Storage::disk('ppics')->put($viewPortOrg, $request->file('profilepicture'));
        } catch (\Exception $e) {
            \Log::error($e);
            return redirect()->back()->with('error','Invalid image uploaded, please try a different image');
        }
    }

the Error screen shot is below enter image description here

how i could resolve this error? Any help?



via Chebli Mohamed

vendredi 14 janvier 2022

How can I show BLOB image file to html page in laravel?

I am fetching the blob type value of a png image from database and show it in my html page but its now working, I am using laravel framework. Please do help.

<img src="data:image/jpeg;base64,'.base64_encode( Auth::user()->photo ).'"
                                class="rounded-circle z-depth-0"
                                alt="avatar image"
                                style="padding-left: 10px"
                                height="35"
                            />


via Chebli Mohamed

How do I upgrade my Laravel 5.6 project to Laravel 8.0.*

I have my project running in Laravel 5.6, now I want to upgrade my Laravel version to 8.0, can anyone please help me with the process and what challenges will I face concerning 5.6 libraries.



via Chebli Mohamed

mercredi 12 janvier 2022

Unable to insert special characters into database in mysql laravel (especially & character)

I want to insert " ~!@#$%^&*()?<>:\| " this string into my table but when I hit save it inserts only this much in table ~!@#$%^, rest of the characters doesn't store in the table.

Here is my laravel controller code

public function store(Request $request)
    {
   
        $x = $request->get('task_name');

        DB::insert('insert into tasks (task_name) values (?)', [$x]);

        $tasks = DB::table('tasks')
                     ->select(DB::raw('task_id,task_name,created,status,prority'))
                     ->where('isActive', '=', '1')
                     ->get();
       
        return $tasks;
}


via Chebli Mohamed

Laravel error: Cannot execute queries while other unbuffered queries are active

My Laravel application (version 5.0.33) has suddenly started throwing the following error:

local.ERROR: exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.' in vendor/laravel/framework/src/Illuminate/Database/Connection.php:296

Looking at the relevant line in Connection.php, it appears to be already using fetchAll:

 public function select($query, $bindings = array(), $useReadPdo = true)
        {
                return $this->run($query, $bindings, function($me, $query, $bindings) use ($useReadPdo)
                {
                        if ($me->pretending()) return array();

                        // For select statements, we'll simply execute the query and return an array
                        // of the database result set. Each element in the array will be a single
                        // row from the database table, and will either be an array or objects.
                        $statement = $this->getPdoForSelect($useReadPdo)->prepare($query);

                        $statement->execute($me->prepareBindings($bindings));

                        return $statement->fetchAll($me->getFetchMode());
                });
        }

I also added the following to my config/database.php:

'options' => [ PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true ]

But I'm still getting the same error. This application has been working correctly for years, and I hadn't made any changes to the code, so I don't know why this suddenly stared happening. I'm also new to Laravel and didn't write the original code, so I'm not even sure where to start debugging the issue. Can anyone help?



via Chebli Mohamed

Laravel 5.8 - Creating a maintenance order and attaching to a car by foreign key

I hope I can ask this question correctly. I have a form to create a car and then another form to create a maintenance order that you can select a car by it's ID to create some maintenance for whichever car was picked. And it works fine in my database I get back the exact car_id selected and they look connected. However, in my browser it is saying that my cars have no relation, and I believe it has something to do with how I create the child in the controller? Am I overwriting the car_id with the request possibly? Here is some code for context.

BLADE:

@section('content')
    <div class="card-body border rounded">
        <form action="" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="form-group">    
                <div class="col-sm-8">
                    <label class="col-sm-4 col-form-label" id="useCar">Use Selected Car</label>
                    <select class="form-control" id="selectCar" name="car_selected" required focus>
                        <option value="" disabled selected>Please select car</option>        
                        @foreach($cars as $car)
                            <option value=""></option>
                        @endforeach
                    </select>
                </div>
            </div>
            <fieldset class="form-group">
                <div class="row">
                    <legend class="col-form-label col-sm-2 pt-0">Maintenance Work: </legend>
                        <div class="col-sm-10">
                            <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="oil_changes" id="gridChecks1">
                            <label class="form-check-label" for="gridChecks1">Oil Changes</label>
                            </div>
                            <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="tire_rotations" id="gridChecks2">
                            <label class="form-check-label" for="gridChecks2">Tire Rotations</label>
                            </div>
                            <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="tune_ups" id="gridChecks3">
                            <label class="form-check-label" for="gridChecks3">Tune-ups</label>
                            </div>
                            <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="repairs" id="gridChecks4">
                            <label class="form-check-label" for="gridChecks4">Repairs</label>  
                            </div>
                        </div>
                </div>
            </fieldset>
            <div class="form-group">
                <label for="maintenanceNotes">Maintenance Notes</label>
                <textarea class="form-control" name="notes" id="maintenanceNotes" rows="3"></textarea>
            </div>
            <br>
            <button class="btn btn-success">Maintenance Request</button>
        </form>
    </div>
@endsection

ROUTES:

Route::get('maintenance/create', 'MaintenanceController@create')->name('maintenance.create');
Route::post('maintenance/store', 'MaintenanceController@store')->name('maintenance.store');

CONTROLLER:

public function store()
    {
        $car_id = request('car_selected');
        $oil = strtoupper(request('oil_changes', 'off')) == 'ON';
        $tire = strtoupper(request('tire_rotations', 'off')) == 'ON';
        $tune = strtoupper(request('tune_ups', 'off')) == 'ON';
        $repair = strtoupper(request('repairs', 'off')) == 'ON';
        $note = request('notes');

        Maintenance::create([
            'car_id' => $car_id,
            'oil_changes' => $oil,
            'tire_rotations' => $tire,
            'tune_ups' => $tune,
            'repairs' => $repair,
            'notes' => $note
        ]);

        return redirect()->route('car.index');
    }


via Chebli Mohamed

Unique Jobs in Laravel 5.2

I have a legacy application in laravel 5.2 and we use queues to process jobs. We observed that the queue can sometimes get too many jobs which leads to duplicate jobs getting dispatched because the previous jobs don't complete processing and the cron that dispatches such jobs runs again and ends up dispatching them over and over.

A simple solution would be to make these jobs unique which would be a very simple change if it were laravel 8. However, we're in laravel 5.2 territory so i'll have to implement unique jobs myself. Or if someone could suggest a better alternative?

Also, if you were to implement unique jobs yourself, how would you do it? The approach I'm thinking is:

Add a unique key for the job to the cache or a database table (implying a lock is attained) Clear the entry once the job is processed (lock released) Before dispatching the job, check if the key exists in the cache or not (lock can be attained or not)



via Chebli Mohamed

laravel-echo-server don't work with proxy

I am using laravel 5.5 for api backend part of application. I am trying to set up working with web-sockets.Can you please tell me why I can not start laravel-echo-server through a proxy? Apache settings

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule /(.*)           ws://localhost:6001/$1 [P,L]

    ProxyRequests Off
    ProxyPass        /socket.io http://localhost:6001/socket.io
    ProxyPassReverse /socket.io http://localhost:6001/socket.io

    #RewriteEngine on
    #RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
    #RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
    #RewriteRule .* ws://localhost:6001%{REQUEST_URI} [P]

But if you use, not a domain, then everything works well Settings laravel-echo-server.json

{
    "authHost": "https://trarchive.it-thematic.ru",
    "authEndpoint": "/api/broadcasting/auth",
    "clients": [
            {
                    "appId": "7pTuIfhqAZMR9ZIwAAAN",
                    "key": "77c87b26b45bd770d1ede3cfe3373fd3"
            }
    ],
    "database": "redis",
    "databaseConfig": {
            "redis": {
                    "port": "6379",
                    "host": "127.0.0.1",
                    "keyPrefix": ""
            },
            "sqlite": {
                    "databasePath": "/database/laravel-echo-server.sqlite"
            }
    },
    "devMode": true,
    "host": null,
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "secureOptions": 67108864,
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "subscribers": {
            "http": true,
            "redis": true
    },
    "apiOriginAllow": {
            "allowCors": false,
            "allowOrigin": "*",
            "allowMethods": "*",
            "allowHeaders": "*"
    }
}

I get error 400, Bad Request



via Chebli Mohamed

mardi 11 janvier 2022

Can't connect to website on port 80 with Laravel Homestead

I'm using Laravel Homestead for my development environment. I have it working at 192.168.0.141:8000, but I need it to work directly at just 192.168.0.141 (i.e. port 80). But it's just not working and I'm not sure what I'm doing wrong. I had it working months ago, but it's not working anymore.

Here's my Homestead.yaml:

---
ip: "192.168.10.10"
memory: 2048
cpus: 2
provider: virtualbox
ssl: true

folders:
    - map: C:\Users\John\Documents\Github\my-app
      to: /home/vagrant/my-app

sites:
    - map: homestead.test
      to: /home/vagrant/my-app/public

networks:
    - type: "public_network"
      ip: "192.168.0.141"

databases:
    - homestead

features:
    - mysql: false
    - mariadb: false
    - postgresql: false
    - ohmyzsh: false
    - webdriver: false


via Chebli Mohamed

Laravel storage FTP driver file exists not working

I have an FTP storage drive defined in my filesystem.php file ... Putting and getting files work perfectly, but when I try and see if a file exists on the remote system, it always returns it doesnt exist even though the file is there

if (Storage::disk('ftp')->exists('/folder/filename.jpg')) {
    echo 'File exists';
} else {
    echo 'File doesnt exist';
}

Is there something wrong with the way i am structuring this?



via Chebli Mohamed

lundi 10 janvier 2022

Mixed Content for PHP laravel 5.4 pagination

We have an application setup behind the AWS load balancer and only the pages serving the pagination have issues with the Mixed Content warning.

We started with checking our .env file which has the correct APP_URL and all other configuration

Next, we checked the server headers and they also seem to be returning fine, Let me know if missing anything.

[REDIRECT_HTTTPS] => on 
[REDIRECT_STATUS] => 200 
[HTTPS] => on // added manually in apache configuration file
[HTTP_X_FORWARDED_FOR] => 14.143.xxx.xxx 
[HTTP_X_FORWARDED_PROTO] => https 
[HTTP_X_FORWARDED_PORT] => 443 

Next, we tried to enforce SSL but no luck

var/www/simpliv/app/Providers/AppServiceProvider.php under the boot function

$this->app['request']->server->set('HTTPS', true);
URL::forceScheme('https');

further read somewhere to check if application is getting secure protocol or not and tried this

Request::secure(); 
This return true

Screenshot of the issue. Unable to proceed further on how to fix this issue

Can provide Apache configuration and .htaccess file if required Here



via Chebli Mohamed

Convert SQL to eloquent query

i have the next query with subequery how can convert it to eloquent, i have some troubles with eloquent conversion :S. Thanks

select a.* from (
    select * 
    from "public"."tabla_procesados" 
    where "state" LIKE '%Failed%' 
    and id_execution = (select max(id_execution) from public.tabla_procesados)
    order by public.tabla_procesados.ts_start_processing desc limit 1
) a
where ts_start_processing < (now() - '10 minutes'::INTERVAL)


via Chebli Mohamed

dimanche 9 janvier 2022

Cannot print value that is returned from Controller Laravel

My view doesn't recognize the variables that are passed from controller to view for printing.
My flow of getting the result on view : model gives the result from db -> controller then checks them and puts them in different arrays -> on form submit, js is called and ajax is used to call the route where I get the results and then I want them to be printed in table format.
There is no issue in queries. The numbers in the response are perfect. But I can't print them on view. My view doesn't recognize the getComptage arrays. Even var_dump(isset($_POST['rechercher'])) doesn't return anything. I've been trying to solve this for 2 days but nothing helped.

Form:

<h2 class="planning-stats-header">
    <p>{!! __('planning.planning_stats_header') !!} </p>
    <p>{!! __('planning.planning_stats_subheader') !!}</p>
</h2>

<form method="POST">
    @csrf
    <table class="table" id="table_recherche" cellpadding="5" cellspacing="5" border="0">
        <tr>
            <td>Date debut: </td>
            <td>
                <input type="text" id="datepickerdebut" name="datedebut" value="">
            </td>
            <td>Date Fin: </td>
            <td>
                <input type="text" id="datepickerfin" name="datefin">
            </td>
        </tr>
        <tr>
            <td align="center" colspan="4">
                <input id="rechercher" type="button" value="Rechercher" name="rechercher">
            </td>
        </tr>
    </table>
</form>
<div id="contenu">
    <table class="table table-striped table-condensed table-hover table-responsive">
        <thead>
            <tr>
                <th>{!! __("planning.nom") !!}</th>
                <th>{!! __("planning.matin") !!}</th>
                <th>{!! __("planning.midi") !!}</th>
                <th>{!! __("planning.soir") !!}</th>
                <th>{!! __("planning.recurrent") !!}</th>
                <th>{!! __("planning.astreinte") !!}</th>
                <th>{!! __("planning.intervention") !!}</th>
            </tr>
        </thead>
        <tbody>
                @foreach($req_personnes as $req_personnes)
                    <tr>
                        <td> </td>
                        @php
                        if(!isset($_POST['rechercher'])) {
                            for($i=0; $i<6; $i++) {
                                echo '<td>2</td>';
                            }
                        } else {
                            for($i=0; $i<6; $i++) {
                                echo '<td>'. $getComptageMA[$i] .'</td>';
                                echo '<td>'. $getComptageMI[$i] .'</td>';
                                echo '<td>'. $getComptageS[$i] .'</td>';
                                echo '<td>'. $getComptageR[$i] .'</td>';
                                echo '<td>'. $getComptageA[$i] .'</td>';
                            }
                        }
                        @endphp
                    </tr>
                @endforeach
        </tbody>
    </table>
</div>

Controller :

public function getStats(Request $request) {
      $calendrierObj = new Calendrier();
      $utilisateurObj = new Utilisateur();
      $hnoObj = new Hno();
      $utilisateurs = $utilisateurObj->creeTableauSGI();
      $req_personnes = $utilisateurObj->getPersonnes();
      if($request->post('date_d') && $request->post('date_f')) {
          $ddebut = $request->post('date_d');
          $dfin = $request->post('date_f');
          $interventions = $hnoObj->creeTableauInterventions($ddebut, $dfin, $utilisateurs);
          $getComptageMA = [];
          $getComptageMI = [];
          $getComptageS = [];
          $getComptageR = [];
          $getComptageA = [];
          $intervent = [];
          for ($i=0; $i<count($utilisateurObj->getPersonnes()); $i++) {
                $sgi = (string) $req_personnes[$i]->identifiant;
                array_push($getComptageMA, $calendrierObj->getComptage($sgi, "MA", $ddebut, $dfin));
                array_push($getComptageMI, $calendrierObj->getComptage($sgi, "MI", $ddebut, $dfin));
                array_push($getComptageS, $calendrierObj->getComptage($sgi, "S", $ddebut, $dfin));
                array_push($getComptageR, $calendrierObj->getComptage($sgi, "R", $ddebut, $dfin));
                array_push($getComptageA, $calendrierObj->getComptage($sgi, "A", $ddebut, $dfin));
                if (array_key_exists((string) $req_personnes[$i]->identifiant, $interventions)) {
                    array_push($intervent, $interventions['identifiant']);
                }
          }
          return array('req_personnes' => $req_personnes, 'getComptageMA' => $getComptageMA, 
              'getComptageMI' => $getComptageMI, 'getComptageS' => $getComptageS, 
              'getComptageR' => $getComptageR, 'getComptageA' => $getComptageA, 
              'ddebut' => $ddebut, 'dfin' => $dfin, 'intervent' => $intervent);
      }

JS:

// display current and previous date on textbox
$(document).ready(function () {
    var todaydate = new Date();
    var day = todaydate.getDate();
    var month = todaydate.getMonth() + 1;
    var year = todaydate.getFullYear();
    var datestring = day + "/" + month + "/" + year;
    document.getElementById("datepickerdebut").value = day-1 + "/" + month + "/" + year;
    document.getElementById("datepickerfin").value = datestring;
});

$('#rechercher').click(function (e) {
   var headers = {
            'X-CSRF-TOKEN':'<meta name="csrf-token" content="">'
        };
   e.preventDefault();
   e.stopPropagation();
   var d = $("#datepickerdebut").val().split('/');   //dd/mm/yyyy
   var debut = d[2]+'/'+d[1]+'/'+d[0];
   var f = $("#datepickerfin").val().split('/');
   var fin = f[2]+'/'+f[1]+'/'+f[0];
   
   $.ajax({
        url: '/planning/stats/statistique',
        method: 'POST',
        data:
            {
                myFunction: 'getStats',
                date_d: debut,
                date_f: fin
            },
        headers: headers,
        dataType: 'html',
        async: false,
    });
});

Response that I'm getting :
enter image description here



via Chebli Mohamed

When I pass string variables to controller in laravel via ajax, It doesn't show me proper data

This is my Ajax Query

  function updateTask() {
    var task_id = document.getElementById('edit').getAttribute('edit_task_id');
    var newTask = document.getElementById('edit_task').value;
    var csrf = document.querySelector('meta[name="csrf-token"]').content;
    var close = document.getElementById('close');
    var editob = new XMLHttpRequest();
    editob.open('POST', '/{task_id}/{newTask}', true);
    editob.setRequestHeader('X-CSRF-Token', csrf);
    editob.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    editob.send("task_id=" + task_id, "newTask=" + newTask);
    
    console.log(newTask);
    console.log(task_id);
  }

This is y Controller

    public function editTask($id, $newTask){
        //$x = $id->get('task_id');
         print_r($id);
         print_r($newTask);
         
    }

And this is the response I get, butI actually want the proper string value that I passed through ajax This is what i get as response



via Chebli Mohamed

samedi 8 janvier 2022

how to keep logged in user to try.com domain from buy.try.com using the same database but different location in Laravel 5?

I have users tables in my database

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('slug');
            $table->text('token');
            $table->enum('user_type', ['1', '2'])->default('1');
            $table->boolean('is_authenticated')->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
    }

They are all connected to the same database but the diffrents folder location. So, when I want to login to try.com, I want also the same user to be login on buy.try.com.

This is the session code of try.com on config->session.php

'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 120,
'expire_on_close' => false,
'cookie' => 'try_session',
'domain' => env('SESSION_DOMAIN', 'try.com'),
'secure' => env('SESSION_SECURE_COOKIE', true), //because I'm using https ssl
'http_only' => null,

And this is the session code of buy.try.com on config->session.php

'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 120,
'expire_on_close' => false,
'cookie' => 'try_session',
'domain' => env('SESSION_DOMAIN', 'buy.try.com'),
'secure' => env('SESSION_SECURE_COOKIE', true), //because I'm using https ssl
'http_only' => null,

Then this is .env of try.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=try_db
DB_USERNAME=try_user
DB_PASSWORD=try123

COMMON_DB_DATABASE=try_db
COMMON_DB_USERNAME=try_user
COMMON_DB_PASSWORD=try123
COMMON_DB_SOCKET=

Then this is .env of buy.try.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=try_db
DB_USERNAME=try_user
DB_PASSWORD=try123

COMMON_DB_DATABASE=try_db
COMMON_DB_USERNAME=try_user
COMMON_DB_PASSWORD=try123
COMMON_DB_SOCKET=

At the end they are all using the common_database to get session session

'common_database' => [
            'driver' => 'mysql',
            'url' => env('COMMON_DATABASE_URL'),
            'host' => env('COMMON_DB_HOST', '127.0.0.1'),
            'port' => env('COMMON_DB_PORT', '3306'),
            'database' => env('COMMON_DB_DATABASE','forge'),
            'username' => env('COMMON_DB_USERNAME','forge'),
            'password' => env('COMMON_DB_PASSWORD', ''),
            'unix_socket' => env('COMMON_DB_SOCKET',''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), 
            ]) : [],
        ],

Can you help me to fix it ?



via Chebli Mohamed

How to get less than data of selected month of year in laravel?

i have a table where all data of students. i need only less than month data of selected month of year. i have date column data like these.

registrationdate
2022-01-31
2021-12-01
2022-07-01
2021-11-12
2021-10-10
2022-01-07 
2020-08-26

if I select month 12 and year 2021 I need only previous data of December 2021

$month=12 and $year =2021

$selectedmonthMalestudents  = \DB::table('students')
                   
        ->whereRaw('extract(month from registrationdate) = ?','<' [$month])
        ->whereRaw('extract(year from registrationdate) = ?', [$year])
        ->count();

Please Help me How to do these...



via Chebli Mohamed

confusion in Db structure for fees in school project laravel [closed]

in my school fee management system i have course category ,class ,teacher ,student,payment and fee models and when the class is created the course category and teachers are related to it and when a student is added the class is related in many to many relation , and also when the payment is created in each month the class is related with it in foreign key.....i already developed it but i confused in the way how to manage fee or invoice of each payment that is created in each month for the student i ....the student pay their monthly payment in cash for the admin and the admin registered as "payed " in the system .......i can show all the code if it is required ..........please help me ??



via Chebli Mohamed

jeudi 6 janvier 2022

/tmp/laravel-excel does not exist

so i am using laravel excel for importing .csv files and because the .csv files contain a lot of data then i running the import using laravel queue with redis driver

everything working just fine at local server at my mac using valet

but the problem occur when i tried the same code at production server at our vps that managed using runcloud

and it is only happen if i am using queue driver beside snyc. so if i change it to use database driver or redis driver then the error come.

after doing multiple debuging i find out that the error is because it can't create \tmp\ files for this plugins for doing import

to help find the key issue here is my configuration

"php": ">=7.1.3",
"maatwebsite/excel": "^3.1",
"laravel/framework": "5.6.*",
"predis/predis": "^1.1", 

and here is stacktrace from laravel.log

[2022-01-06 14:57:14] local.ERROR: File "/tmp/laravel-excel-kzUS1G2AIXnig0Z1VKs5AegK3ar98WRS.csv" does not exist. {"exception":"[object] (InvalidArgumentException(code: 0): File \"/tmp/laravel-excel-kzUS1G2AIXnig0Z1VKs5AegK3ar98WRS.csv\" does not exist. at /home/runcloud/webapps/puskopcuina/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php:137)
[stacktrace]
#0 /home/runcloud/webapps/puskopcuina/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php(152): PhpOffice\\PhpSpreadsheet\\Shared\\File::assertFile()
#1 /home/runcloud/webapps/puskopcuina/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php(540): PhpOffice\\PhpSpreadsheet\\Reader\\BaseReader->openFile()
#2 /home/runcloud/webapps/puskopcuina/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php(349): PhpOffice\\PhpSpreadsheet\\Reader\\Csv->canRead()
#3 /home/runcloud/webapps/puskopcuina/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php(330): PhpOffice\\PhpSpreadsheet\\Reader\\Csv->loadIntoExisting()
#4 /home/runcloud/webapps/puskopcuina/vendor/maatwebsite/excel/src/Jobs/ReadChunk.php(118): PhpOffice\\PhpSpreadsheet\\Reader\\Csv->load()
#5 [internal function]: Maatwebsite\\Excel\\Jobs\\ReadChunk->handle()
#6 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array()
#7 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#8 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\\Container\\BoundMethod::callBoundMethod()
#9 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Container/Container.php(564): Illuminate\\Container\\BoundMethod::call()
#10 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\\Container\\Container->call()
#11 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Bus\\Dispatcher->Illuminate\\Bus\\{closure}()
#12 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#13 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\\Pipeline\\Pipeline->then()
#14 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(49): Illuminate\\Bus\\Dispatcher->dispatchNow()
#15 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(83): Illuminate\\Queue\\CallQueuedHandler->call()
#16 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(326): Illuminate\\Queue\\Jobs\\Job->fire()
#17 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(276): Illuminate\\Queue\\Worker->process()
#18 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\\Queue\\Worker->runJob()
#19 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(101): Illuminate\\Queue\\Worker->daemon()
#20 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(85): Illuminate\\Queue\\Console\\WorkCommand->runWorker()
#21 [internal function]: Illuminate\\Queue\\Console\\WorkCommand->handle()
#22 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array()
#23 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#24 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\\Container\\BoundMethod::callBoundMethod()
#25 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Container/Container.php(564): Illuminate\\Container\\BoundMethod::call()
#26 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Console/Command.php(179): Illuminate\\Container\\Container->call()
#27 /home/runcloud/webapps/puskopcuina/vendor/symfony/console/Command/Command.php(255): Illuminate\\Console\\Command->execute()
#28 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Console/Command.php(166): Symfony\\Component\\Console\\Command\\Command->run()
#29 /home/runcloud/webapps/puskopcuina/vendor/symfony/console/Application.php(1009): Illuminate\\Console\\Command->run()
#30 /home/runcloud/webapps/puskopcuina/vendor/symfony/console/Application.php(273): Symfony\\Component\\Console\\Application->doRunCommand()
#31 /home/runcloud/webapps/puskopcuina/vendor/symfony/console/Application.php(149): Symfony\\Component\\Console\\Application->doRun()
#32 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Console/Application.php(89): Symfony\\Component\\Console\\Application->run()
#33 /home/runcloud/webapps/puskopcuina/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\\Console\\Application->run()
#34 /home/runcloud/webapps/puskopcuina/artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle()
#35 {m

ain} "}



via Chebli Mohamed