Ad

Schedueled Command How To Correctly Get Database Informartion By Using DB Query's

- 1 answer

In this project users can like each other's pictures and at certain times (with a cron job that I haven't made yet) the project should automatically pick a winner ( this will be the picture with the most likes).

I've created a table in my MySQL DB that store's the post_id and the user_id of the user that liked the post. In a scheduled command, I would like to get the post_id that appears the most in the table.

I made a Laravel command do:newwinner and in its handle function, I first tested the query directly in my DB and it worked it gave me a list of all the posts with the winner on top of the list. Then I tried to implement that query in my command. But when I tried to run it it gives me errors.

This is the handle function in my do:newwinner command

public function handle()
{
    echo "start job";
    $outcome = DB::select('select post_id, COUNT(post_id) from post_user group by post_id desc');
    echo " end job".$outcome;
}

Also, the import that I used: use Illuminate\Database;

I want to be able to extract the winner from my database each time so I can store it in a winners table in my DB.

when running: php artisan do:newwinner this is the error message I get:

    ?[41;1m Symfony\Component\Debug\Exception\FatalThrowableError ?[49;22m : ?[33mClass 'App\Console\Commands\DB' not found?[39m

  at ?[32mD:\School\3de jaar\Development\web-development\CocaCola\app\Console\Commands\newWinner.php?[39m:?[32m44?[39m
    40|      */
    41|     public function handle()
    42|     {
    43|         echo "start job";
  > 44|         $outcome = DB::select('post_id,
COUNT(post_id) from post_user group by post_id desc');
    45|         echo " end job".$outcome;
    46|     }
    47| }
    48|

  ?[33mException trace:?[39m

  ?[36m1   ?[39m?[33mApp\Console\Commands\newWinner::handle()?[39m
      ?[32mD:\School\3de jaar\Development\web-development\CocaCola\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php?[39m:?[32m32?[39m

  ?[36m2   ?[39m?[33mcall_user_func_array([])?[39m
      ?[32mD:\School\3de jaar\Development\web-development\CocaCola\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php?[39m:?[32m32?[39m

  ?[32mPlease use the argument ?[39m?[31m-v?[39m?[32m to see more details.?[39m
Ad

Answer

DB is not in your current namespace App\Console\Commands. So you can either import it at the top

use DB;

or

use Illuminate\Support\Facades\DB;

or precede it with a backslash \DB::table(...). This solves the class not found exception.

Ad
source: stackoverflow.com
Ad