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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/R9Puv4t
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/uai9UqA
via IFTTT

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;
   
    });   }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/s970fQJ
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/y47J6hE
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/fLPze5p
via IFTTT

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');


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/vy06HmS
via IFTTT

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',
]);                           

                                         


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/jGpiZaM
via IFTTT

lundi 28 mars 2022

Unknown command in chromedriver

I'm working on a PHP project and using dusk to conduct tests (OS: Ubuntu 20). When I run the chromedriver on Linux and navigate to any URL, I am getting an unexpected error. For example, the next error happens when I navigate to localhost:9515/logo.png:

{ "value":
    { "error":"unknown command",
      "message":"unknown command: unknown command: logo.png",
      "stacktrace":"#0 0x5561bf5e33e3 \u003Cunknown>\n#1 0x5561bf348468 \u003Cunknown>\n#2 0x5561bf3991de \u003Cunknown>\n#3 0x5561bf398f57 \u003Cunknown>\n#4 0x5561bf31f634 \u003Cunknown>\n#5 0x5561bf32044a \u003Cunknown>\n#6 0x5561bf60ff56 \u003Cunknown>\n#7 0x5561bf6272ad \u003Cunknown>\n#8 0x5561bf611dae \u003Cunknown>\n#9 0x5561bf627c34 \u003Cunknown>\n#10 0x5561bf605be2 \u003Cunknown>\n#11 0x5561bf31f206 \u003Cunknown>\n#12 0x7f5f2c10d0b3 \u003Cunknown>\n"}}

The problem is that dusk also navigates to webpages and instead of getting the HTML contents, it's getting the same error.

I'm completely stumped at two things. First, why does there seem to be a recursion of unknown commands (it's as if the unknown command itself is the unknown command)? Second, why is the unknown command pointing at the URL, or the file?

Things I have tried:

  • I have already re-installed chromedriver
  • I have confirmed that the version of the chromedriver is the same as the Chrome and Chromium versions (99)
  • I have tried launching the chromedriver myself and using Laravel dusk, but the outcome remains the same

I would appreciate any help.


EDIT: This is my DuskTestCase.php file, which I haven't really changed:

<?php

namespace Tests;

use Laravel\Dusk\TestCase as BaseTestCase;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;

abstract class DuskTestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     * @return void
     */
    public static function prepare()
    {
        static::startChromeDriver();
    }

    /**
     * Create the RemoteWebDriver instance.
     *
     * @return \Facebook\WebDriver\Remote\RemoteWebDriver
     */
    protected function driver()
    {
        $options = (new ChromeOptions)->addArguments([
            '--disable-gpu',
            '--headless'
        ]);

        return RemoteWebDriver::create(
            'http://127.0.0.1:9515', DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY, $options
            )
        );
    }
}

And this is the test:

