jeudi 31 mars 2022

upload file with laravel

I´m trying upload one file to storage/app with laravel for this, i´m checking that my folder exist:

if(isset($request->file_job)){
            $pathFolder = storage_path('app/contratos/'.$tarea->contratoTrey->serie->SERIE.'-'.$tarea->contratoTrey->N_CONTRATO.'/tareas/T-'.$tarea->ntarea);
           
            if(!\File::exists($pathFolder)) {
                \File::makeDirectory($pathFolder, 0755, true, true);
            }


            $filePath = 'app/contratos/'.$tarea->contratoTrey->serie->SERIE.'-'.$tarea->contratoTrey->N_CONTRATO.'/tareas/T-'.$tarea->ntarea;
            \Storage::disk('local')->put($filePath, $request->file_job);
        }

if not exist i´m building my structure folder and put my file in this folder.

My problem it´s in my DB i´m insert my file name with getClientOriginalName() but in this route

'app/contratos/'.$tarea->contratoTrey->serie->SERIE

my app was builded a file, not directory and in this directory my file with his original name...

i don´t know that i´m doing wrong.. i trayed creating a new variable with this name and save... same error or problem...

Thanks for readme and help me. Sorry for my bad english



via Chebli Mohamed

If Laravel collection has more than 1000 items the hasMany relationship collections are dissapearing

I have a Laravel query:

$var = Model::with(['rel1','rel2.1','rel2.2','rel2.3','rel3','rel4'])
->whereBetween('datum', [$start, $end])
->get();

If $var has more than 1000 items the hasMany relationships return an empty collection. If the same query has less than 1000 items the relationships are fine.

I have tried to set the PHP ini settings:

ini_set('memory_limit', '512M');

ini_set('max_input_vars', 30000);

ini_set('max_execution_time', 380);

But nothing worked so far.

On localhost everything works as expected, this issue only apears on the web server. Laravel is 5.4, PHP version 7.2.24

I'd like to get the relationships even if the collection is largen than 1000.

Thanks for your help.



via Chebli Mohamed

mercredi 30 mars 2022

Trying to get data using forgein key Angular

This is laravel function in the controller

public function getcatproduct($id)
    {
        $categories = category::all();
        $products = product::where('category_id', "=", $id)->first();
        // $products = $prod->categories;
        $categories = category::findOrFail($id);
        return response()->json([
            'data' => $categories,
            'data' => $products,
            'message' => 200
        ]);
    }

Typescript code getCatByProduct is a service I'm using laravel as an API !

   ngOnInit(): void {
  
    this.id = this.route.snapshot.paramMap.get('id');
    this.getProductbyCategData();
   
  }

getProductbyCategData(){
    this.dataService.getCatByProduct(this.id).subscribe(res => {
     this.data = res;
     this.product = this.data;
   
    });   }


via Chebli Mohamed

Correct setup for a Laravel resource of a jsonb column?

I have a jsonb column in Postgres that I'm trying to make use of with Laravel. When the resource itself is returned (rest, etc), the value for that column is returned null:

{
    "content": [
        {
            "partner_uuid": "bc844aa7-283e-4b82-8188-2f8764bc9d59",
            "metadata": null
        }
    ]
}

From the backend, this row definitely is non-null:

bc844aa7-283e-4b82-8188-2f8764bc9d59 | {"test": "test"}

I'm not very familiar with Laravel, and so I'm struggling a bit. The problem seems to be in the resource itself, which has a single function:

class PartnerMetadataResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'partner_uuid' => $this->partner_uuid,
            'metadata' => $this->metadata,
        ];
    }
}

If the metadata column is any other column type, this code seems sufficient to return the value as expected. I've tested with integers, text/varchar (and even the other column which is type uuid).

What is needed to return a value for that column? Either as escaped text, or as proper nested json?



via Chebli Mohamed

Multiple queue workers: some restart, some don't with ERROR (spawn error)

Our application provides a separate database for each of our users. I have set up an emailing job which users may dispatch to run in background via a Laravel 5.3 Queue. Some users succeed in evoking this facility (so it does work - same codebase) but some users fail.

The users who fail to generate the email are all characterised by the following error when trying to restart all user queues using sudo supervisor start all, eg:

shenstone-worker:shenstone-worker_02: ERROR (spawn error)
shenstone-worker:shenstone-worker_00: ERROR (spawn error)
shenstone-worker:shenstone-worker_01: ERROR (spawn error)

An example of a user who's email facility works:

meadowwood-worker:meadowwood-worker_02: started
meadowwood-worker:meadowwood-worker_00: started
meadowwood-worker:meadowwood-worker_01: started

The log of all attempted restarts has a load of these spawn errors at the beginning then all the successful queue restarts at the end.

The worker config files for these two users are:

[program:shenstone-worker]
process_name=%(program_name)s_%(process_num)02d
directory=/var/www/solar3/current
environment=APP_ENV="shenstone"
command=php artisan queue:work --tries=1 --timeout=300
autostart=true
autorestart=true
user=root
numprocs=3
redirect_stderr=true
stdout-logfiles=/var/www/solar3/storage/logs/shenstone-worker.log

and

[program:meadowwood-worker]
process_name=%(program_name)s_%(process_num)02d
directory=/var/www/solar3/current
environment=APP_ENV="meadowwood"
command=php artisan queue:work --tries=1 --timeout=300
autostart=true
autorestart=true
user=root
numprocs=3
redirect_stderr=true
stdout-logfiles=/var/www/solar3/storage/logs/meadowwood-worker.log

As you see, generically identical. Yet shenstone does not restart its queues to capture requests from its jobs table, but meadowwood does. No logfiles appear in storage.

So why do some of these queues restart successfully, and a load don't?

Looking at the stackoverflow issue Running multiple Laravel queue workers using Supervisor inspired me to run sudo supervisorctl status and yes I can see a more elaborate explanation of my problem:

shenstone-worker:shenstone-worker_00                               FATAL     too many open files to spawn 'shenstone-worker_00'
shenstone-worker:shenstone-worker_01                               FATAL     too many open files to spawn 'shenstone-worker_01'
shenstone-worker:shenstone-worker_02                               FATAL     too many open files to spawn 'shenstone-worker_02'

As opposed to:

meadowwood-worker:meadowwood-worker_00                             RUNNING   pid 32459, uptime 0:51:52
meadowwood-worker:meadowwood-worker_01                             RUNNING   pid 32460, uptime 0:51:52
meadowwood-worker:meadowwood-worker_02                             RUNNING   pid 32457, uptime 0:51:52

But I still cannot see what I can do to resolve the issue.



via Chebli Mohamed

mardi 29 mars 2022

where is forceScheme function y laravel

I want to work in https app I cant geerate https links whit "url" blade function in some ask question say have use this, but, not works

\Illuminate\Support\Facades\URL::forceScheme('https');


via Chebli Mohamed

Laravel validation rule based on other fields value

I have this radio button

<input class="form-check-input" type="radio" name="discount" value="Yes">
<input class="form-check-input" type="radio" name="discount" value="No" checked>

and this hidden field

 <input type="hidden" name="discount_valid" value="true">

by default this hidden field is true

Now when i'm trying to validate if discount_valid is true then it should submit the form this code is working but i want to add another condition, if discount is No then it should submit the form irrespective of whether discount value is true or false. If discount is Yes and discount_valid is false then form should not submit.

$validator = Validator::make($request->all(), [
            'discount_valid'=>'in:true',
]);                           

                                         


via Chebli Mohamed

lundi 28 mars 2022

realpath(): open_basedir restriction in effect

everyone. I get this error on my shared host. I contact the support and they said that they don't give permission for my account to open_basedir area. (Since it is not an upgraded account) What can I do unless buy for premium version.



via Chebli Mohamed

vendredi 25 mars 2022

How do you run a Laravel 5 project on a computer with PHP v8.1 installed [duplicate]

I saw a Laravel project online and want to execute it on my computer to make it a reference for my upcoming project.

I was trying to install composer dependencies by typing the command composer install in the project root path and received this kind of error:

Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Your lock file does not contain a compatible set of packages. Please run composer update.

  Problem 1
    - sentry/sentry is locked to version 1.11.0 and an update of this package was not requested.
    - sentry/sentry 1.11.0 requires php ^5.3|^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 2
    - spatie/laravel-medialibrary is locked to version 3.18.0 and an update of this package was not requested.
    - spatie/laravel-medialibrary 3.18.0 requires php ^5.5|^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 3
    - fzaninotto/faker is locked to version v1.9.2 and an update of this package was not requested.
    - fzaninotto/faker v1.9.2 requires php ^5.3.3 || ^7.0 -> your php version (8.1.4) does not satisfy that requirement.  Problem 4
    - phpspec/prophecy is locked to version v1.10.3 and an update of this package was not requested.
    - phpspec/prophecy v1.10.3 requires php ^5.3|^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 5
    - phpunit/php-timer is locked to version 1.0.9 and an update of this package was not requested.
    - phpunit/php-timer 1.0.9 requires php ^5.3.3 || ^7.0 -> your php version (8.1.4) does not satisfy that requirement.  Problem 6
    - sebastian/diff is locked to version 1.4.3 and an update of this package was not requested.
    - sebastian/diff 1.4.3 requires php ^5.3.3 || ^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 7
    - sebastian/environment is locked to version 1.3.8 and an update of this package was not requested.
    - sebastian/environment 1.3.8 requires php ^5.3.3 || ^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 8
    - sentry/sentry 1.11.0 requires php ^5.3|^7.0 -> your php version (8.1.4) does not satisfy that requirement.
    - sentry/sentry-laravel 0.7.1 requires sentry/sentry ^1.6.0 -> satisfiable by sentry/sentry[1.11.0].
    - sentry/sentry-laravel is locked to version 0.7.1 and an update of this package was not requested.

