How to get all results of a table with Many To Many relationship

I’m working on an Online Store project and I wanted to create Add To Favourite system for users to add products that they like to their favourite list.

So I have created a table named favourite_products which goes like this:

enter image description here

So the usr_id stands for user id and prd_id stands for product id.

Now I wanted to get all the data from this table.

So I tried adding this to the Controller:

$userFavourites = new User();
dd($userFavourites->favourites);

But it does not return data and shows this empty collection:

IlluminateDatabaseEloquentCollection {#2862 ▼
  #items: []
}

However data already exists there.

So my question is, how can I show all the results from favourite_products at a table with User Many To Many relationship?

Here is the User.php Model:

public function favourites()
    {
        return $this->belongsToMany(Product::class, 'favourite_products', 'usr_id', 'prd_id')->withTimestamps();
    }

And this the Product.php Model:

public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }

Ajax form submit with rich text box without page reload

Hello Everyone please I’m having a problem with my ajax form submit. When I use a rich textbox to submit my form I have to click on the submit button twice before the request sends. Please guys I seriously need help. I want that immediately I press the submit button once the form should submit immediately.
Here is my code :

<script src="https://cdn.tiny.cloud/1/qagffr3pkuv17a8on1afax661irst1hbr4e6tbv888sz91jc/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>

                    <div id="comments">
                        <h5>Comments</h5>
                        <hr style="margin: 15px 0;">
                        <form action="javascript:void(0)" name="comment-form" id="comment-form" method="post">
                            @csrf
                            <textarea id="mytextarea" class="form-control" name="comment" placeholder="Write your Comments Here"></textarea>
                            <small class="text-danger"><strong>Should not exceed 255 characters</strong></small>
                            <input type="hidden" name="banner_id" value="{{$banner->id}}">
                            <input type="hidden" name="user_id" value="{{$usercom}}">
                            <br>
                            <button type="submit" class="btn btn-success btn-sm">Post Comment</button>
                          </form>
                          <div id="comment-loading">
                              <small><b>Please wait</b></small>
                             <img src="{{asset('load-img/loader.gif')}}" alt="" width="50px">
                          </div>
                          <br>

                        <div class="fb-comments" data-href="#" data-width="100%" data-numposts="10" id="div2">
                            <h5 style="margin-left: 10px">{{$banner->comments}} Comments</h5>
                            <hr>
                            <ul class="element" data-config='{ "type": "list", "limit": 5, "element": "li", "more": "↓ show more", "less": "↑ show less", "number": true }' style="list-style-type: none; padding-inline-start: 10px !important;">
                           @forelse ($comments as $comment)
                           <li>
                           <p class="text-success" style="line-height: 1em;"><b>{{$comment->user->username ?? 'Unknown'}}</b></p>
                           <span style="font-size: 14px;">{!!$comment->comment!!}</span>
                        </li>
                           @empty
                               No Comment has been made yet.
                           @endforelse
                        </ul>
                        </div>
                    </div>

<script src="{{asset('js/jquery.min.js')}}"></script>
<script src="{{asset('js/jquery.validate.min.js')}}"></script>
<script>
        if ($("#comment-form").length > 0) {
            $("#comment-form").validate({
                rules: {
      banner_id: {
        required: true,
        maxlength: 11
      },
      comment: {
        required: true,
        maxlength: 255
      },
    },
    messages: {
        banner_id: {
            required: "<small class='text-danger'>Banner Id Required</small>",
        maxlength: "<small class='text-danger'>Your banner id maxlength should be 11 characters long.</small>"
      }, 
      comment: {
            required: "<small class='text-danger'>Comment is Required</small>",
        maxlength: "<small class='text-danger'>Your comment maxlength should be 255 characters long.</small>"
      }, 
    },
         submitHandler: function(form) {
             $.ajaxSetup({
             headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
             }
            });
            $('#comment-loading').show();
             $.ajax({
               url: "{{url('postcomment')}}",
               type: "POST",
               data: $('#comment-form').serialize(),
               success: function( response ) {
                $('#comment-loading').hide();
                document.getElementById("comment-form").reset();     
                   $("#div").load(" #div > *");
                   $("#div2").load(" #div2 > *");             
               }
             });
            }
        })
    }
    </script>

<script>
    tinymce.init({
      selector: "#mytextarea",
      plugins: "emoticons",
      toolbar: "emoticons",
      toolbar_location: "bottom",
      menubar: false
    });
  </script>
<script>
    $(function () {
        $('#comment-loading').hide();
    });
</script>

PLease I seriously need your assistance here. Thanks In advance.

How can i calculate the time user is spending on page?