<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class ExampleTest extends DuskTestCase
{
    /**
     * A basic browser test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/') // also experimented with localhost and 127.0.0.1 (with ports), but no change
                    // ->pause(2000)
                    ->assertSee('Sign In');
        });
    }
}

In the environment file, I have set APP_URL=http://127.0.0.1:9515.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/qb4WlD5
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/PEDgNVz
via IFTTT

dimanche 27 mars 2022

pass data to welcome message

my register has a welcome message (email), it generates a random number

    protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        't_matricula' => $data['t_matricula'],
        'number' => rand(100, 9200),
        'matricula' => $data['matricula'],
        'password' => Hash::make($data['password']),
    ]);

    Mail::to($user->email)->send(new WelcomeMail($user));
    
    return $user;
}

I need to pass that generated value (Number) to the welcome email, then print it in the email template



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/e9vwzkh
via IFTTT

vendredi 25 mars 2022

Decrypting AES-256-CBC with Nodejs to PHP Laravel (5.8)

I have instance key and iv. I want to decrypt data to json with NodeJS programming like this

const crypto = require("crypto")
export const decryption = (body: string) => {
const key = process.env.SECRET_TOKEN; // if (!key) throw new Error("Key is missing");
const iv = process.env.SECRET_IV;
if (!iv) throw new Error("Key is missing");
let encryptedText = Buffer.from(body, "hex");
let decipher = crypto.createDecipheriv("aes-256-cbc", Buffer.from(key, "hex"), Buffer.from(iv, "hex"));
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString(); }

I tried to use openssl_decrypt but not working. Please you help me convert NodeJS programming to PHP (Laravel 5.8).

Thank in advance.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/NseqAd7
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/YOn47pC
via IFTTT

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

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/YMoZCWm
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Uy9LRTO
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/saAPRGV
via IFTTT

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&date=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=1&date=03%2F22%2F2022

then it is working how can i urlencode in laravel

Controller:

public function Detail(Request $request)
    {
         
        $start_date=date('Y-m-d H:i:s', strtotime($request->date));
    }

Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/gSXUP4v
via IFTTT

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();


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/mrWMtX6
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Hx7j6Qc
via IFTTT

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' ));  


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/8VvxnjO
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/gIMr5b9
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/iRB4v7l
via IFTTT

jeudi 17 mars 2022

Retrieve objects after committing transaction in same request using Laravel

I have an app where I'm using Elloquent working with transactions and I need to retrieve the new objects after calling the commit method, however, the commit is fired near the end of the request.

Here is an example of my problem, I didn't post the original code, I just want to illustrate what I am facing

<?php
DB::beginTransaction();

try{
   $u= \App\User::count(); //returns x
   $u_new= new \App\User(['name' => 'John']);
   $u_new->save();
   DB::commit();
 }catch(\PDOException $e){
  DB::rollback();
 }
 $u2= \App\User::count(); //keeps returning x and not x+1


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/deIFCVm
via IFTTT

How can I send data to this Laravel form via AJAX?

I am making a Laravel 8 app with posts and post categories. I am now working on the Edit post form, and I need to prepopulate it with the post's current data.

The id column in the catergories table is the category_id foreign key in the posts table.

In the Posts model I have:

class Posts extends Model {
   use HasFactory;
    
    protected $fillable = [
        'title',
        'category_id',
        'description',
        'body'
    ];
}

The route is Route::get('/dashboard/posts/edit/{id}', [PostsController::class, 'editPost']).

The editPost method in the controller:

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

class PostsController extends Controller {

    // More code

    public function editPost($id) {

        $post = Posts::select (
            "posts.id",
            "posts.title",
            "posts.description",
            "posts.body",
            "catergories.name as category_name"
            )
            ->leftJoin("catergories", "posts.category_id", "=", "catergories.id")
            ->where('posts.id', $id)
            ->first();

            echo $post->title . '<br>';
            echo $post->category_name . '<br>';
    }
}

In the form:

<div class="form-group mb-2 @error('title') has-error @enderror"> 
        <label for="title" class="text-muted">Title</label>       
        <input id="title" type="text" name="title" placeholder="Title" value="" class="form-control @error('title') is-invalid @enderror" autofocus>

        @error('title')<span class="error-msg"></span>@enderror
    </div>

    <div class="form-group mb-2 @error('category_id') has-error @enderror">
        <label for="category" class="text-muted">Category</label>
        <select name="category_id" id="category" class="form-control @error('category_id') is-invalid @enderror">
            <option value="0">Select a category</option>
            @foreach($categorys as $category)
                <option value="" >
                    
                </option>
            @endforeach
        </select>
</div>

The goal

The form is placed in a Bootstrap 5 modal, which means that I can not access https://myapp.test/dashboard/posts/edit/1 to get the necessary data. I have to do this via AJAX.

For this purpose, I have the following JavaScript function

function populateEditForm(event, entity) {
    var id = event.currentTarget.dataset.id;
    var url = `/dashboard/${entity}/edit/${id}`;
    console.log(url);

    var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE) { 
                if (xmlhttp.status == 200) {
                    console.log(xmlhttp.responseURL);
                }
            }
    };

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

that I call in a Blade template:

<a onclick="populateEditForm(event, 'posts')" href="#" data-id="" title="Edit post" data-bs-toggle="modal" data-bs-target="#edit_post_modal">
        <i class="fa fa-edit"></i>
</a>

The problem

The console corectly displays the path to the edit method in the controller: https://myapp.test/dashboard/posts/edit/1 (for the post with id equal to 1), but I don't know how to use this to get the necessary data ( $post->title, $post->category_name, etc) and pass it to the form.

What is missing?


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/XmIkDJ9
via IFTTT

Image file path not inserting in database with laravel8

enter image description here enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/JxukO8Y
via IFTTT

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 );
}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/8943csR
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/XVSLyr0
via IFTTT

mardi 15 mars 2022

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>



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/P203XFx
via IFTTT

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]



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/WeF8wBp
via IFTTT

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>


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/n1qKm5h
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/58tmNuq
via IFTTT

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>


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/yHWXrYt
via IFTTT

dimanche 13 mars 2022

How can I redirect html codes to controller in Laravel?

This is my code

[ '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 inside array in 'icon' label

from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/p4yal5L
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/IjM9YB4
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3jUlz5S
via IFTTT

Calculating how many years are from a date

I'm a beginner in PHP, I started a project based on laravel framework and I have this issue. Also the version of PHP that I use is 8.1.3

So, I have a tabel. In this table I need to show a value if the person is hired for more than one year.

And I put in Model this code

public function hiringdate() {
         if(($this->now - $this->hiring_date) / (60 * 60 * 24) > 1) 
         {return 100;} 
       }

Also in Controller they are defined like this:

$newmember->hiring_Date = $req['hiring_date'];
$newmember->now = $now->strtotime("now");

What am I doing wrong here?

Thanks!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/tcAB1vM
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/gxFv0I6
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/HQK2t8A
via IFTTT

How to Save File in storage folder with Original name?

I want to store an uploaded file with its original client name in the storage folder. What do I need to add or change in my code?Any help or recommendation will be greatly appreciated

Here my Controller

public function store(Request $request) {
    $path = "dev/table/".$input['id']."";
    $originalName = $request->file->getClientOriginalName();
    $file = $request->file;
    
    
    Storage::disk('local')->put($path, $file);
}

Edit: I know how to get the originalClientName. the problem is storing the file in the folder using the original name, not the hash name.I needed help on this specific part Storage::disk('local')->put($path, $file);



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/wcaUyuS
via IFTTT

Uncaught TypeError: Cannot read properties of undefined (reading 'find') in formvalidation.js file

formValidation.js:1370 Uncaught TypeError: Cannot read properties of undefined (reading 'find') at FormValidation.Framework.Bootstrap.updateStatus (formValidation.js:1370:45) at FormValidation.Framework.Bootstrap.validateField (formValidation.js:1619:30) at FormValidation.Framework.Bootstrap.validate (formValidation.js:1508:22) at HTMLFormElement. (formValidation.js:167:26) at HTMLFormElement.dispatch (jquery-3.1.1.min.js:3:10315) at HTMLFormElement.q.handle (jquery-3.1.1.min.js:3:8342)



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/DtQTx3V
via IFTTT

mercredi 9 mars 2022

Multiple language in laravel

I want to use two language in my web application for that i have created this dropdown in my view:

 @if ( Config::get('app.locale') == 'en')
 <li><a class="dropdown-item" href="">Arabic</a></li>
 @elseif ( Config::get('app.locale') == 'ar' )
 <li><a class="dropdown-item" href="">English</a></li>
 @endif

web route:

    Route::get('setlocale/{locale}', function ($locale) {
        if (in_array($locale, \Config::get('app.locales'))) {
          session(['locale' => $locale]);
        }
      
        return redirect()->back();
    });

 Route::get('contact', 'ContactController@index')->name('contact');
 Route::get('home', 'HomeController@index')->name('home');

config/app.php

'locale' => 'en',

'locales' => ['ar', 'en'],

Middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use App;
use Config;
use Session;
use Illuminate\Http\Request;

class Locale
{
    /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
   public function handle($request, Closure $next)
   {
     
     //$raw_locale = Session::get('locale');
     $raw_locale = $request->session()->get('locale');
     if (in_array($raw_locale, Config::get('app.locales'))) {
       $locale = $raw_locale;
     }
     else $locale = Config::get('app.locale');
       App::setLocale($locale);
       return $next($request);
   }
}

when i click on dropdown the language changes but the url is still same i want on initial load of my application if url is testsite.com then it should be by default testsite.com/en if we visit on any page i want that language appended in the url like if i go to contact then it should be testsite.com/en/contact.Same language should be appended to url if i change from dropdown but presently language is not being appended. This language should be prefixed on frontend url only not on backend url (Admin). Any solution Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/fLVQo7l
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/n4PkSs5
via IFTTT

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


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/GyuLEmX
via IFTTT

Is there any security issue in Laravel 5.2.23 till now?

I have got a Laravel 5.2.23 project to work on for some fixes and it is running perfectly. Now, is it necessary to update the project to any other version? Is there any security issue with Laravel 5.2.23 till now?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/G6wj2pD
via IFTTT

GroupBy not working in Laravel With Method

I use GroupBy query inside the WITH method in laravel query like following.

$q = Invoice::query();

     if($request->from_date){  $q->where('invoice_date','>=',date('Y-m-d',strtotime($request->from_date))); }

     if($request->to_date){ $q->where('invoice_date','<=',date('Y-m-d',strtotime($request->to_date))); }
    
     if($request->branch_id){ $q->where('branch_id',$request->branch_id); }

    $q->with(['invoiceitems' => function($query){

            $query->select('tax_rate');
            $query->groupBy('tax_rate');
    
    }]);  
      
     $invlist=$q->paginate(50);

In Result, Invoice table records returned but invoice items empty



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/xkziUb6
via IFTTT

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%'
                );


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/bOGhSTF
via IFTTT

mardi 8 mars 2022

How to get current user when running command in laravel

I'm processing in the command line. And I want to get the current user, I use 2 ways to get it, but both return a result in Null

use Illuminate\Support\Facades\Auth;

public function handle()
{
   Auth::id(); //null
   // or
   auth()->user()->id //null
}

If I submit the form, using those 2 methods can get the current user, but when I run the command, I can't get it. Anyone give me any ideas to improve it. Thank you



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/wMgHUb9
via IFTTT

lundi 7 mars 2022

Apache 2 automatically adds the Range header (env variable HTTP_RANGE)

We are running a Laravel 5.7 app on our production server, which is running some version of Apache 2 (the SERVER_SOFTWARE env variable only shows "Apache") with PHP 7.2 FCGI.

The env variable HTTP_RANGE seems to be set automatically (apparently always to bytes=0-5242879) by Apache which leads to file downloads failing with an HTTP 416 error.

According to the developer console, the initial request does not contain a Range header. For development, we are using Laravel's built-in development server (via php artisan serve), which works without issues too, so I am pretty confident that Apache 2 is adding that header on its own.

How do I debug where HTTP_RANGE is being set? As a workaround, how do I disable this behavior in .htaccess?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/rhH5AFf
via IFTTT

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!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/XkKrhzi
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/adiuJlD
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/j7ruXF0
via IFTTT