Here is my composer.json file. If I'm going to downgrade to fix this problem I just want to ask exactly where?

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "laravelcollective/html": "5.1.*",
        "laracasts/flash": "^1.3",
        "intervention/image": "^2.3",
        "intervention/imagecache": "^2.3",
        "laracasts/utilities": "~2.0",
        "sofa/eloquence": "~5.1@dev",
        "tymon/jwt-auth": "0.5.*",
        "spatie/laravel-medialibrary": "^3.18",
        "rap2hpoutre/laravel-log-viewer": "^0.6.1",
        "zizaco/entrust": "dev-laravel-5",
        "sentry/sentry-laravel": "^0.7.0"
    },
    "require-dev": {
        "barryvdh/laravel-debugbar": "^2.0",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database",
            "app/Lubus"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "allow-plugins": {
            "kylekatarnls/update-helper": true
        }
    }
}

How can I fix this?



via Chebli Mohamed

How do you run a Laravel project with PHP version requirements lower than the currently installed active PHP version [duplicate]

I saw a Laravel project online and want to execute it on my computer to make it a reference for my upcoming project.

I was trying to install composer dependencies by typing the command composer install in the project root path and received this kind of error:

Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Your lock file does not contain a compatible set of packages. Please run composer update.

  Problem 1
    - sentry/sentry is locked to version 1.11.0 and an update of this package was not requested.
    - sentry/sentry 1.11.0 requires php ^5.3|^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 2
    - spatie/laravel-medialibrary is locked to version 3.18.0 and an update of this package was not requested.
    - spatie/laravel-medialibrary 3.18.0 requires php ^5.5|^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 3
    - fzaninotto/faker is locked to version v1.9.2 and an update of this package was not requested.
    - fzaninotto/faker v1.9.2 requires php ^5.3.3 || ^7.0 -> your php version (8.1.4) does not satisfy that requirement.  Problem 4
    - phpspec/prophecy is locked to version v1.10.3 and an update of this package was not requested.
    - phpspec/prophecy v1.10.3 requires php ^5.3|^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 5
    - phpunit/php-timer is locked to version 1.0.9 and an update of this package was not requested.
    - phpunit/php-timer 1.0.9 requires php ^5.3.3 || ^7.0 -> your php version (8.1.4) does not satisfy that requirement.  Problem 6
    - sebastian/diff is locked to version 1.4.3 and an update of this package was not requested.
    - sebastian/diff 1.4.3 requires php ^5.3.3 || ^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 7
    - sebastian/environment is locked to version 1.3.8 and an update of this package was not requested.
    - sebastian/environment 1.3.8 requires php ^5.3.3 || ^7.0 -> your php version (8.1.4) does not satisfy that requirement.
  Problem 8
    - sentry/sentry 1.11.0 requires php ^5.3|^7.0 -> your php version (8.1.4) does not satisfy that requirement.
    - sentry/sentry-laravel 0.7.1 requires sentry/sentry ^1.6.0 -> satisfiable by sentry/sentry[1.11.0].
    - sentry/sentry-laravel is locked to version 0.7.1 and an update of this package was not requested.

Here is my composer.json file. If I'm going to downgrade to fix this problem I just want to ask exactly where?

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "laravelcollective/html": "5.1.*",
        "laracasts/flash": "^1.3",
        "intervention/image": "^2.3",
        "intervention/imagecache": "^2.3",
        "laracasts/utilities": "~2.0",
        "sofa/eloquence": "~5.1@dev",
        "tymon/jwt-auth": "0.5.*",
        "spatie/laravel-medialibrary": "^3.18",
        "rap2hpoutre/laravel-log-viewer": "^0.6.1",
        "zizaco/entrust": "dev-laravel-5",
        "sentry/sentry-laravel": "^0.7.0"
    },
    "require-dev": {
        "barryvdh/laravel-debugbar": "^2.0",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database",
            "app/Lubus"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "allow-plugins": {
            "kylekatarnls/update-helper": true
        }
    }
}

How can I fix this?



via Chebli Mohamed

jeudi 24 mars 2022

Laravel 5.4 Create PDF File barry

I want to Import new library to my project. this is what I want to import

composer require barryvdh/laravel-dompdf

but, my project refuse this package.and this is error what I get

Info from https://repo.packagist.org: #StandWithUkraine
Using version ^1.0 for barryvdh/laravel-dompdf
./composer.json has been updated
Running composer update barryvdh/laravel-dompdf
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires barryvdh/laravel-dompdf ^1.0 -> satisfiable by barryvdh/laravel-dompdf[v1.0.0].        
    - barryvdh/laravel-dompdf v1.0.0 requires illuminate/support ^6|^7|^8|^9 -> found illuminate/support[v6.0.0, ..., v6.20.44, v7.0.0, ..., v7.30.6, v8.0.0, ..., v8.83.5, v9.0.0, ..., v9.5.1] but these were not loaded, likely because it conflicts with another require.


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

And this is my Project Version

Laravel Framework 5.4.36

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  clear-compiled       Remove the compiled class file
  down                 Put the application into maintenance mode
  env                  Display the current framework environment
  help                 Displays help for a command
  inspire              Display an inspiring quote
  list                 Lists commands
  migrate              Run the database migrations
  optimize             Optimize the framework for better performance
  serve                Serve the application on the PHP development server
  tinker               Interact with your application
  up                   Bring the application out of maintenance mode
 app
  app:name             Set the application namespace
 auth
  auth:clear-resets    Flush expired password reset tokens
 cache
  cache:clear          Flush the application cache
  cache:forget         Remove an item from the cache
  cache:table          Create a migration for the cache database table
 config
  config:cache         Create a cache file for faster configuration loading
  config:clear         Remove the configuration cache file
 db
  db:seed              Seed the database with records
 event
  event:generate       Generate the missing events and listeners based on registration
 key
  key:generate         Set the application key
 make
  make:auth            Scaffold basic login and registration views and routes
  make:command         Create a new Artisan command
  make:controller      Create a new controller class
  make:event           Create a new event class
  make:job             Create a new job class
  make:listener        Create a new event listener class
  make:mail            Create a new email class
  make:middleware      Create a new middleware class
  make:migration       Create a new migration file
  make:model           Create a new Eloquent model class
  make:notification    Create a new notification class
  make:policy          Create a new policy class
  make:provider        Create a new service provider class
  make:request         Create a new form request class
  make:seeder          Create a new seeder class
  make:test            Create a new test class
 migrate
  migrate:install      Create the migration repository
  migrate:refresh      Reset and re-run all migrations
  migrate:reset        Rollback all database migrations
  migrate:rollback     Rollback the last database migration
  migrate:status       Show the status of each migration
 notifications
  notifications:table  Create a migration for the notifications table
 queue
  queue:failed         List all of the failed queue jobs
  queue:failed-table   Create a migration for the failed queue jobs database table
  queue:flush          Flush all of the failed queue jobs
  queue:forget         Delete a failed queue job
  queue:listen         Listen to a given queue
  queue:restart        Restart queue worker daemons after their current job
  queue:retry          Retry a failed queue job
  queue:table          Create a migration for the queue jobs database table
  queue:work           Start processing jobs on the queue as a daemon
 route
  route:cache          Create a route cache file for faster route registration
  route:clear          Remove the route cache file
  route:list           List all registered routes
 schedule
  schedule:run         Run the scheduled commands
 session
  session:table        Create a migration for the session database table
 storage
  storage:link         Create a symbolic link from "public/storage" to "storage/app/public"
 vendor
  vendor:publish       Publish any publishable assets from vendor packages
 view
  view:clear           Clear all compiled view files

how I can to use this Package ? someone said laravel 5 can use this package. but, in my project can't install this package. someone said, I must upgrade my Laravel Version to Laravel ^6. someone said, laravel 5.7 can run this project. now I'm confuse and stuck in this proses.



via Chebli Mohamed

mardi 22 mars 2022

Laravel Framework Upgrade 5.4 -> ^6|^7|^8

I want to Update my Laravel Project. And I already run this code on my project terminal

composer update laravel/framework

but I just get Info Like this

Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Package jakub-onderka/php-console-color is abandoned, you should avoid using it. Use php-parallel-lint/php-console-color instead.                                                                                                                 
Package jakub-onderka/php-console-highlighter is abandoned, you should avoid using it. Use php-parallel-lint/php-console-highlighter instead.                                                                                                     
Package maddhatter/laravel-fullcalendar is abandoned, you should avoid using it. No replacement was suggested.
Package mtdowling/cron-expression is abandoned, you should avoid using it. Use dragonmantank/cron-expression instead.    
Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
Package fzaninotto/faker is abandoned, you should avoid using it. No replacement was suggested.
Package phpunit/php-token-stream is abandoned, you should avoid using it. No replacement was suggested.
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Generating optimized autoload files
Carbon 1 is deprecated, see how to migrate to Carbon 2.
https://carbon.nesbot.com/docs/#api-carbon-2
    You can run ".\vendor\bin\upgrade-carbon" to get help in updating carbon and other frameworks and libraries that depend on it.
33 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> Illuminate\Foundation\ComposerScripts::postUpdate
> php artisan optimize
Generating optimized class loader
The compiled services file has been removed.

and this is my composer.json

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "almasaeed2010/adminlte": "~3.1",
    "ecasanes/laravel-google-calendar-php-6": "^1.1",
    "guzzlehttp/guzzle": "^7.4",
    "intervention/image": "^2.7",
    "laravel/framework": "5.4.*",
    "laravel/tinker": "~1.0",
    "maddhatter/laravel-fullcalendar": "^1.3",
    "uxweb/sweet-alert": "^2.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.7"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"scripts": {
    "post-root-package-install": [
        "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ],
    "post-install-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postInstall",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "php artisan optimize"
    ]
},
"config": {
    "preferred-install": "dist",
    "sort-packages": true,
    "optimize-autoloader": true
}}

I want to upgrade my Project min to Laravel ^6 to use composer require barryvdh/laravel-dompdf