I have made a function , on login the user actual date month-day-year hours-minutes-second are saved on database .
On log-out i have made a function to calculate the time the user has stayed on page but for some reasons the function is not working.
I need to calculate with the following idea , ‘The time user has logged out’ – ‘The time user has been logged in ‘=’total’,
Then i need to get the all total the user has spent on page and add this total i made the calculation.

 [![public function calculateTimeOnPage(){

        $id = $_SESSION['userid'];
        $stmt = $this->connection->pdo->prepare("SELECT * FROM users WHERE id = '$id'");
        
        $stmt->execute();    
        $result = $stmt->fetch();
        $end_time_on_page = Date("Y-m-d H:i:s");
        $todayDate_ = date('Y-m-d H:i:s');
     
        $total = strtotime($end_time_on_page) - strtotime($result['page_start_time']); 
  
        $actual_date = date("Y-m-d H:i:s",$result['time_on_page']);
    
        $calculate_time_on_page = $total + strtotime($actual_date);
        
        $data = date("Y-m-d H:i:s",$calculate_time_on_page);
        
        echo 'Data : '.$data . '<br>';
        
        $stmt_up = $this->connection->pdo->prepare("UPDATE users SET 
        time_on_page = TIMESTAMPDIFF(SECOND,'".$data."','".$todayDate_."')
        WHERE id = '$id'");

        function convertSecToTime($sec)
        {
            $date1 = new DateTime("@0");
            $date2 = new DateTime("@$sec");
            $interval = date_diff($date1, $date2);
            $parts = ['years' => 'y', 'months' => 'm', 'days' => 'd', 'hours' => 'h', 'minutes' => 'i', 'seconds' => 's'];
            $formatted = [];
            foreach($parts as $i => $part)
            {
                $value = $interval->$part;
                if ($value !== 0)
                {
                    if ($value == 1){
                        $i = substr($i, 0, -1);
                    }
                    $formatted[] = "$value $i";
                }
            }

            if (count($formatted) == 1)
            {
                return $formatted[0];
            }
            else
            {
                $str = implode(', ', array_slice($formatted, 0, -1));
                $str.= ' and ' . $formatted[count($formatted) - 1];
                return $str;
            }
        }

        //convertSecToTime($sec);

        echo convertSecToTime($result['time_on_page']); // qekjo perdoret per mi show sa kohe ka

        echo "UPDATE users SET 
        time_on_page = TIMESTAMPDIFF(SECOND,'".$data."','".$todayDate_."')
        WHERE id = '$id'";

        $stmt_up->execute();
    }][1]][1]

PHP hex2bin acsii table

I try convert hex “fc” to symbol “ü”. Like on this Site. But in php this symbol “ü” not “fc” its like unicode “c3bc”. So how to convert “fc” to symbol “ü” in php ?

Sending scheduled emails with lumen 8 and mailgun

I have a Lumen app (v8) configured for sending emails using Mailgun. Everything works flawlessly when I send the mail immediately, but when I try to use the “later” method it seems to be ignored.
This is what I am using:
file app.php

$app->configure('services');
$app->configure('mail');
$app->configure('queue');

$app->alias('mail.manager', IlluminateMailMailManager::class);
$app->alias('mail.manager', IlluminateContractsMailFactory::class);

$app->alias('mailer', IlluminateMailMailer::class);
$app->alias('mailer', IlluminateContractsMailMailer::class);
$app->alias('mailer', IlluminateContractsMailMailQueue::class);

$app->make('queue');

the Onboard3.php mail class:

<?php
namespace AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
use IlluminateSupportFacadesDB;

class Onboard3 extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $info;

    public function __construct($info)
    {
        $this->info = $info;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return
            $this->from('[email protected]', 'Sender name')
            ->subject("Subject")
            ->view('emails.users.onboard3')
            ->text('emails.users.onboard3_plain');
    }
}

My controller method:

Mail::to([
    '[email protected]'
])
->later(
    Carbon::now()->addMinutes(10000)
    , new Onboard3($recipient)
);

Prevent a package from including the provider definition of the embedded composer.json

I have a use case where I want to extend a certain package by using my own service provider as well as extending the provided command.

The package has a composer.json definition as follows:

"extra": {
    "laravel": {
      "providers": ["BeyondCode\LaravelWebSockets\WebSocketsServiceProvider"],
      "aliases": {
        "WebSocketRouter": "BeyondCode\LaravelWebSockets\Facades\WebSocketRouter"
      }
    }
  }

I want laravel to ignore the providers definition without modifying the package.

Does anyone know if that is actually possible?

Setup Xdebug configuration for php scripts called in cron by docker-entrypoint.sh in vscode

Currently using VSCode on MacOS, Xdebug is working well for my php web application ran with docker.

But I also have some php scripts that are called by the docker-entrypoint.sh as crons and I’d like to be able to debug them as well. I can’t configure it properly, nothing happens when I set breakpoints while the crons are running.

