lundi 31 janvier 2022

Laravel Dispatch method called from static method results in different Job Payload

I have refactored some code so that 2 public function created within a Controller file, have been moved into a Model file and as public static.

The following method is called from within a Controller:

public static function moveItem(Transactin $transaction)

and self::confirmPayment($order) is called within this method which calls:

private static function confirmPayment(Order $order)

Within this method a mailable is created and dispatched via SendPaymentConfirmation::dispatch($mailable, $order)

The construct of the Job Class is as follows:

public function __construct(OrderPaid $mailable, Order $order)
{
    $this->mailable = $mailable;
    $this->order = $order;
}

The code was working fine before moving it to static methods. This is from the working jobs.payload:

O:45:\"Illuminate\\Contracts\\Database\\ModelIdentifier\":4:{
  s:5:\"class\";
  s:9:\"App\\Order\";
  s:2:\"id\";i:123456;
  s:9:\"relations\";a:5:{i:0;
  s:8:\"payments\";i:1;
  s:21:\"payments.transactions\";i:2;
  s:14:\"customisations\";i:3;
  s:8:\"user\";i:4;
  s:7:\"creator\";}

Different payload that is saved after calling via the static methods:

O:45:\"Illuminate\\Contracts\\Database\\ModelIdentifier\":4:{
  s:5:\"class\";
  s:9:\"App\\Order\";
  s:2:\"id\";i:123456;
  s:9:\"relations\";a:11:{i:0;
  s:8:\"payments\";i:1;
  s:21:\"payments.transactions\";i:2;
  s:5:\"items\";i:3;
  s:19:\"items.customisation\";i:5;
  s:14:\"customisations\";i:8;
  s:8:\"user\";i:10;
  s:7:\"creator\";}

As you can see, it has added a number of additional relations. These are valid but strange that it is adding more. When the queue is run, Laravel returns the following error:

local.ERROR: Call to a member function customisation() on null
[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function customisation() on null at /home/vagrant/code/test/app/Models/Order/Item.php:44)

I changed the constuct of the Job to use withoutRelations but still getting the error:

public function __construct(OrderPaid $mailable, Order $order)
{
    $this->mailable = $mailable;
    $this->order = $order->withoutRelations();
}

Is there a reason why the relations would be different when called via non-static vs static method?



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

mardi 25 janvier 2022

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

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

Get error when composer create-project --prefer-dist laravel/laravel laravel-essentials

My system is Windows 11. I am a new learner for Laravel and I am following the guidance to set up my working environments. I create my Laravel follow the steps as below.. then I get error.

Step 1: Download PHP and save it in the folder C:\Program Files\php, sent the path to this folder.

Step 2: Download Composer and save it in the folder C:\Program Files\php\php.exe

Step 3: Download vagrant and virtualbox. Then run those lines in the command

C:\Users\mreal>vagrant box add laravel/homestead --box-version 8.1.0
==> box: Loading metadata for box 'laravel/homestead'
    box: URL: https://vagrantcloud.com/laravel/homestead
This box can work with multiple providers! The providers that it
can work with are listed below. Please review the list and choose
the provider you will be working with.

1) hyperv
2) parallels
3) virtualbox
4) vmware_desktop

Enter your choice: 3
==> box: Adding box 'laravel/homestead' (v8.1.0) for provider: virtualbox
    box: Downloading: https://vagrantcloud.com/laravel/boxes/homestead/versions/8.1.0/providers/virtualbox.box
==> box: Box download is resuming from prior download progress
    box:
==> box: Successfully added box 'laravel/homestead' (v8.1.0) for 'virtualbox'!

Step 4: Create laravel and I get error

C:\Users\mreal>composer create-project --prefer-dist laravel/laravel laravel-essentials
Creating a "laravel/laravel" project at "./laravel-essentials"
Installing laravel/laravel (v8.6.10)
  - Installing laravel/laravel (v8.6.10): Extracting archive
Created project in C:\Users\mreal\laravel-essentials
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/framework[v8.75.0, ..., 8.x-dev] require league/flysystem ^1.1 -> satisfiable by league/flysystem[1.1.0, ..., 1.x-dev].
    - league/flysystem[1.1.0, ..., 1.x-dev] require ext-fileinfo * -> it is missing from your system. Install or enable PHP's fileinfo extension.
    - Root composer.json requires laravel/framework ^8.75 -> satisfiable by laravel/framework[v8.75.0, ..., 8.x-dev].

To enable extensions, verify that they are enabled in your .ini files:
    - C:\Program Files\php\php.ini
You can also run `php --ini` in a terminal to see which files are used by PHP in CLI mode.
Alternatively, you can run Composer with `--ignore-platform-req=ext-fileinfo` to temporarily ignore these required extensions.


via Chebli Mohamed

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

vendredi 21 janvier 2022

Laravel - Uncaught TypeError: Cannot read properties of null (reading 'value')