but after Edit "laravel/framework": "^8.0" and "phpunit/phpunit": "^9.0", I got error message like this

Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires phpunit/phpunit ^9.0, found phpunit/phpunit[9.0.0, ..., 9.5.19] but the package is fixed to 5.7.27 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
  Problem 2
    - laravel/framework[v8.0.0, ..., v8.83.5] require monolog/monolog ^2.0 -> found monolog/monolog[2.0.0, ..., 2.4.0] but the package is fixed to 1.27.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - Root composer.json requires laravel/framework ^8.0 -> satisfiable by laravel/framework[v8.0.0, ..., v8.83.5].      

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

I already stuck in this step. I can't move to next step from my project. thank you



via Chebli Mohamed

foreach with config data file laravel

I´m traying create rows check if in my product array have any product in config file. If in my array product have any value that coincide with my config file, in this column put a ex image.

in my config file y have this:

return [
    'productos' => [
        "DFDAP20" => [
            'label' => 'DFDAP20',
            'text'  => 'DEPURADOR FLUJO DIRECTO AQUALUXE PREMIUM 2.0'
        ],
        "DDP20" => [
            'label' => 'DDP20',
            'text'  => 'DESINCRUSTADOR DCALUXE PRO 2.0'
        ],
        /* RENOMBRADO A DIA 02/12/2020 POR EQUIPO DE GENERADOR DE HIDROGNEO
        "DESDPU" => [
            'label' => 'DESDPU',
            'text'  => 'DESINFECCIÓN DE DEPURADORA'
        ],*/
        "EGENO" => [
            'label' => '1110',
            'text'  => 'EQUIPO GENERADOR DE HIDRÓGENO'
        ],
        "FAOS" => [
            'label' => 'FAOS',
            'text'  => 'FUENTE DE AGUA OSMOTIZADA'
        ],
        "G4V" => [
            'label' => 'G4V',
            'text'  => 'GRIFO DE CUATRO VÍAS'
        ],
        "SLOXIWATER" => [
            'label' => '1133',
            'text'  => 'SISTEMA DE LIMPIEZA OXI WATER'
        ],
        "JUEGOFILTROS" => [
            'label' => 'JUEGOFILTROS',
            'text'  => 'JUEGO DE FILTROS'
        ]
    ]
];

in my product array i have this:

Array
(
    [0] => Array
        (
            [codigo] => 41
            [ref] => 1110
            [nombre] => EQUIPO GENERADOR DE HIDROGENO HYDROGEN 333 TECH
            [precio] => 999.99
            [cantidad] => 1
            [id_precontrato] => 14900
        )

    [1] => Array
        (
            [codigo] => 129
            [ref] => 674
            [nombre] => PIZZA  PAN NW407 DORADO
            [precio] => 39.48
            [cantidad] => 1
            [id_precontrato] => 14900
        )

    [2] => Array
        (
            [codigo] => 291
            [ref] => 956
            [nombre] => COLECCIÓN COCINA INTERNACIONAL, ALTA GASTRONOMÍA INTERNACIONAL, COCINA EQUILIBRADA Y SALUDABLE. HD - 3D, 2 TOMOS+1DVD (GD)
            [precio] => 140.09
            [cantidad] => 1
            [id_precontrato] => 14900
        )

)

and in my blade i´m doing a foreach that check if any value it´s in array:

@foreach(config('instalacion')['productos'] as $key => $value)
          <div class="cajas2" style="height: 25px; border:1px solid black; position: relative;">
            @if(in_array($value["text"], $productos))
              <img src="" style="width: 16px; position: absolute; left: 40%; top: 50%; transform: translateY(-50%); -webkit-transform: translateY(-50%);">
            
            @else
              @php
                echo "eee";
                print_r($productos);
              @endphp
            @endif
          </div>
        @endforeach

but always get in else...

I don´t know that i´m doing wrong, but i can´t solve this problem.

Thanks for readme and sorry for my english



via Chebli Mohamed

Pass date in url in Laravel

I have this Link in my view

 <a href="">
 Link
 </a>

when i click on this link this url is called

detail?id=2&03-22-2022

getting this error :

Could not parse '03-22-2022': DateTime::__construct(): Failed to parse time string (03-22-2022) at position 0 (0): Unexpected character

but if my url is

detail?id=03%2F22%2F2022

then it is working how can i urlencode in laravel

Thanks



via Chebli Mohamed

lundi 21 mars 2022

groupby Not working with laravel and PostreSQL

I am using PostreSQL . when I try to use groupBy in my laravel query. It showing Grouping error:

$available_Area = DB::table('area AS a')
->select('a.*','a.name as a_name', 'f.name as f_name', 'zc.code as zc_code') 
->join('transaction AS t', 't.f_id', '=', 'a.f_id')
->leftjoin('facility AS f', 'f.id', '=', 't.f_id')
->leftJoin('transaction_detail AS td', 'td.t_id', '=', 't.id')
->leftJoin('zone_component AS zc', 'zc.id', '=', 'td.comp_id') 
->whereNotIn('a.id', DB::table('transaction_detail AS td')
            ->select('zc.a_id')
            ->join('zone_component AS zc', 'zc.id', '=', 'td.comp_id')                  
            ->whereIn('td.card_type', ['C_OVA','C_M21'])
                            ->where('td.t_id', $url)
                        )
            ->groupBy('a.id')
->where('t.id', @$url) 
->get();

Then I tried with DISTINCT ON It showing syntax error

$available_Area = DB::table('area AS a')
->select('a.*','a.name as a_name', 'f.name as f_name', 'zc.code as zc_code', DB::raw("DISTINCT ON(a.id)")) 
->join('transaction AS t', 't.f_id', '=', 'a.f_id')
->leftjoin('facility AS f', 'f.id', '=', 't.f_id')
->leftJoin('transaction_detail AS td', 'td.t_id', '=', 't.id')
->leftJoin('zone_component AS zc', 'zc.id', '=', 'td.comp_id') 
->whereNotIn('a.id', DB::table('transaction_detail AS td')
            ->select('zc.a_id')
            ->join('zone_component AS zc', 'zc.id', '=', 'td.comp_id')                  
            ->whereIn('td.card_type', ['C_OVA','C_M21'])
                            ->where('td.t_id', $url)
                        )
->where('t.id', @$url) 
->get();


via Chebli Mohamed

Redirect after registration in Laravel

I am using laravel 5.5

Column A Column B
Cell 1 Cell 2
Cell 3 Cell 4

I want to change the redirect of a billing page to the dashboard after a successful registration. I have changed the Protected $redirectTo = '/dashboard'; but it always take me to the billing page

I tried changing the redirect to the dashboard but it wants the user to fill the billing form before they can access the dashboard. I want the user to skip that billing process



via Chebli Mohamed

Whic one is best and most widely used? [closed]

I am really confused what to choose as a backend language either i should go with php or .net,node . kindly share your knowlege with me i shal be very gratefull to you guys. Thanks which one is better now these days?



via Chebli Mohamed

dimanche 20 mars 2022

Use Laravel query builder inside WherenotIn

I have the following query and i want to know if this is possible in laravel's querybuilder:

SELECT "a".*
FROM   "area" AS "a"
       INNER JOIN "transaction" AS "t"
               ON "t"."f_id" = "a"."f_id"
WHERE  "t"."id" = 'c5931409-37b7-4248-b958-831edaae4075'
       AND "a"."id" NOT IN(SELECT "zc"."a_id"
                           FROM   "transaction_detail" AS td
                                  INNER JOIN "zone_component" AS "zc"
                                          ON "zc"."id" = "td"."comp_id"
                           WHERE
           td."t_id" = 'c5931409-37b7-4248-b958-831edaae4075'
           AND td."card_type" IN ( 'C_OVA', 'C_M21' ));  


via Chebli Mohamed

vendredi 18 mars 2022

Laravel 5.4 Undefined variable error - problem with controller?

I'm getting this error: Undefined variable: sales_rep_names (View: C:\wamp64\www\VLCMRenewals\resources\views\search\index.blade.php)

when I try adding a new search dropdown in my blade. This is the new code I've added that's causing the problem:

                
                    <!-- adding sales rep placeholder
                    Can we make this a drop-down menu?

                    
                    need to make sure "name=" is correct -->
                    <div class="form-group col-md-4">
                    <label class="mr-sm-2" >Sales Representative</label>
                    <select class="custom-select mr-sm-2" name="primary_sales_rep">
                    <option selected></option>
                        @if(count($sales_rep_names) >0)
                            @foreach ($sales_rep_names as $sales_rep_name)
                                <option value=''></option>
                            @endforeach
                        @endif
                        </select>
                    </div>

And here's an example of a dropdown that DOES work (I copied the format):


<div class="form-group col-md-4" >
<label class="mr-sm-2" >Manufacturer Name</label>
<select class="custom-select mr-sm-2" name="company">
<option selected></option>
@if(count($manufacturer_names) >0)
@foreach ($manufacturer_names as $manufacturer_name)
<option value=''></option>
@endforeach
@endif
</select>
</div>

Lastly, here's the code I have my in Controller (manufacturer and customer both work):

    public function index()
    {
        // will need to add Sales Rep here
        $customer_names = DB::table('dbo.contract_view')
            ->distinct()
            ->orderBy('Customer_Name','asc')
            ->get(['Customer_Name']);
        $manufacturer_names = DB::table('dbo.contract_view')
            ->distinct()
            ->orderBy('Manufacturer_Name','asc')
            ->get(['Manufacturer_Name']);

        // when I tested with product part number it also gave me an error with index.blade.php. maybe this is the wrong spot?
        $sales_rep_names = DB::table('dbo.contract_view')
        ->distinct()
        ->orderBy('Primary_Sales_Rep','asc')
        ->get(['Primary_Sales_Rep']);
        return view('search.index', ['customer_names' => $customer_names], ['manufacturer_names' => $manufacturer_names], ['sales_rep_names' => $sales_rep_names]);
        
    }

Any advice?



via Chebli Mohamed

Throwing fatal error "'Class 'Breadcrumbs' not found" in Laravel 5.2