Here is my launch.json configuration at the moment (all the codesource – web, scripts…- is under myapp/app) :

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "log": true,
            "pathMappings": {
                "/opt/myapp/app": "/Users/me/src/myapp/app"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9002,
            "log": true
        }
    ]
}

In my docker-compose.yml, I also have PHP_XDEBUG_ENABLED=true for the web container and the cron container of course.

Any ideas / configuration examples to get the debug working for the php crons ?

Laravel 8 – Insert using multiple join and calculation laravel

I want to solve the following problem using one query for example

Questions Table

 id  |  question | correct_answer | point

 1   | "what ..?"| 'test'         | 10
 2   | "what ..?"| 'test'         | 5

Answers Table

id |  question_id | user_id | answers | point


Using Laravel 8 I want to add answers to multiple questions at the same time using join and get scores from the questions table and if user answers match to questions.correct_answer also add its score to answers table
use something like code:

DB::table('questions')->join('answers','answers.question_id','=','questions.id')

Thanks in Advance 🙂

How to submit form value on .env or config/myconfig.php?

I have a CRM for menaging data, so far so good. I am thinking to add some seetings extra option on my CRM, i am thinking for a route /seeting-value and on this to display a form. I mean when a user go to this route to personalize CRM as his like, for example site-name, body-background-color, site-description, maybe to change db config. I know this config have to do with .env and config/myconfig.php , what i dont know is how to pass this submit form on emv or my config, how it really works. I have search on google but i didnt find any good documentation about this. Any one have an idea?

404 Not Found nginx/1.14.2 after upgrade PHP 8 on Azure – Laravel

I’m trying to upgrade from PHP 7.4 to PHP 8 on Azure App Service (Linux).

It shows the following error:
404 Not Found – nginx/1.14.2

I understood that the problem is that Azure from PHP 8 use NGINX instead Apache.
So I followed the steps given here:
https://azureossd.github.io/2021/09/02/php-8-rewrite-rule/index.html

For a while it’s worked correctly but from the day after it stopped to work and restart to show the error “404 Not Found
nginx/1.14.2”

This is my default file:

server {
    #proxy_cache cache;
    #proxy_cache_valid 200 1s;
    listen 8080;
    listen [::]:8080;
    root /home/site/wwwroot;
    index  index.php index.html index.htm;
    server_name  example.com www.example.com; 

    location / {            
        index  index.php index.html index.htm hostingstart.html;
        try_files $uri $uri/ /index.php?$args;
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /html/;
    }
    
    # Disable .git directory
    #
    location ~ /.git {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Add locations of phpmyadmin here.
    #
    location ~ [^/].php(/|$) {
        fastcgi_split_path_info ^(.+?.php)(|/.*)$;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_connect_timeout         300; 
        fastcgi_send_timeout           3600; 
        fastcgi_read_timeout           3600;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }
}

Get all texts between html tags in string php

i have a string like that:

test test test <span> hello </span> test test test <span> hello2 </span>

and i try to get the text between the span tags like:

array [

0 => 'hello',
1 => 'hello2
];

i tried:

$regex = '#<s*?spanb[^>]*>(.*?)</spanb[^>]*>#s';
$matches = [];
$item->text = preg_match($regex,  $item->text, $matches);

but there i only get the first match: ‘hello’

Symfony 5 – Clear cache contract command

use SymfonyContractsCacheItemInterface;
use SymfonyComponentCacheAdapterFilesystemAdapter;

$cache = new FilesystemAdapter();

$value = $cache->get('my_cache_key', function (ItemInterface $item) {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

I use Symfony 5.4 and the cache contracts on an application and some cache expirations are quite long. My problem is that some values need to be changed and to do it properly, I would need to be able to purge the cache with a command line on my production server to be sure to have correct data.
I can make a custom command ex: php bin/console app:cache:custom-clear that invalidates some tags but I’m surprised I don’t have a native command to do this cache purge operation globally.

It may be that it’s simple and I didn’t understand anything but I don’t see much in the doc on this point.
If anyone has a lead, I’m interested.

Query returns null for date not existing – PHP & MYSQL

I am beginner with mysql and PHP Larvel. I have a query thats says

Sale::whereDate('created_at', '>=' , $startDate)
    ->whereDate('created_at', '<=' , $endDate)
    ->where('company_id',$companyId)
    ->selectRaw(implode(',', $query))
    ->get();

The query below returns data for January since the startDate is ‘2022-01-01’ and endDate is ‘2022-01-31’

But when i do same for February, it returns null because there is no 2022-02-31 in reality. But when i set the endDate to ‘2022-02-29’, it returns data.

How can i make my query still bring data even tho 2022-02-31 does not exist on calendar ?