I'm trying to use lightpick datepicker on my application. Unfortunately this works when I don't follow standards, and doesn't work when I do.
Blade :

@section('page_script')
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
@endsection

@section('content')
    @include('planning.partials.planningStatsForm')
@endsection

datePicker.js:

var picker = new Lightpick({
    field: document.getElementById('ddebut_picker'),
    secondField: document.getElementById('dfin_picker'),
    repick: true,
    lang: 'fr',
    singleDate: false,
    selectForward: true
});

Error (if I use the above code) : enter image description here

If I use the script tags inside @section('content') and do no use separate @section('page_script') section then everything works perfectly. But for the current code, it doesn't work. I haven't changed anything in the js, controller, blade or model.



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

mercredi 19 janvier 2022

Eloquent select field after aggregation

I have three models, User, Post and Comment. User and Post are in a One-To-Many relationship, and so are User and Comment. For the sake of this example, there isn't a Post-Comment relationship.

When I run the following query

User::withCount(['posts', 'comments'])->get()

I obtain the expected results:

[
...
  App\Models\User {#3459
    id: 18,
    username: "Foo",
    created_at: "2021-12-08 11:38:39",
    updated_at: "2021-12-08 11:38:39",
    posts_count: 5,
    comments_count: 15,
  }
...
]

I would like to remove the timestamps from the resulting models. I've tried putting the array of fields I want as parameter for get (as in ->get(['username', 'posts_count', 'comments_count']), but the result didn't change at all.

I've also tried replacing get(...) with select(...)->get(), but that produces this error:

Illuminate\Database\QueryException with message 
'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts_count' in 'field list'  
(SQL: select `username`, `posts_count`, `comments_count` from `users`)'

which I assume it is due to the fact that the aggregation function is not yet being executed.

So I came up with this solution

$usersWithCounts = User::withCount(['posts', 'comments'])->get()
    ->map(function ($item, $key) {
         return $item->only(['username', 'posts_count', 'comments_count']); 
      });

but it doesn't feel right: the returned collection is no longer made of Eloquent models, just simple arrays.

[
...
  [
    username: "Foo",
    posts_count: 5,
    comments_count: 15,
  ]
...
]

What's the right way of proceeding?



via Chebli Mohamed

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

i want to change date format to text and export to excel

please i need seome help!

Mycode:

$start = Carbon\Carbon::createFromFormat('d-m-Y', '01-02-2019')->firstOfMonth();
$end = Carbon\Carbon::createFromFormat('d-m-Y', '01-02-2019')->lastOfMonth(); 

i want change date format 01-02-2019 to Day1 and etc export to excel. sorry for my bad english.



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 how to use model scope method inside join query

i want to use scope method inside join subquery so is there any way I can do that in laravel?

Post Model

    public function scopePublished($query)
    {
        return $query->where('published',true);
    }

Now I want to join user table with post table but in join I want to use this scope method directly but its giving me error.

Users::join('posts',function($q){
    $q->on('posts.user_id','users.id');
    $q->published();

})->get();

So is there any way I can use scope directly inside join subquery ?



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 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 {main}"} 

update

here is my config/excel.php

<?php

use Maatwebsite\Excel\Excel;