I converted my application from Laravel 5.0 to Laravel 5.2. I created laravel 5.2 project through the command prompt. And copied model, view and controllers from old application. Next gave full permission to storage folder. Now the issue is, while run the project after login its throwing fatal error like "'Class 'Breadcrumbs' not found". How can I fix that?



via Chebli Mohamed

jeudi 17 mars 2022

Join one to many relationship tables and return all record using laravel eloquent

I have two tables users and posts. users has one to many relation with posts table. Post has 'type' column. This type may be sports,art, politics... etc.

users table - id, name, account_type, email

account_type may be active, test, blacklisted ... etc

posts table - id, user_id, name, type, date

Here I need to get all 'politics' posts of all 'active' players posted after a particular 'date'

How to get this using laravel eloquent way?

I have below function in User model class

public function post()
{
    return $this->hasMany( Post::class );
}


via Chebli Mohamed

mercredi 16 mars 2022

How can I query all, orderby, and paginate?

enter image description here

I don't know what is wrong with my query, but the count is clearly wrong, it kept showing as 1912 when my total records are 12363


I tried

to change this line under my default case

$q = Visitor::where('created_at', '<', now());

to

$q = Visitor::all(); but I got error; 

Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.


switch ($interval) {
    case 'day':
    $q = Visitor::where('created_at', '>', now()->today());
    break;
    case 'week':
    $q = Visitor::where('created_at', '>', now()->subWeek());
    break;
    case 'month':
    $q = Visitor::where('created_at', '>', now()->subMonth());
    break;
    case 'year':
    $q = Visitor::where('created_at', '>', now()->subYear());
    break;
    case 'last':
    $q = Visitor::where('created_at', '>', $last);
    break;
    default:
    $q = Visitor::where('created_at', '<', now());
    break;
}


$visitors = $q->orderBy('created_at', 'desc')->paginate(15);

http://app.test/visitor?interval=year

I got 1912 - correct 👍🏽


http://app.test/visitor

I got 1912 - not correct ❌, It should query all since the interval is not specified.

If I do :

dd(count(Visitor::all()));

I got 12363 so that should be the right value.

Please let me know if you spot what I missed



via Chebli Mohamed

Open web page in Iframe Redsys API

I´m traying integrate Redsys API in my app. All Api it´s integrated but my question it´s that in my project i need open form redsys in modal with iframe. In my controller i have all my code to create a petition to servers and return a form:

<form action="https://sis.redsys.es/sis/realizarPago" method="post" id="redsys_form" name="redsys_form" >
            <input type="hidden" name="Ds_MerchantParameters" value="eyJEU19NRVJDSEFOVF9BTU9VTlQiOjEzOTkwMCwiRFNfTUVSQ0hBTlRfT1JERVIiOiIyMjAyMDIyMDAwMzciLCJEU19NRVJDSEFOVF9NRVJDSEFOVENPREUiOiI2NjgyODc5OSIsIkRTX01FUkNIQU5UX0NVUlJFTkNZIjoiOTc4IiwiRFNfTUVSQ0hBTlRfVFJBTlNBQ1RJT05UWVBFIjoiMCIsIkRTX01FUkNIQU5UX1RFUk1JTkFMIjoiMSIsIkRTX01FUkNIQU5UX1BBWU1FVEhPRFMiOiJUIiwiRFNfTUVSQ0hBTlRfTUVSQ0hBTlRVUkwiOiJodHRwczpcL1wvaW50cmFuZXQuZ3J1cG9kZWx1eGUuY29tXC9yZWRpcmVjY2lvbmVzXC9ub3RpZmljYXRpb24/aWRlbj1kMWYyN2Q0YWVlMGFjN2E3JmRhdGU9TWpBeU1pMHdNeTB4TmlBeE5qb3lNVG8xTlElM0QlM0QiLCJEU19NRVJDSEFOVF9VUkxPSyI6Imh0dHBzOlwvXC9pbnRyYW5ldC5ncnVwb2RlbHV4ZS5jb21cL2FkbWluXC9yZWRyZWRzeXNcL3VybG9rP2lkZW49ZDFmMjdkNGFlZTBhYzdhNyZkYXRlPU1qQXlNaTB3TXkweE5pQXhOam95TVRvMU5RJTNEJTNEIiwiRFNfTUVSQ0hBTlRfVVJMS08iOiJodHRwczpcL1wvaW50cmFuZXQuZ3J1cG9kZWx1eGUuY29tXC9hZG1pblwvcmVkcmVkc3lzXC91cmxrbz9pZGVuPWQxZjI3ZDRhZWUwYWM3YTcmZGF0ZT1NakF5TWkwd015MHhOaUF4TmpveU1UbzFOUSUzRCUzRCIsIkRTX01FUkNIQU5UX01FUkNIQU5UTkFNRSI6IkVESUNJT05FUyBHUlVQTyBERUxVWEUiLCJEU19NRVJDSEFOVF9USVRVTEFSIjoiTUFSVElORVogSklNRU5FWiBNQVJJQSBMVUlTQSIsIkRTX01FUkNIQU5UX1BST0RVQ1RERVNDUklQVElPTiI6IlBhZ28gY29tcGxldG8ifQ=="/>
            <input type="hidden" name="Ds_Signature" value="jWWSm5xrRjxo0LoD4joa6mrBgw4rMg1t8/2nTWAjgjs="/>
            <input type="hidden" name="Ds_SignatureVersion" value="HMAC_SHA256_V1"/>
            <input type="submit" name="btn_submit" id="btn_submit" value="Send"  >
        </form>
    <script>document.forms["redsys_form"].submit();</script>

this code i need open in my iframe by POST method, but src it´s invalid... In my controller i have this:

public function store(Request $request)
    {
        $importe = $request->get('importe');
        $nomape = $request->get('nomape');

        $desc = 'Pago completo';
        $importe = str_replace(',', '.', $importe);


        $pago = PagoTarjeta::create([
            'iden'   => bin2hex(random_bytes(8)),
            'nomape' => $nomape,
            'importe'=> $importe,
            'desc'   => $desc,
            'id_empleado' => auth()->user()->id,
            'id_estado' => 1,
            'id_precontrato' => $request->has('_id_precontrato') ? $request->_id_precontrato : null
        ]);

        /*if(!$pago) {
            return redirect()->route('admin.pago_tarjeta.index')->withErrors('pago_tarjeta', 'No se ha podido crear la transacción correctamente..');
        }*/

        $pago->update(['norder' => config('redsys.serie.PT').str_pad($pago->id, 10, 0, STR_PAD_LEFT)]);

        try {
            $key = config('redsys.key');

            Redsys::setAmount($importe);
            Redsys::setOrder($pago->norder);
            Redsys::setMerchantcode(config('redsys.merchantcode')); //Reemplazar por el código que proporciona el banco
            Redsys::setCurrency(config('redsys.currency'));
            Redsys::setTransactiontype('0');
            Redsys::setTerminal('1');
            Redsys::setMethod('T'); //Solo pago con tarjeta, no mostramos iupay
            $esto = Redsys::setNotification(route('redirecciones.notification', [
                'iden' => $pago->iden,
                'date' => base64_encode($pago->created_at)
            ])); //Url de notificacion
            Redsys::setUrlOk(route('admin.redredsys.urlok', [
                'iden' => $pago->iden,
                'date' => base64_encode($pago->created_at)
            ])); //Url OK
            Redsys::setUrlKo(route('admin.redredsys.urlko', [
                'iden' => $pago->iden,
                'date' => base64_encode($pago->created_at)
            ])); //Url KO
            Redsys::setVersion(config('redsys.version'));
            Redsys::setTradeName(config('redsys.tradename'));
            Redsys::setTitular($nomape);
            Redsys::setProductDescription($desc);
            Redsys::setEnviroment('live'); //Entorno test

            $signature = Redsys::generateMerchantSignature($key);
            $merchantSignature = Redsys::setMerchantSignature($signature);

            $form = Redsys::executeRedirection();
        }
        catch(Exception $e){
            echo $e->getMessage();
        }

        return $form;
    }

i need open this web in my modal:

enter image description here

This img it´s sending my form with POST and PHP not javascript.

Thanks to read me, and sorry for my bad english



via Chebli Mohamed

Error msg Symfony\Component\Process\Exception\RuntimeException TTY mode is not supported on Windows platform

Hi guys I have been having various error messages with my laravel installation. Basically, These errors occur mostly when I run commands related to Database. The below error msg occurred after I ran the "PHP artisan DB" command. Another command that triggers another type of error is "PHP artisan DB:seed.

And help will be helpful

Symfony\Component\Process\Exception\RuntimeException

TTY mode is not supported on Windows platform.

at D:\LARAVEL PROJECT 1\laravel-api\vendor\symfony\process\Process.php:1059 1055▕ */ 1056▕ public function setTty(bool $tty) 1057▕ { 1058▕ if ('\' === \DIRECTORY_SEPARATOR && $tty) { ➜ 1059▕ throw new RuntimeException('TTY mode is not supported on Windows platform.'); 1060▕ } 1061▕ 1062▕ if ($tty && !self::isTtySupported()) { 1063▕ throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');

1 D:\LARAVEL PROJECT 1\laravel-api\vendor\laravel\framework\src\Illuminate\Database\Console\DbCommand.php:41 Symfony\Component\Process\Process::setTty()

2 D:\LARAVEL PROJECT 1\laravel-api\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:36 Illuminate\Database\Console\DbCommand::handle() PS D:\LARAVEL PROJECT 1\laravel-api>



via Chebli Mohamed

mardi 15 mars 2022

ERROR!!! Illuminate\Database\QueryException SQLSTATE[42S02]: Base table or view not found: 1146 Table

I ran into an error and I have not figured out how to resolve it alone. so I opted to get help from this community. I will explain a bit though the screenshots are provided.

I created a new laravel project, created a database, users table, connected the env file with the required info, created a factory, seeders with the artisan make: command

when I tried generating the fakers with the help of factory and seeders for my student table, after running the command "PHP artisan DB:seed" -> I got the error msg

Any help will be appreciated 🙏

Env File

Student_Table

Student_Factory

Student_factory

Error_msg

Link Based on error msg

Link based on error msg 2

Link based on error msg 3

[Link based on error msg 4][9]

[Database_seeder file][10]



via Chebli Mohamed

get a value from 1 to 5 with stars

i'm working on a ratings project, where I need to get values from 1 to 5 represented with stars. in my code I already have the design working.

How can I get a value to then save with POST?

when marking the stars i need to obtain a value and then save it with the POST method.
PD: i am working with laravel 8

const ratingStars = [...document.getElementsByClassName("rating__star")];
const ratingResult = document.querySelector(".rating__result");

printRatingResult(ratingResult);

function executeRating(stars, result) {
   const starClassActive = "rating__star fas fa-star";
   const starClassUnactive = "rating__star far fa-star";
   const starsLength = stars.length;
   let i;
   stars.map((star) => {
      star.onclick = () => {
         i = stars.indexOf(star);

         if (star.className.indexOf(starClassUnactive) !== -1) {
            printRatingResult(result, i + 1);
            for (i; i >= 0; --i) stars[i].className = starClassActive;
         } else {
            printRatingResult(result, i);
            for (i; i < starsLength; ++i) stars[i].className = starClassUnactive;
         }
      };
   });
}

function printRatingResult(result, num = 0) {
   result.textContent = `${num}/5`;
}

executeRating(ratingStars, ratingResult);
@import "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css";
body {
   height: 100vh;
   display: grid;
   place-items: center;
   overflow: hidden;
}

.rating {
   position: relative;
   width: 180px;
   background: transparent;
   display: flex;
   justify-content: center;
   align-items: center;
   gap: .3em;
   padding: 5px;
   overflow: hidden;
   border-radius: 20px;
   box-shadow: 0 0 2px #b3acac;
}

.rating__result {
   position: absolute;
   top: 0;
   left: 0;
   transform: translateY(-10px) translateX(-5px);
   z-index: -9;
   font: 3em Arial, Helvetica, sans-serif;
   color: #ebebeb8e;
   pointer-events: none;
}

.rating__star {
   font-size: 1.3em;
   cursor: pointer;
   color: #dabd18b2;
   transition: filter linear .3s;
}

.rating__star:hover {
   filter: drop-shadow(1px 1px 4px gold);
}
 <div class="rating">
          <span class="rating__result"></span> 
         <i class="rating__star far fa-star"></i>
         <i class="rating__star far fa-star"></i>
         <i class="rating__star far fa-star"></i>
         <i class="rating__star far fa-star"></i>
         <i class="rating__star far fa-star"></i>
      </div>


via Chebli Mohamed

lundi 14 mars 2022

Testing when using the Eloquent "on" method

I am writing the test now.

I have multiple databases and am switching between them using the "on" method.

Here is the code I want to test. I've abbreviated a few things. Post::on("connection2")->get(); and return api

in postApiTest.php

//create any post use factory in code

//debug
Post::on("connection2")->count() // return 0
Post::on("connection_default")->count()// return many post

$response->assertOk()  //200
            ->assertJsonCount(10) // but return 0
            ->assertJsonFragment([ // but dont have json
                'title' => 'title',
            ]);

I want to test the number of pieces coming back from the API, but it is zero

Use the same connection or Mock methods or Is there a better way?



via Chebli Mohamed

How to edit image in Laravel 5.7?

I inserted the image in my database, now I am trying to edit the images and the edited image should be deleted from my folder and a new image should be updated there. Could you please help me where I am mistaking?

Here is my Controller.php file

 public function edit($slider)
{
    $property=Property::all();
    $slider = Slider::find($slider);
    $data = ['property'=>$property, 'slider'=>$slider];
    return view('admin.slider.edit', $data);
}

 public function update(Request $r, $id)
{
       $slider=Slider::find($id);
       if( $r->hasFile('slider_thumb')){ 

        $thums               = $r->slider_thumb;
        $slider_thumb = uniqid($chr).'.'.$thums->getClientOriginalExtension();
        $img = Image::make($thums->getRealPath());
        $img->resize(204, 107, function ($constraint) {
            $constraint->aspectRatio();          
        });
        $thumbPath = public_path().'/slider_img/'.$slider_thumb;

        if (file_exists($thumbPath)) {
            $this->removeImage($thumbPath);
        } 
        $img->save($thumbPath);
        $optimizerChain = OptimizerChainFactory::create();
        $optimizerChain->optimize($thumbPath);
        $slider_thumbimg = $slider_thumb;

        }else{
            $slider_thumb = NULL;
        }
        $slider->property_id = $r->property_id;
        $slider->slider_image=$slider_imageimg;
        $slider->save();
       return redirect('/admin/slider');
    }

}

here is my HTML file

            <form class="form-horizontal" method="POST" action="" enctype="multipart/form-data">
            @csrf
            @method('PUT')

@if($slider->slider_image    == NULL or $slider->slider_image == '')
                                            <img src="" style="width: 100px; height: 100px;">
                                            @else
                                            <img src="" style="width: 100px; height: 80px;">
                                            @endif
                                            <input type="file" name="slider_image" value="">

                <div class="form-group">
                    <div class="col-sm-12 text-right">
                        <button type="submit"  class="btn btn-info">
                            <i class="fa fa-check"></i> Save
                        </button>
                    </div>
                </div>
            </form>


via Chebli Mohamed

How to display the name of the agent. Laravel 8

I'm new to laravel. I have created a foreign key. what I am trying to do is to display the name of the agents according to the agents_id which is the foreign key. I can only display the agents_id. when I put "$rapport->agents_id->nom" it doesn't work. I have this error.

ErrorException Attempt to read property "nom" on int (View: C:\wamp64\www\SET\resources\views\rapport\index.blade.php)

please help me



via Chebli Mohamed

dimanche 13 mars 2022

How can I redirect html codes to controller in Laravel?

This is my code

<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;
use Auth;

class SideNavDeliGroceryComposer
{
    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $navigations = [
            'dashboard' => [
                'title' => 'Dashboard',
                'url' => 'deligrocery.dashboard.view',
                'icon' => 'delirush-am-dashboard',
                'permission_for' => 'dashboard'
            ],
            'customers' => [
                [
                    'title' => 'Customers',
                    'url' => 'deligrocery.customer.view',
                    'icon' => 'delirush-am-customers',
                    'permission_for' => 'customer'
                ], [
                    'title' => 'Orders',
                    'url' => 'deligrocery.customer.order-management.view',
                    'icon' => 'delirush-am-orders',
                    'permission_for' => 'order'
                ]
            ],
            'delivery' => [
                [
                    'title' => 'Rushers',
                    'url' => 'deligrocery.delivery.rusher.view',
                    'icon' => 'delirush-am-rushers',
                    'permission_for' => 'rusher'
                ], [
                    'title' => 'Job Order Management',
                    'url' => 'deligrocery.delivery.job-order.view',
                    'icon' => 'delirush-am-delivery',
                    'permission_for' => 'job-order'
                ]
            ],
            'grocery_partner' => [
                [
                    'title' => 'Partner Management',
                    'url' => 'deligrocery.grocery-partner.partner-manager.view',
                    'icon' => 'fa-solid fa-store',
                    // 'icon' => 'delirush-am-food-partners',
                    'permission_for' => 'rusher'
                    
                ]
            ],
            'service_settings' => [
                [
                    'title' => 'Delivery Service Configuration',
                    'url' => 'deligrocery.delivery_service_settings.view',
                    'icon' => 'delirush-am-delivery-fee',
                    'permission_for' => 'delivery-service-configuration'
                ]
            ],
            'finance' => [
                [
                    'title' => 'Finance Management',
                    'url' => 'deligrocery.finance.merchant-partner-commission-report.view',
                    'icon' => 'delirush-am-finance',
                    'permission_for' => 'finance'
                ]
            ],
            'Tools' => [
                [
                    'title' => 'Category Type Management',
                    'url' => 'deligrocery.tools.category-type.view',
                    'icon' => 'delirush-am-finance',
                    'permission_for' => 'finance'
                ]
            ],
        ];
        
        // $navs = ['customers' => [],'delivery' => []];
        // $permissions = Auth::guard('admin')->user()->getAllPermissions()->groupBy('permission_for');
        // foreach ($permissions as $permissionKey => $permission) {
        //     foreach($navigations as $navKey => $navigation) {
        //         $permissionFors = array_column($navigation, 'permission_for');
        //         $check = array_search($permissionKey, $permissionFors);
        //         if($check !== false) {
        //             array_push($navs[$navKey], $navigation[$check]);
        //         }
        //     }
        // }
        
        $view->with([
            'navs' => $navigations,
            'current' => request()->route()->getName()
        ]);
    }
}

I want to put this code <i class="fa-solid fa-store"></i> inside array in 'icon' label



via Chebli Mohamed

Laravel relationships and storing data

I am new to laravel i have to store cv_id and job_id and user_id in a table in the DB. So This is my Schema cv

 Schema::create('cv', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
             $table->string ('FName') ;
            $table->date('PrefJobEnd');
            $table->integer('WorkExp');
            $table->string('fileCV');
            $table->timestamps();
        });
    }

User Schema

 Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('status')->default(1);
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();

Jobs Schema:

  Schema::create('jobs', function (Blueprint $table) {
            $table->id();
              $table->string('title');
            $table->string('logo');
             $table->integer('WorkExp');
            $table->string('Company');
            $table->string('salary');
        
            $table->timestamps();

I create a new table to collect the ids of each of them called Job application table:

 Schema::create('job_applications', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');        
        $table->unsignedBigInteger('cv_id');
        $table->unsignedBigInteger('job_id');
        $table->timestamps();
    });

Then I specified some relationships in models

User model:

public function cv()
{
    return $this->hasOne('App\Models\cv');
}

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

JobApplication Model;

     public function cv()
        {
             return $this->belongsTo(cv::class, 'user_id');
    
        }
        public function Job()
        {
             return $this->belongsTo(Job::class, 'Job_id');
    
        }

cv model:

  public function Job()
    {
         return $this->hasMany(Job::class, 'user_id');

    }


    public function User()
    {
         return $this->hasMany(USer::class, 'user_id');

    }

}