return [
    'exports'            => [

        /*
        |--------------------------------------------------------------------------
        | Chunk size
        |--------------------------------------------------------------------------
        |
        | When using FromQuery, the query is automatically chunked.
        | Here you can specify how big the chunk should be.
        |
        */
        'chunk_size' => 1000,

        /*
        |--------------------------------------------------------------------------
        | Temporary path
        |--------------------------------------------------------------------------
        |
        | When exporting files, we use a temporary file, before storing
        | or downloading. Here you can customize that path.
        |
        */
        'temp_path'  => sys_get_temp_dir(),

        /*
        |--------------------------------------------------------------------------
        | CSV Settings
        |--------------------------------------------------------------------------
        |
        | Configure e.g. delimiter, enclosure and line ending for CSV exports.
        |
        */
        'csv'        => [
            'delimiter'              => ',',
            'enclosure'              => '"',
            'line_ending'            => PHP_EOL,
            'use_bom'                => false,
            'include_separator_line' => false,
            'excel_compatibility'    => false,
        ],
    ],

    'imports' => [

        'heading_row' => [

            /*
            |--------------------------------------------------------------------------
            | Heading Row Formatter
            |--------------------------------------------------------------------------
            |
            | Configure the heading row formatter.
            | Available options: none|slug|custom
            |
            */
            'formatter' => 'slug',
        ],

        'csv' => [
            'delimiter'              => '|',
            'enclosure'              => '"',
            'line_ending'            => PHP_EOL,
            'use_bom'                => false,
            'include_separator_line' => false,
            'excel_compatibility'    => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Extension detector
    |--------------------------------------------------------------------------
    |
    | Configure here which writer type should be used when
    | the package needs to guess the correct type
    | based on the extension alone.
    |
    */
    'extension_detector' => [
        'xlsx'     => Excel::XLSX,
        'xlsm'     => Excel::XLSX,
        'xltx'     => Excel::XLSX,
        'xltm'     => Excel::XLSX,
        'xls'      => Excel::XLS,
        'xlt'      => Excel::XLS,
        'ods'      => Excel::ODS,
        'ots'      => Excel::ODS,
        'slk'      => Excel::SLK,
        'xml'      => Excel::XML,
        'gnumeric' => Excel::GNUMERIC,
        'htm'      => Excel::HTML,
        'html'     => Excel::HTML,
        'csv'      => Excel::CSV,
        'tsv'      => Excel::TSV,

        /*
        |--------------------------------------------------------------------------
        | PDF Extension
        |--------------------------------------------------------------------------
        |
        | Configure here which Pdf driver should be used by default.
        | Available options: Excel::MPDF | Excel::TCPDF | Excel::DOMPDF
        |
        */
        'pdf'      => Excel::DOMPDF,
    ],
];


via Chebli Mohamed

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mkstudent.classes_student' doesn't exist (SQL: insert into `classes_student` (`classes_id`,

i dont know why it is going to store in mkstudent.classes_student table , i mean i created many to many table class_student and when i tray to store a a student that have a class this error is happening any one who can help me please? the code is here student controller

public function store(createstudentrequest $request)
    {

       $student= Student::create([
            'first_name'=>$request->first_name,
            'last_name'=>$request->last_name,
            'phone_number'=>$request->phone_number
        ]);

        if($request->class){
            $student->classe()->attach($request->class);
        }

        session()->flash('success','student added successfully');
        return redirect(route('students.index'));
    }

student.create

<form action="" method="POST" enctype="multipart/form-data" >
            @csrf
            <div class="form-group">
                <label for="title">First Name</label>
                <input type="text" name="first_name" class="form-control" value="">
            </div>
            <div class="form-group">
                <label for="title">Last Name</label>
                <input type="text" name="last_name" class="form-control" value="">
            </div>
            <div class="form-group">
                <label for="title">Phone Number</label>
                <input type="text" name="phone_number" class="form-control" value="">
            </div>
            <div class="form-group">
                <label for="Class">Class</label>
                @if($classes->count() > 0)
                <select name="class[]" id="class" multiple="true" class="form-control">
                    @foreach($classes as $class)
                    <option value="">
                        
                    </option>
                    @endforeach
                </select>
                @endif
            </div>

and the migration for class_student is

 public function up()
    {
        Schema::create('class_student', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('classes_id');
            $table->integer('student_id');
            $table->timestamps();
        });
    }

and in the student model


class Student extends Model
{
     protected $fillable = [
        'first_name','last_name','phone_number'
    ];

    public function classe()
    {
      return $this->belongsToMany(Classes::class);
    }
}

in the classes model

 public function students()
    {
        return $this->belongsToMany(Student::class);
    }


via Chebli Mohamed

mercredi 5 janvier 2022

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mkstudent.classes_teacher' doesn't exist (SQL: select `teachers`.*, `classes_teacher`.`cla

here is my Classes model

class Classes extends Model
{
   protected $fillable = [
        'name','course_catagory_id','teacher_id'
    ];

    public function coursecatagory()
    {
        return $this->belongsTo(CourseCatagory::class);
    }
    public function teacher()
    {
        return $this->belongsToMany(Teacher::class);
    }
}

and migrations

public function up()
    {
        Schema::create('classes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('course_catagory_id');
            $table->integer('teacher_id');
            
            $table->timestamps();
        });
    }

and create classes page

  <div class="card-body">
            @if(session()->has('success'))
             <div class="alert alert-success">
                 
               </div>
             @endif
            <form method="POST" action="">
               @csrf 
               
            <table class="table table-boreder">
               <tr>
                  <th>Name</th>
                  <td>
                     <input type="text" name="name" class="form-control">
                  </td>
               </tr>
               <tr>
                  <td colspan="2">
                     <input type="submit" value="submit" class="btn btn-primary ">
                     
                  </td>
               </tr>
                                  
               </table>
          </form>
            </div>
          </div>

and classes index page

<div class="card-body">
        @if($data->count()>0)
        <table class="table">
            <thead>
                <th>name</th>
                <th>Course Catagory</th>
                <th>
                    Teacher
                </th>
            </thead>
            <tbody>
                @foreach($data as $d)
                <tr>
                    
                    <td>
                        

                    </td>
                    <td>
                        

                    </td>
                    
                    
                    <td>
                    <a href="#">
                        
                    </a>
                    </td>
            
                    
                </tr>
                @endforeach
            </tbody>
        </table>
        @else
        <h3 class="text-center">No class Yet!</h3>
        @endif
        
    </div>

and when i create a new class it saved in the database but dose not restricted to the index view and when i tray to see the index view only the class name is displayed the other fields are not dispalyed and the error face the error



via Chebli Mohamed