job model:

  protected $primarykey ='id';
    protected $table ='jobs';

     //user post piviot for savedJobs
     public function User()
     {
         return $this->hasMany('App\Models\User');
     }
 
     
     public function deadlineTimestamp()
     {
        //  return Carbon::parse($this->deadline)->timestamp;
     }
    
  
     public function cv()
    {
         return $this->belongsTo(cv::class, 'user_id');

    }

I am trying to store ids of user, job and cv with following code in the controller; The error

Creating default object from empty value

    public function applyJob(Request $request,$id)



    {
         
        
              
        $application= new JobApplication;
        $jobs = Job::find($request->job_id);
        $jobs->job_id = $id;

  $users = User::find($request->user);
    $users->user_id = $id;


        $cv=cv::all( );
    
        $cv =cv::where ($users.'user_id','=',$cv.'user_id');
        $cv->cv_id = $id;

      

 //    dd($user);
         
       

        $ratings->save();
        
      


    //     return redirect('/')->with('success','well vvvvdscs');

also i tried this one the error was "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'cv_id' cannot be null (SQL: insert into job_applications (user_id, job_id, cv_id, updated_at, created_at) values (4, 1, ?, 2022-03-13 10:46:44, 2022-03-13 10:46:44))"

//     // $jobs = Job::find($request->job_id);
//     // $cv = cv::find($request->cv_id);
//     // $user = User::find(auth()->user()->id);
//     // $application = new JobApplication;
//     // $application->user_id = auth()->user()->id;
//     // $application->job_id = $request->job_id;
//     // $application->cv_id = $request->cv_id;
//     // $application->save();
//     // dd($application);

   

}

So any one can tell me a way or what is wrong in my code?



via Chebli Mohamed

vendredi 11 mars 2022

Select multiple dates in the mutiple date selelect picker

Im using laravel. I have saved multiple dates using multiple date selector. so now i need to select those saved values in that date picked when loading screen again. my date picker created like this.


<input type="text" id="closed_dates" name="closed_dates" class="form-control date"/>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>

<script>
        $('#closed_dates').datepicker({
            multidate: true
        });
</script>

it has saved value in the database like this format,

03/01/2022,03/02/2022,03/09/2022,03/10/2022,03/11/2022

so when loading my page, values pass from the controller. i need to select those dates in that date picker on the page load. how can i do it?



via Chebli Mohamed

jeudi 10 mars 2022

modify the default login in laravel

i need to modify the default login, (email and password). I must use a field other than email to make the login

User Model:

  protected $fillable = [
    'name',
    'email',
    't_matricula',
    'matricula',
    'number',
    'password',
];

i could use the Number field as data to login, where should I modify to use Number instead of Name?



via Chebli Mohamed

Laravel Spatie - Custom Attribute value when audit log via modal

on my modal, I have two functions which I have used to log the data when it has been changed. those are below.

namespace App\Models;

use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Contracts\Activity;
use Illuminate\Support\Facades\Auth;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Receivinglogentry extends Model
{
    use HasFactory;
    use LogsActivity;

    protected $fillable = [
        'status',
        'amt_shipment',
        'container',
        'po',
        'etd_date',
        'eta_date',
    ];

    protected $casts = [
        'po_ref' => 'json',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()->logOnly(['*'])->logOnlyDirty();
    }

    public function tapActivity(Activity $activity,string $eventName)
    {
        $current_user = Auth::user()->name;
        $event        = $activity->attributes['event'];
        $data         = $activity->relations['subject']->attributes['container'];
        $masterID     = $activity->relations['subject']->attributes['id'];

        $activity->description   = "{$current_user} has {$event} Container : {$data}";
        $activity->causer_name   = $current_user;
        $activity->master_id     = $masterID ;
        $activity->log_name      = 'Receivinglogentry';
    }
}

fillable data status has been stored as an integer value. but I have to log it as a string value something like PENDING or ACTIVE. any recommendation to log attributes customizably is appricated.



via Chebli Mohamed

mercredi 9 mars 2022

I'm trying to change Larabel's DB from Oracle to MariaDB, but I get the following error

Assumptions and what we want to achieve

I'm trying to change Larabel's DB from Oracle to MariaDB, but I get the following error

Problem/error message being encountered

[2022-03-10 09:05:14] staging.ERROR: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '1,'M',1,0)) story_one_count, SUM(DECODE(stat_study_log.log_type, 'P', CEIL(fo...' at line 1 (SQL: select SUM(DECODE(stat_study_log.log_type, 'P',1,'M',1,0)) story_one_count, SUM(DECODE(stat_study_log.log_type, 'P', CEIL(fox_contents.play_time / 80), 'M', CEIL(fox_contents.play_time / 80), 0)) story_one_point, SUM(DECODE(stat_study_log.log_type, 'P', fox_contents.play_time, 'M', fox_contents.play_time, 0)) story_one_time, SUM(DECODE(stat_study_log.log_type, 'A', 1, 0)) story_auto_count, SUM(DECODE(stat_study_log.log_type, 'A', CEIL(fox_contents.play_time / 80), 0)) story_auto_point, SUM(DECODE(stat_study_log.log_type, 'A', fox_contents.play_time, 0)) story_auto_time, SUM(DECODE(stat_study_log.log_type, 'S', 1, 0)) song_one_count, SUM(DECODE(stat_study_log.log_type, 'S', CEIL(fox_contents.play_time / 80), 0)) song_one_point, SUM(DECODE(stat_study_log.log_type, 'S', fox_contents.play_time, 0)) song_one_time, SUM(DECODE(stat_study_log.log_type, 'B', 1, 0)) song_auto_count, SUM(DECODE(stat_study_log.log_type, 'B', CEIL(fox_contents.play_time / 80), 0)) song_auto_point, SUM(DECODE(stat_study_log.log_type, 'B', fox_contents.play_time, 0)) song_auto_time from `stat_study_log` inner join `fox_contents` on `fox_contents`.`fc_id` = `stat_study_log`.`fc_id` where `fu_id` = U201803221135520456 and `log_date` > 2021-10-12 23:59:59 limit 1) {"userId":"","email":"","request_method":"GET","request_url":"","headers":{"cookie":["XSRF-TOKEN=eyJpdiI6InZUVjlYaVE0NHVUMUNFQ2RQeERqUEE9PSIsInZhbHVlIjoiYTR2c1VOa3VnbnI2NlJSWlE2cUZVMHJHMnhzOVwvb2dueTlZeE01TW9rWDVEaXQwdjJiQ3J1aTVKMFB3NUFPd1QiLCJtYWMiOiJkMDQyNzQ5MjBmMzgxYjMwMWRkNmY2ZGVkMzI2ZjM5NmIxNmM4ZGZiYzBlYzFlMGI0YTc4MDIzYWNmNjVjM2FhIn0%3D; fox_session=eyJpdiI6IjRpU2hIMlRkR1wvVVVXTWxkV2Y3MWVBPT0iLCJ2YWx1ZSI6InUxRE84RFlOalVRQm5OZGJRVnBRNEY3SW1weHVFR0pjdHF6R1wvUmtwVVNSK1BqNjNOaXJzN2FBNHBxb1pkQkJDIiwibWFjIjoiNTQ0ZTY1Mzc2OWU4YzM3OTIxODQ1ZWNiY2U1NmVmNmE5YjM3OTYxZTE5ZGY1YTZmOTY0NzlkNTdlODUxNzJjYSJ9"],"referer":["https://apis.littlefox.com/web/studylog/summary"],"connection":["keep-alive"],"user-agent":["Mozilla/5.0 (iPhone; CPU iPhone OS 15_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"],"accept":["*/*"],"api-user-agent":["LF_APP_iOS:phone/2.6.5/iPhone14,5/iOS:15.3"],"api-locale":["ko_KR"],"accept-encoding":["gzip, deflate, br"],"accept-language":["ko-KR,ko;q=0.9"],"x-requested-with":["XMLHttpRequest"],"authorization":["Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJodHRwczpcL1wvYXBpcy5saXR0bGVmb3guY29tXC9hcGlcL3YxXC9zdHVkeS1sb2dcL3N1bW1hcnlcL2J5LXRlcm0iLCJpYXQiOjE2NDY4NzA3MTIsImV4cCI6MTY0OTQ2MjcxMiwibmJmIjoxNjQ2ODcwNzEyLCJqdGkiOiJoOTJvU1JUekxLY0t3c2UyIiwic3ViIjoiVTIwMTgwMzIyMTEzNTUyMDQ1NiIsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjciLCJhdXRoX2tleSI6IjM0MTYwODIyOTkwMzg2NzUiLCJjdXJyZW50X3VzZXJfaWQiOiJVMjAxODAzMjIxMTM1NTIwNDU2IiwiZXhwaXJlX2RhdGUiOjE2ODU3NTk0NDB9.OwVWmectqoTmjk3jL0ECCNNHDH1U_ulbFdH6e7MTqXrhCYufdsiwryA0XDSvwZ4ubQ97zkYZh3dP9I_3d_i2ig"],"host":[""],"content-length":[""],"content-type":[""]},"inputs":[],"exception":"[object] (Illuminate\\Database\\QueryException(code: 42000): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '1,'M',1,0)) story_one_count, SUM(DECODE(stat_study_log.log_type, 'P', CEIL(fo...' at line 1 (SQL: select SUM(DECODE(stat_study_log.log_type, 'P',1,'M',1,0)) story_one_count, SUM(DECODE(stat_study_log.log_type, 'P', CEIL(fox_contents.play_time / 80), 'M', CEIL(fox_contents.play_time / 80), 0)) story_one_point, SUM(DECODE(stat_study_log.log_type, 'P', fox_contents.play_time, 'M', fox_contents.play_time, 0)) story_one_time, SUM(DECODE(stat_study_log.log_type, 'A', 1, 0)) story_auto_count, SUM(DECODE(stat_study_log.log_type, 'A', CEIL(fox_contents.play_time / 80), 0)) story_auto_point, SUM(DECODE(stat_study_log.log_type, 'A', fox_contents.play_time, 0)) story_auto_time, SUM(DECODE(stat_study_log.log_type, 'S', 1, 0)) song_one_count, SUM(DECODE(stat_study_log.log_type, 'S', CEIL(fox_contents.play_time / 80), 0)) song_one_point, SUM(DECODE(stat_study_log.log_type, 'S', fox_contents.play_time, 0)) song_one_time, SUM(DECODE(stat_study_log.log_type, 'B', 1, 0)) song_auto_count, SUM(DECODE(stat_study_log.log_type, 'B', CEIL(fox_contents.play_time / 80), 0)) song_auto_point, SUM(DECODE(stat_study_log.log_type, 'B', fox_contents.play_time, 0)) song_auto_time from `stat_study_log` inner join `fox_contents` on `fox_contents`.`fc_id` = `stat_study_log`.`fc_id` where `fu_id` = U201803221135520456 and `log_date` > 2021-10-12 23:59:59 limit 1) at /data/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: 42000): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '1,'M',1,0)) story_one_count, SUM(DECODE(stat_study_log.log_type, 'P', CEIL(fo...' at line 1 at /data/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:326)
[stacktrace]

Source code in question

<?php

namespace App\Api\V1\Controllers\User;

use App\Api\V1\Controllers\BaseController;
use App\Api\V1\Controllers\Content\StoryController;
use App\Api\V1\CustomException;
use App\Api\V1\Resources\ContentCollection;
use App\Api\V1\Resources\StudyLog\ListByDateCollection;
use App\Api\V1\Resources\StudyLog\RecentlySeriesCollection;
use App\Api\V1\Resources\StudyLog\SummaryByTermResource;
use App\Api\V1\Resources\StudyLog\SummaryTotalResource;
use App\Models\Content;
use App\Models\User\CrosswordScore;
use App\Models\User\EbookStudyLog;
use App\Models\User\Quiz\Result as QuizResult;
use App\Models\User\SeriesStudyStat;
use App\Models\User\StartwordsScore;
use App\Models\User\StatActStudyDailyByLevel;
use App\Models\User\StatStudyDaily;
use App\Models\User\StatStudyDailyByLevel;
use App\Models\User\StatStudyHourly;
use App\Models\User\StudyLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

    /**
     * 
     *
     * @return SummaryTotalResource
     */
    public function summaryTotal()
    {
        $current_user_id = auth()->payload()->get('current_user_id');

        $summary = [
            'start_date' => \LittlefoxLocalization::setTimezoneDate(auth()->user()->reg_date)->toDateString(),
            'end_date' => \LittlefoxLocalization::setTimezoneDate(now())->toDateString(),
            'count' => 0,
            'point' => 0,
            'time' => 0,
        ];

        if ($animation_latest_study_log = StudyLog::where('fu_id', $current_user_id)->limit(1)->first()) {
            $summary['latest_study_time'] = \LittlefoxLocalization::setTimezoneDate($animation_latest_study_log->log_date)->toDateTimeString();
            $summary['latest_study_device'] = in_array($animation_latest_study_log->view_type, ['F', 'N'], true) ? 'pc' : 'mobile';
        }

        if ($ebook_latest_study_log = EbookStudyLog::where('fu_id', $current_user_id)->orderBy('log_date', 'desc')->first()) {
            if (is_null($ebook_latest_study_log) || is_null($animation_latest_study_log) || $ebook_latest_study_log->log_date->gt($animation_latest_study_log->log_date)) {
                $summary['latest_study_time'] = \LittlefoxLocalization::setTimezoneDate($ebook_latest_study_log->log_date)->toDateTimeString();
                $summary['latest_study_device'] = $ebook_latest_study_log->device_type == 'PC' ? 'pc' : 'mobile';
            }
        }

        $daily_max_date = now(auth()->user()->timezone)->subDays(2)->endOfDay();

        // NOTE: 
        if ($stat_study_daily_summary = StatStudyDaily::where('fu_id', $current_user_id)->summary()->addSelect(\DB::raw('MAX(st_date) max_date'))->first()) {
            if ($stat_study_daily_summary->max_date) {
                $daily_max_date = Carbon::parse($stat_study_daily_summary->max_date, auth()->user()->timezone)->endOfDay();
            }

            $summary['count'] += (int)array_sum($stat_study_daily_summary->only(['story_one_count', 'story_auto_count', 'story_ebook_count', 'song_one_count', 'song_auto_count']));
            $summary['point'] += (int)array_sum($stat_study_daily_summary->only(['story_one_point', 'story_auto_point', 'story_ebook_point', 'song_one_point', 'song_auto_point']));
            $summary['time'] += (int)array_sum($stat_study_daily_summary->only(['story_one_time', 'story_auto_time', 'story_ebook_time', 'song_one_time', 'song_auto_time']));
        }

        // NOTE: 
        $hourly_start_date = $daily_max_date->copy()->addSecond()->startOfSecond()->setTimezone('Asia/Seoul');

        $max_date = StatStudyHourly::where('fu_id', $current_user_id)
            ->where('st_date', '>=', $hourly_start_date->toDateTimeString())
            ->select(\DB::raw('MAX(st_date) max_date'))
            ->first();

        if ($max_date && $max_date->max_date) {
            $hourly_max_date = Carbon::parse($max_date->max_date)->endOfHour();

            // NOTE: 
            $stat_study_hourly_summary = StatStudyHourly::where('fu_id', $current_user_id)
                ->where('st_date', '>=', $hourly_start_date->toDateTimeString())
                ->where('st_date', '<=', $hourly_max_date->toDateTimeString())
                ->summary()
                ->get();

            foreach ($stat_study_hourly_summary as $hourly_summary) {
                $summary['count'] += (int)array_sum($hourly_summary->only(['story_one_count', 'story_auto_count', 'story_ebook_count', 'song_one_count', 'song_auto_count']));
                $summary['point'] += (int)array_sum($hourly_summary->only(['story_one_point', 'story_auto_point', 'story_ebook_point', 'song_one_point', 'song_auto_point']));
                $summary['time'] += (int)array_sum($hourly_summary->only(['story_one_time', 'story_auto_time', 'story_ebook_time', 'song_one_time', 'song_auto_time']));
            }
        } else {
            $hourly_max_date = $daily_max_date;
        }

        // NOTE: 
        if ($study_log_summary = StudyLog::where('fu_id', $current_user_id)->where('log_date', '>', $hourly_max_date->toDateTimeString())->summary()->first()) {
            $summary['count'] += (int)array_sum($study_log_summary->only(['story_one_count', 'story_auto_count', 'story_ebook_count', 'song_one_count', 'song_auto_count']));
            $summary['point'] += (int)array_sum($study_log_summary->only(['story_one_point', 'story_auto_point', 'story_ebook_point', 'song_one_point', 'song_auto_point']));
            $summary['time'] += (int)array_sum($study_log_summary->only(['story_one_time', 'story_auto_time', 'story_ebook_time', 'song_one_time', 'song_auto_time']));
        }

        // NOTE: 
        if ($ebook_study_log_summary = EbookStudyLog::where('fu_id', $current_user_id)->where('log_date', '>', $hourly_max_date->toDateTimeString())->summary()->first()) {
            $summary['count'] += (int)($ebook_study_log_summary->story_ebook_cnt);
            $summary['point'] += (int)($ebook_study_log_summary->story_ebook_point);
            $summary['time'] += (int)($ebook_study_log_summary->story_ebook_time);
        }

        return new SummaryTotalResource($summary);
    }

What we tried

I debugged it in dd and identified the relevant part and found the cause of the error, but how to convert the Oracle way of writing SUM(DECODE) to MariaDB's CASE expression? I don't know where to go from there.

Supplemental information (e.g., FW/tool version)

Laravel5.7, MariaDB10.3



via Chebli Mohamed

Manually throw Laravel ValidationException VS FormRequestValidationException

Is there any difference when I throw ValidationException manally and when ValidationException is thrown by laravel from FormRequest.

Following code will clear the problem

UserController.php

public function checkEmailExists(Request $request){
    try {
        $validation =  Validator::make($request->only('email'), [
            'email' => 'required|email|exists:users,email',
        ]);
        if ($validation->fails()) {
            throw (new ValidationException($validation));
        }
    } catch (\Exception $exception){
        return $exception->render(); //nothing is returned/displayed
    }
}

Handler.php

public function render($request, Throwable $exception)
{
    dd($exception instanceof Exception);
}

From the UserController I am throwing ValidationException manually and in Handler.php render method I am checking the $exception is an instance of Exception. So If I throw ValidationException manually then

dd($exception instanceof Exception); //gives false

But when I use UserStoreRequest (FormRequest)

UserController.php

public function checkEmailExists(UserStoreRequest $request){
    //Exception thrown by laravel if validation fails fro UserStoreRequest
}

then in Handler.php render() method

dd($exception instanceof Exception); //gives true

1:- Why it has different behavior when I throw ValidationException manally and when ValidationException is thrown by laravel from FormRequest?

2:- If I throw ValidationException manually then in the catch block I get the following error

Error {#3627
  #message: "Call to undefined method Illuminate\Validation\ValidationException::render()"
  #code: 0
  #file: "myproject/app/Http/Controllers/UserController.php"
  #line: 33


via Chebli Mohamed

How to write a where not in query in laravel?

I want to write a Where not in query in laravel. I wrote in sql it's working fine please help me convert the query to laravel.

This is the query...

SELECT * 
FROM `apiaccessauth` 
WHERE `site_name` NOT IN (
                SELECT `site_name` 
                FROM `API_site_access_log` 
                WHERE `created_at` LIKE '%2021-10-15%'
                );


via Chebli Mohamed

lundi 7 mars 2022

determine url parameter in Laravel

I am new to Laravel an have a question. I have controller named ReportsArchiveController and function named loadReport in it. this is what the method get

public static function loadReport(Request $request, $id, $view = 'reports.archive.single', $user_id = null)

this is the rout:

Route::get('/archive/{id}', ['as' => 'reports.archive.view', 'uses' => 'ReportsArchiveController@loadReport']);

I want to create new route that will use this method, and ask from where the user entered.

Route::get('/archive/{id}/csv', ['as' => 'reports.archive.view', 'uses' => 'ReportsArchiveController@loadReport']);

and ask in the method load report if the url is from /archive/{id}/csv or from /archive/{id}.

what I should add to the loadreport method to know if the user is from the url with csv or without? what to add to the method parameters? using Laravel 7



via Chebli Mohamed

How can I use a HFSql database with laravel (or php)?

I need to query an HFSql database in addition to my main database (which is MySql) with a laravel (V 5.6) application. I made some research and I found that I have to use the OLEDB server to make the connection (apparently more efficient than ODBC). For now I only have to make "SELECT" requests, to display datas. But I'm wondering if I could (maybe later) use this connection to modify datas into the HFSql database (requests PUT/POST/etc...)?

I found some forums where people have to query an HFSql databse with php and it seems working fine. But I never found someone who has to modify datas like this... I'm totally useless in windev...

Is there anyone who have ever tried to connect a laravel app with multiple databases including an HFSql database?

Do you have some advices or code snippets about the procedure to connect and query this type of database?

Thanks a lot for your answers!



via Chebli Mohamed

dimanche 6 mars 2022

Assets retreving issue in Laravel 5.4

#Issue Assets retreving issue in Laravel 5.4

Server root directory

-- public_html/
-- pilardir/ [Laravel Installed Here Project Controller, Models, Views Working from this directory]

Domain setup

www.thepiresearch.com Domain pointing directory (public_html/)

The problem here is the laravel application setup in the [pilardir] directory so when we setting up any assets file or upload blog images from the app then its uploading here pilardir/public/uploads/blogs which is all correct.

Now the problem is when we fetching the assets files / images it return the path and assets url from

public_html/public/uploads/blogs which is incorrect.



via Chebli Mohamed

i want to make validation for two unique col with laravel

i have two colums type_id , size_id in table i want to make validation role to prevent user enter the same record

example this is database ( type_size_db)

type_id size_id
type123 sm
type456 bg

if user enter this value (type123 , sm ) the validation will display this values was enterd but if user enter this value (type123 , bg) ,,,, >> will enterd successfully

in databas i make the two value unique $table->unique(['type_id', 'size_id']);

but the role of valdation not working will with me ! i need help

i am using laravel 5.8



via Chebli Mohamed

samedi 5 mars 2022

Create anchor tag with route contain under @php script in blade template

Route not working. how can I write an anchor tag, based on some condition? if the condition is true then the anchor tag will be printed with the route, I write the below code But I get an error.

In my blade template

@php
    if(SOMECONDATION){
    echo '<a href="">Approve</a>';
    }   
@endphp


via Chebli Mohamed

Laravel not validating array input

I'm trying to validate some input array fields in Laravel. My application reports back the field is required, even though it has been filled out.

The validation code I have is:

$this->validate($request, [
        'first_name'        => 'required',
        'last_name'         => 'required',
        'telephone'         => 'required',
        'email'             => 'unique:contacts,email,' . $request->id,
        'address'           => 'required',
        'address.0.address_line_1'         => 'required',
    ]);

The posted array is:

Array
(
[0] => Array
    (
        ['address_line_1'] => aa
        ['address_line_2'] => 
        ['city'] => 
        ['county'] => 
        ['postcode'] => 
        ['property_type'] => site
    )

)

My input fields are constructed like so:

address[0]['address_line_1']

I'm getting the validation message error:

The address.0.address line 1 field is required.

Anyone know what's wrong here?



via Chebli Mohamed

how can i store all details on login base

This is user profile when user click on refund button then store all data of user in another table how its possible?

this is my controller

 public function refundstore(Request $request)
{
    
   $user_id = Auth::user()->id
    $refund = new Refund(); 

$refund->user_id = $id;
$refund->refund_id = $refund->id; 

$refund->save();
    return view('front.user.profile', compact('user_id', 'refund'));
}

This is view

 <form action="" method="post">
              @csrf
            <button class="applyRefund mt-2">Apply For Refund</button>
           </form>

This is route

Route::post('refundstore', ['as' => 'refundstore', 'uses' => 'RefundController@refundstore']);


via Chebli Mohamed

jeudi 3 mars 2022

How to display single image in slider using loop in Laravel 5.7?

I am trying to display the single image in the slider, but whenever the user will click on this then it's open a popup in data-src="multiple-images-here" where I am running the slider. But the main issue is with the single image display in for loop. It displays all the available images in the loop. Please suggest me the best solution for this.

Here is my index.blade.php file where I am trying to display the slider using this code.

<div class="container-fluid margin-gallery d-lg-block d-block position-relative">
     <div class="row">
        <div class="col-lg-12 p-0">
           <div class="demo-gallery">
              @php
              if($propertys->propertyImage!=null){
              $images =  json_decode($propertys->propertyImage->image_path, true);
              }
              else{
              $images=null;
              }
              @endphp
              <?php
              $images_prop = collect($images['property_images']);
              ?>
              <ul id="lightgallery">
              @if($images['property_images']!=null)
                 @forelse($images_prop as $img)
                 <li class="sizing-li position-relative" data-src="">
                    <a href="javascript:void()">
                       <img class="img-responsive" src="" style="width:929px; height:495px;">
                    </a>
                 </li>
                 @empty
                 @endforelse
                 @endif
              </ul>
           </div>
        </div>
     </div>
  </div>

I want to display the first image from for loop here

<img class="img-responsive" src="" style="width:929px; height:495px;">


via Chebli Mohamed

Laravel - validate input to be in the interval [-1, 10] without 0. not_in not working properly?

As the title says, I'm having trouble validating an input field like I said in the title.

I tried it this way:

$request->validate([
            'nota' => 'min:-1|not_in:0|max:10',
        ]);

Basically, I want this "nota" field to have values in the interval [-1, 10] without 0.

But I can still enter 0.

Why doesn't it work and how can I fix it?



via Chebli Mohamed

How to create a record in the database base on email received to my site?

I have Laravel web application for my portfolio. https://www.bunlongheng.com

Under the portfolio section, you will see this

enter image description here

Right now, I have a CRUD for admin only to create them, but a thought come to my mind ...

I would like to create this automated email to just email myself to create a new record to the database.

Example

Anyone email to : portfolio@bunlongheng.com

Subject: Title of portfolio Body:

  1. Task 1
  2. Task 2
  3. Task 3

With attachments : 2 images (example)

Goal:

I want to accept and parse that email, and create a new portfolio record

  • Subject = Title
  • Body = Description
  • Attachments = Portfolio Images

enter image description here

How do I start ?



via Chebli Mohamed

How can I optimize or reduce the time complexity of the following code in Laravel 5.2.45?

In users table I have following data.

id   name    parent_id 
1     A           0
2     B           1
3     C           2
4     D           3
5     E           4
6     F           1

A have four level children. E is also children of A. E is the last, it has not any children. Now I can fetch all the children of any parent like the following code.

function getChildren($Id){
   $cache = [];
   $chList = [];
   $allUser = User::orderBy('parent_id', 'asc')
        ->orderBy('parent_id', 'asc')
        ->get();
   foreach($allUser as $user) {
    $cache [$user->parent_id][] = $user;        
   }
  $children0 = empty($cache [$Id]) ? [] : $cache [$Id];
  #first level child
  foreach($children0 as $child1) {

    $chList[$child1->id] = $child1;

    if(!empty($cache [$child1->id])) {

        #Second level child
        foreach($cache [$child1->id] as $child2) {

            $chList[$child2->id] = $child2;

            if(!empty($cache [$child2->id])) {

                #third level child
                foreach($cache [$child2->id] as $child3) {

                    $chList[$child3->id] = $child3;

                    if(!empty($cache [$child3->id])) {

                        #fourth level child
                        foreach($cache [$child3->id] as $child4) {
                            #can not be parent
                            $chList[$child4->id] = $child4;
                            
                        }
                    }
                }
            }
        }
    }
}

return $chList;
}

I can get the actual result by this code. But for huge data it is time consuming. Can any one help me to reduce time complexity or optimize the code?



via Chebli Mohamed

mercredi 2 mars 2022

Laravel 5.7 Chunk Exception: Cannot traverse an already closed generator

I am trying to get my models as generators so I can then loop over them 1 after the other, I am getting Exception: Cannot traverse an already closed generator.

 $chunk = MyModel::where('processed', '=', false)->cursor();
 foreach ($chunk as $c) {
  dd($c);
}


via Chebli Mohamed

laravel fetching data how to aligned in single line

I'm new in laravel and html im able to get data from table using foreach. but i get data not aliened as I required help me.

my required alignment enter image description here now I'm getting alignment enter image description here

@foreach ($Subject_Of_Examination as $user)
                                       
   <td style=" text-align: center; position: absolute; " > <font size="3"><p>,</p></font></td>
                                       
@endforeach


via Chebli Mohamed

mardi 1 mars 2022

How to print custom message in try catch - php laravel

I need to write to log some data when exception occurred, since it is dynamic data and I need the message I tried with simple code, just to write 'Boom' if exception occurred. However just the automatic exception data written in logs (as before the try catch). can someone advise how to print to log in the catch? I just need to add additional text to the exception, just to be more specific

try {
    $sheet->setCellValue($cell,$innervalue);
} catch(Exception $e) {
    $message = 'Can not set value: '.$innervalue .' in cell ' .$cell .$headerArray[$headerIndex];
    \Log::info('boom');
}

and in the logs nothing displayed enter image description here



via Chebli Mohamed