How to properly use composite keys as the primary key in Laravel with Spatie Roles and Permissions package?

I need to use both email and phone_number as the primary key for the User model in my Laravel application. Since Laravel doesn’t natively support composite primary keys, I found a workaround to implement it. However, I’m facing issues with relationships, especially when using the Spatie Roles and Permissions package. Specifically, I’m getting an “Array to string conversion” error. Also facing issue on auth()->user() helper function which is returning unexpected result.

Here’s the setup I have:

User Model:

namespace AppModels;

use IlluminateFoundationAuthUser as Authenticatable;
use SpatiePermissionTraitsHasRoles;
use IlluminateDatabaseEloquentBuilder;

class User extends Authenticatable
{
    use HasRoles;

    public $incrementing = false;
    protected $keyType = 'string';
    protected $primaryKey = ['email', 'phone_number'];
    
    protected $fillable = ['email', 'phone_number', 'name', 'password'];
}

Issue:
When accessing relationships like $user->roles, I encounter the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `users` where (`0` = email and `1` = phone_number) and `users`.`deleted_at` is null limit 1)

Event Color based on Resource / Room Color – Fullcalendar.js PHP MySQL

I want to display the event color / background color based on each room’s color (I have 3 different colors for 3 different rooms/resource). But the parsed colors from resources.php wasn’t displayed as I expected in every events on each different rooms (3 rooms). So I want to change the event’s colors based on their room’s placement (room_id) on MySQL db.

calendar:

resources.php

$sql = "SELECT id, room_name AS title FROM room_list";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();

$colors = ['#00DCFF', '#fe9e0c', '#179f66'];
$colorIndex = 0;

$resources = array();
if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    $row['color'] = $colors[$colorIndex % count($colors)];
    $resources[] = $row;
    $colorIndex++;
  }
}

echo json_encode($resources);

$stmt->close();

script.js

document.addEventListener("DOMContentLoaded", function () {
  $.ajax({
    url: "models/resources.php",
    type: "GET",
    dataType: "json",
    success: function (resources) {
      initializeCalendar(resources);
    },
  });
});

function initializeCalendar(resources) {
  let events = [];
  if (scheds) {
    Object.keys(scheds).map((k) => {
      let row = scheds[k];
      let room = resources.find((resource) => resource.id == row.room_id);
      let color = room.color;
      let event = {
        id: row.id,
        title: row.title,
        start: row.start_datetime,
        end: row.end_datetime,
        resourceId: row.room_id,
        backgroundColor: color,
        borderColor: color,
      };
      
      events.push(event);
    });
  }
  let calendarEl = document.getElementById("calendar");
  let calendar = new FullCalendar.Calendar(calendarEl, {
    schedulerLicenseKey: "CC-Attribution-NonCommercial-NoDerivatives",
    headerToolbar: {
      left: "prev,next,today",
      center: "title",
      right:
        "resourceTimeGridDay,resourceTimeGridFourDay,resourceTimeGridMonths",
    },
    views: {
      resourceTimeGridFourDay: {
        type: "resourceTimeGrid",
        duration: { days: 3 },
        buttonText: "3 Days",
      },
      resourceTimeGridMonths: {
        type: "dayGridMonth",
        duration: { months: 1 },
        buttonText: "Months",
      },
      resourceTimeGridDay: {
        buttonText: "Day",
      },
    },
    resources: resources,
    events: events,
    editable: true,
    allDaySlot: false,
    datesAboveResources: true,
    eventDidMount: function (info) {
      if (scheds) {
        Object.keys(scheds).map((k) => {
          let row = scheds[k];
          let room = resources.find((resource) => resource.id == row.room_id);
          let color = room.color;
          info.el.style.backgroundColor = color;
        });
      }
    },
  });

  calendar.render();
}

I tried every possible way on script.js to change the backgroundColor or textColor to display the same color based on each rooms in my script.js in view types – even using eventDidMount like the shown image.

Now it just displays the green color (#179f66) for every event.

I tried to change the eventDidMount to this:

eventDidMount: function (info) {
      if (scheds) {
        Object.keys(scheds).map((k) => {
          let row = scheds[k];
          let room = resources.find((resource) => resource.id == row.room_id);
          let color = room.color;
          info.event.extendedProps.backgroundColor = color;
        });
      }
    },

but it only changes the dots color:

event-colors(dot-color)

PHP not writting logs in case of 504

I have a Symfony application and I have set a request_terminate_timeout = 60 to be the same as Nginx timeout, and afterwords for 504 requests I can’t see production logs, but if I use prod env locally I can see the logs. Logs are written to php://stdout

In the monolog config, I use the stream handler, so it should not use any buffer but immediately send logs to tty, and locally it send logs right away (again, locally I tested it with prod env), so everything should be fine, right? Here is the Monolog config:

monolog:
    handlers:
        main:
            type: stream
            path: "%log_path%"
            level: info
            channels: ["!event"]
        console:
            type: console
            process_psr_3_messages: false
            channels: ["!event", "!doctrine"]
        deprecation:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.deprecations.log"
        deprecation_filter:
            type: filter
            handler: deprecation
            max_level: info
            channels: ["php"]

Logpath value:

parameters:
    log_path: "%env(string:default:default_log_path:LOG_DESTINATION)%"

And log destination is equal to php://stdout

Also for the sake of the test, I add logs directly to index.php to omit framework and monolog, like this

(new Dotenv())->bootEnv(dirname(__DIR__) . '/.env');

$logFile = isset($_SERVER['LOG_DESTINATION']) && $_SERVER['LOG_DESTINATION'] !== ''
    ? $_SERVER['LOG_DESTINATION']
    : 'php://stdout';

try {
     file_put_contents(
         $logFile,
         json_encode(
             [
                 'datetime' => (new DateTimeImmutable())->format('Y-m-dTH:i:s.uP'),
                 'message' => 'Request init.',
             ],
             JSON_THROW_ON_ERROR,
         ) . PHP_EOL,
         FILE_APPEND,
     );
} catch (Throwable $e) {
    file_put_contents(
        $logFile,
        '{"message" : "Error writing logs. ' . $e->getMessage() . '."}' . PHP_EOL,
        FILE_APPEND,
    );
}

register_shutdown_function(
    static function () use ($requestId, $logFile, $start): void {
        $errorArray = error_get_last();
        try {
            file_put_contents(
                $logFile,
                json_encode(
                    [
                        'datetime' => (new DateTimeImmutable())->format('Y-m-dTH:i:s.uP'),
                        'message' => 'Request finished.',
                        'last_error' => is_array($errorArray) ? $errorArray : [],
                        'execution_time_ms' => round((microtime(true) - $start) * 1000),
                    ],
                    JSON_THROW_ON_ERROR,
                ) . PHP_EOL,
                FILE_APPEND,
            );
        } catch (Throwable $e) {
            file_put_contents(
                $logFile,
                '{"message" : "Error writing logs. ' . $e->getMessage() . '."}' . PHP_EOL,
                FILE_APPEND,
            );
        }
    },
);

again I do not see those logs in production, but locally I can see all the logs including this new added to index.php. Maybe there is a config on the PHP level that controls some buffer or something like that?? Why locally with prod env I see those logs, but on production (that actually uses the same docker image) I see only the Nginx log of about 504 but nothing from the application side? Thanks in advance!

Cannot declare class ComposerAutoloaderInit{an ID}, because the name is already in use

Our monitoring system shows this error logs sporadically on any kind of requests. We cannot reproduce it locally and we have a Prod Environment with 25 FPM instances and it happens to occur on different instances. We work with symfony and a lot of different composer packages of course.

This is the exact Error message (anonymized)

Cannot declare class ComposerAutoloaderInit{placeholder for an ID}, because the name is already in use in /home/vcap/app/vendor/composer/autoload_real.php on line 5

Microsoft Entra ID External Authentication Method

I need to implement an external authentication method for Microsoft Entra ID using PHP, but I haven’t found much documentation on it.

According to the documentation, to add an External Authentication Method (EAM), we need to provide:

Client ID
Discovery Endpoint
App ID

Here are the relevant links:

Managing External Authentication Methods
Concept of External Authentication Method Providers

My question is: Do we need to generate the discovery endpoint on the PHP authorization server itself, or is this the URL we obtained while creating the application in Entra: https://login.microsoftonline.com/<tenant_id>/v2.0/.well-known/openid-configuration?

registered the app in portal.azure.com for client id and secret

Update mysql database from updating individual cells

Hi I am developing a project locally and started from this https://codepen.io/fjfalah/pen/WEppVa to create my table linked to my mysql database. I have had no problems in displaying the data but I am experiencing problems in updating the data. Once I edit and update the table I display the message “Record successfully updated” but it doesn’t actually update anything and I don’t have any error messages in both console and logs. I am trying to update only two columns but actually all of them will have to be modified. I will share the code with you, thanks for any suggestions.

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Admin</title>
        <!-- Bootstrap 5 CSS -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
        <link rel="stylesheet" href="style/style.css">
        
        <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> 
        
        <script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script>
    </head>
    <body>
        <div class="main">
            <div class="title-container">
                <h1>Aggiornamento Prezzi</h1>
                <h2> <?= $user_name ?></h2>
            </div>
            <div class="users-container">
                <h2></h2>
                <div class="table-responsive">
                    <div class="position-relative content">
                        <div class="position-absolute w-100 row" style="z-index: 50;">
                            <div class="col-6">
                                <div class="filter-wrapper">
                                    <input type="radio" class="filter-checkbox" name="filter" data-filter="" value="Tutto" checked="checked" />
                                    Tutto
                                    <input type="radio" class="filter-checkbox" name="filter" data-filter="Antintrusione" value="Antintrusione" />
                                    Antintrusione
                                    <input type="radio" class="filter-checkbox" name="filter" data-filter="Antincendio" value="Antincendio" />
                                    Antincendio
                                </div>
                            </div>
                        </div>
                    </div>
                    <br>
                    <table id="sample_data" class="table table-hover">
                        <thead>
                            <tr>
                                <th scope="col"> Prodotti ID</th>
                                <th scope="col">Nome Prodotto</th>
                                <th scope="col">Gamma</th>
                                <th scope="col">Alfanumerico</th>
                                <th scope="col">Descrizione</th>
                                <th scope="col">Assorbimento</th>
                                <th scope="col">Icona 1</th>
                                <th scope="col">Icona 2</th>
                                <th scope="col">Icona 3</th>
                                <th scope="col">Icona 4</th>
                                <th scope="col">Icona 5</th>
                                <th scope="col">Immagine</th>
                                <th scope="col">Garanzia</th>
                                <th scope="col">Riparazione</th>
                                <th scope="col">Costo Acquisto</th>
                                <th scope="col">Prezzo Vendita</th>
                                <th scope="col">Stato</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $var = @$_POST['ProdottiID'] ;
                            $stmt = $conn->prepare("SELECT * FROM `prodotti`");
                            $stmt->execute();
                            $result = $stmt->fetchAll();

                            foreach ($result as $row) {
                                $ProdottiID = $row['ProdottiID'];
                                $NomeProdotto = $row['NomeProdotto'];
                                $Gamma = $row['Gamma'];
                                $Alfanumerico = $row['Alfanumerico'];
                                $Descrizione = $row['Descrizione'];
                                $Assorbimento = $row['Assorbimento'];
                                $Icona1 = $row['Icona1'];
                                $Icona2 = $row['Icona2'];
                                $Icona3 = $row['Icona3'];
                                $Icona4 = $row['Icona4'];
                                $Icona5 = $row['Icona5'];
                                $Immagine = $row['Immagine'];
                                $Garanzia = $row['Garanzia'];
                                $Riparazione = $row['Riparazione'];
                                $CostoAcquisto = $row['CostoAcquisto'];
                                $PrezzoVendita = $row['PrezzoVendita'];
                                $Stato = $row['Stato'];
                            ?>
                          <tr>
                            <td id="ProdottiID" scope="col"><span class="value"><?= $ProdottiID ?></span><div></div></td>
                            <td id="NomeProdotto" scope="col"><span class="value"><?= $NomeProdotto ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Gamma ?></span><div></div></td>
                            <td id="Alfanumerico" scope="col"><span class="value"><?= $Alfanumerico ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Descrizione ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Assorbimento ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Icona1 ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Icona2 ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Icona3 ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Icona4 ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Icona5 ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Immagine ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Garanzia ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Riparazione ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $CostoAcquisto ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $PrezzoVendita ?></span><div></div></td>
                            <td scope="col"><span class="value"><?= $Stato ?></span><div></div></td>
                        </tr>
                                                      <?php
                            }
                            ?>
                      </tbody>
                    </table>
                </div>
            </div>
        </div>
      <script>
        $('table tbody').on('dblclick', 'td', function(){
    var valCell = $(this).find('span').text();
    
    $(this).find('span').hide();
    $(this).find('div').show().html('
      <div class="input-group">
        <input type="text" class="form-control" value="'+valCell+'">
        <span class="input-group-btn">
          <button id="save" class="btn btn-default" type="button"><i class="bi bi-check2"></i></button>
          <button id="close" class="btn btn-default" type="button"><i class="bi bi-x-circle"></i></button>
        </span>
      </div>');
    $(this).find('input').focus();
    $(this).closest('tbody').find('td').not($(this)).each(function(){
      $(this).find('span').show();
      $(this).find('div').hide();
    });
  }); 
  
  $('table').on('click','#close',function(){
    $(this).closest('td').find('span.value').show();
    $(this).closest('div').hide();
  });
    $('table').on('click','#close',function(){
    $(this).closest('td').find('span.value').show();
    $(this).closest('div').hide();
  });
  $('table').on('click','#save', function(){
     var getValueInput = $(this).closest('div').find('input').val();
    $(this).closest('td').find('span.value').text(getValueInput);
    
    $(this).closest('td').find('span.value').show();
    $(this).closest('div').hide();

    jQuery.ajax({
        url: "conn/action2.php",
        method: "POST",
        data: {ProdottiID: $('#ProdottiID').val(), NomeProdotto: $('#NomeProdotto').val(), Alfanumerico: $('#Alfanumerico').val()},
        cache: false,
        success: function(response)
        {
          alert("Record successfully updated");
        }
    });
  });
      </script>
    </body>
</html>

This is the php file for updating the database

<?php

//action2.php


$NomeProdotto = $_POST['NomeProdotto']; 
$Alfanumerico = $_POST['Alfanumerico'];
$ProdottiID = $_POST['ProdottiID'];

//You need create a database connection
$dbhost = 'localhost';
$dbuser = '11111';
$dbpass = '22222';

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "lslistini2");

if(! $conn ){
   die('Could not connect: ' . mysqli_error());
}

$retval = mysqli_query($conn,"UPDATE prodotti SET ProdottiID = '$ProdottiID', NomeProdotto = '$NomeProdotto', Alfanumerico = '$Alfanumerico' WHERE ProdottiID = '$ProdottiID'");

if(! $retval ) {
   die('Could not update data: ' . mysqli_error());
}
echo "Updated data successfullyn";
mysqli_close($conn);


?>

Thanks again for your help

redirect problem when file_get_html on php

I want to see html source of ‘https://piugame.com’ on php. but I got error code like this.

Warning: file_get_contents(https://piugame.com): Failed to open stream: Redirection limit reached, aborting in /simple_html_dom.php on line 82

So, I access ‘https://piugame.com’ on iframe tag. turn on the DevTools and saw this redirect loop.

enter image description here

What is this? and How can I stop this loop?

this is php code about to get html source

<?php
    include 'simple_html_dom.php';

    $html = file_get_html('https://piugame.com');
    echo $html;
?>

and this is html code about to see redirect loop

<HTML>
<iframe src="https://piugame.com"></iframe>
</HTML>

Quantity Key Missing for Some Items When Submitting Order in Laravel

I’m working on a multi-step form in Laravel to handle order submissions. The form allows users to request various items from different categories, and I’m encountering an issue where some items are missing the quantity key in the submitted data. Despite setting a default quantity value for these items, the error persists.
In my application, the order submission involves iterating over the requested items and ensuring that each item has a valid quantity before processing it. However, the log file shows that some items still have a quantity key missing or set to null, even after attempting to set a default value

CODE

Here is the category table

 id | category_name | created_at | updated_at

Here is the product table

id | category_id (fk) | product_name | updated_at | created_at

Here is the inventory table

 id | avaliability | status | weight | sku | product_id (fk) | area | monetary_value | 
 donated_value | created_at | updated_at

Category Model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppModelsProducts;
class Category extends Model
{
    
    protected $table = 'category';  
    protected $fillable = ['category_name'];
    use HasFactory;

    public function products() {
        return $this ->hasMany(Products::class);
    }
}

Products Model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppModelsCategory;

class Products extends Model
{
    protected $table = 'products';
    use HasFactory;

    protected $fillable = ['product_name', 'category_id'];

    public function category() {
        return $this->belongsTo(Category::class);
    }

    public function inventories()
    {
        return $this->hasMany(Inventory::class,'product_id');
    }
    
}

Inventory Model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppModelsProducts;

class Inventory extends Model
{
    protected $table = 'inventory';

    protected $fillable = [
        'sku',
        'product_id', 
        'created_at',
        'updated_at',
    ];

    // Define the relationship to the Product model
    public function product()
    {
        return $this->belongsTo(Products::class,'product_id');
    }
   
    
    use HasFactory;
}
    

HTML FORM

 <h4>Order Section</h4>
<section>
  <div class="row">
     <div class="col-12">
           <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Order Section</h4>
                            </div>          
                            <div class="card-body family-demo-scrollbar">
                                <div class="table-responsive ">
                                <table id="example" class="display" style="min-width: 845px;">
                                 <thead>
                                 <tr>
                                    <th>AVALIABILITY</th>
                                    <th>STATUS</th>
                                    <th>CATEGORY</th>
                                    <th>ITEM NAME</th>
                                    <th>REQUESTED</th>
                                    
                                  </tr>
                                </thead>
                                  <tbody>
                               @foreach($fetchInventoryData as $data)
                               @foreach($data->products as $product)
                               @foreach($product->inventories as $inventory)
                              <tr>
                                <td>{{$inventory->avaliability}}</td>
                                <td style="color: {{ $inventory->status === 'IN STOCK' ? 'green' : 'red' }};">{{ $inventory->status }}</td>

                                

                                <td>{{ $data->category_name }}</td>
                               
                                <td>{{ $product->product_name }}</td>
                                
                                <td>
                                  <!--  <input type="number" name="" id="" min="0" class="form-control"> -->
                                  <input type="number" name="requested[{{ $product->id }}][quantity]" min="0" class="form-control">
                                  <input type="hidden" name="requested[{{ $product->id }}][category]" value="{{ $data->category_name }}">
                                  <input type="hidden" name="requested[{{ $product->id }}][requestedItem]" value="{{ $product->product_name }}">
                                </td>
                               

                                
                              </tr>
                              @endforeach
                               @endforeach
                               @endforeach
                               </tbody>

                              <tfoot>
                                            <tr>
                                                <th>AVALIABILITY</th>
                                                <th>STATUS</th>
                                                <th>CATEGORY</th>
                                                <th>ITEM NAME</th>
                                                <th>REQUESTED</th>
                                                

                                            </tr>
                                        </tfoot>
                                    </table>
                                    <br><br>
                                </div>
                            </div>
             </div>
        </div>
    </div>
</section>

CONTROLLER

 // handling the third section of the multi step form for request order
        $requestedItems = $req->input('requested');

        // Validate or handle missing quantity values (consider front-end validation)
        foreach ($requestedItems as &$itemData) {
          if (!isset($itemData['quantity']) || is_null($itemData['quantity'])) {
            $itemData['quantity'] = 0; // Set a default value (optional)
            // Display a user-friendly error message (front-end)
          }
        }
        unset($itemData); // Unset reference after loop
        
        $categoryTotals = $this->calculateCategoryTotals($requestedItems);
        
        foreach ($requestedItems as $itemData) {
          insertOrderItem($itemData, $categoryTotals[$itemData['category']], now(), $familyId);
        }
        
        function calculateCategoryTotals($requestedItems) {
          $categoryTotals = [];
          foreach ($requestedItems as $itemData) {
            $category = $itemData['category'];
            if (!isset($categoryTotals[$category])) {
              $categoryTotals[$category] = 0;
            }
            $categoryTotals[$category] += $itemData['quantity'];
          }
          return $categoryTotals;
        }
        
        function insertOrderItem($itemData, $categoryTotal, $dateRequested, $familyId) {
          DB::table('requestorder')->insert([
            'category' => $itemData['category'],
            'categoryTotal' => $categoryTotal,
            'requestedItem' => $itemData['requestedItem'],
            'amountNeeded' => $itemData['quantity'],
            'daterequested' => $dateRequested,
            'family_id' => $familyId,
          ]);
        }

ERROR LOGS

[2024-06-28 22:19:25] local.INFO: Requested Items: [{"quantity":null,"category":"BATH","requestedItem":"Hangers"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Lamp"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Lg Rug"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Sm Rug"},{"quantity":null,"category":"Miscellaneous","requestedItem":"TV Tray"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Folding table"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Folding chairs"},{"quantity":"1","category":"bedding","requestedItem":"sheet set"},{"quantity":"2","category":"bedding","requestedItem":"Bed Frame"},{"quantity":"3","category":"bedding","requestedItem":"Comforter"}] 
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"BATH","requestedItem":"Hangers"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"BATH","requestedItem":"Hangers"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lamp"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lamp"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lg Rug"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lg Rug"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Sm Rug"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Sm Rug"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"TV Tray"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"TV Tray"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding table"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding table"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding chairs"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding chairs"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":"1","category":"bedding","requestedItem":"sheet set"} 
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":"2","category":"bedding","requestedItem":"Bed Frame"} 
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":"3","category":"bedding","requestedItem":"Comforter"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"BATH","requestedItem":"Hangers"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lamp"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lg Rug"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Sm Rug"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"TV Tray"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding table"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding chairs"}  
[2024-06-28 22:19:25] local.INFO: Family ID below pdfdata : {"family_id":372} 
                    

How can I allow user to upload file via AJAX. Then read that file using PHP

I am trying to build a file reader on my website. The background idea is for the user to be able to select a JSON file from their PC. Choose it using an upload function on my website, then view the contents of that JSON file on that same page.

I currently have working code for the decoding and outputting of the JSON file. The part I am struggling with is the file upload, and reading the data from the uplaoded file.

The reason I am struggling is that I don’t want the file to be uploaded to my site. I am hoping for the file to be temporary, or read via AJAX and the data outputted from that file. Once the page refreshes, the file and data will be gone. This is designed so I don’t have hundreds of files being uploaded to my website.

The working code I currently have below allows me to change the file url currently with a select form. This works and on the form submit, the php variable $url changes to the option value in the dropdown.

I am now hoping to replace this dropdown select with an upload function so the user can choose any JSON file from their PC.

<script>
<?php 
    if($_POST['Submit']) {
        $url = $_POST['urlchooser'];
        echo $url;
        var_dump($url);
    } else {
        $url = "Choose JSON File";
        echo "Choose JSON File";
        var_dump($url);
    }
?> 
</script>
<form action="" method="post" id="form">
    <select name="urlchooser">
        <option value="<?php echo $url ?>">
            Choose JSON File       
        </option>
        <option value="file1.json">File 1</option>
        <option value="file2.json">File 2</option>
    <input type="submit" name="Submit" id="formsubmit" value="Select File">
</form>

The form above changes the php variable $url which is used to decode and read the file. (I haven’t included all of the decode and output code as this is incredibly long and working fine)

Thanks

How can I use the group prefix outside the closure in Laravel routes

The scenario I want to achieve is that I want to access the prefix $fragment outside the closure.

So this is what I want to achieve:

Route::group([
    'prefix' => '{fragment}',
    'namespace' => 'AppHttpControllers' . 'V' . '{fragment}',
    'middleware' => [
        'v' . '{fragment}' . '.myMiddleWare',
    ],
], function ($pathParam) {
    Route::get(
        'hello',
        function ($fragment) use ($pathParam) {
            return response()->json([$pathParam]);
        }
    );
});

I also thought of doing something like:

request()->getHost()

But it returns null.

So it is quite evident that the variable $fragment would be accessible inside the endpoint /hello but it is not accessible outside of it.

Any help would be highly appreciated.
Thanks!

How to force column to be in array if it matches the whole thing?

I have the following MySQL query:

SELECT tbPacientesComunicacao.id 
FROM tbPacientesComunicacao 
WHERE tbPacientesComunicacao.idRefUser = 1 
   AND tbPacientesComunicacao.idRefPaciente = 4
   AND tbPacientesComunicacao.id IN (
     SELECT idRefComunicacao 
     FROM tbPacientesComunicacaoDestinatarios 
     WHERE idRefUser IN (2,8)
   );

The issue is that MySQL returns the ID if either 2 or 8 matches… how can I say hey only return the id if both numbers (2 and 8) matches?

Table tbPacientesComunicacao

id description
1 Something

Table tbPacientesComunicacaoDestinatarios

idRefComunicacao UserID
1 5
1 7

When a new record is being inserted, I have to check if that record doesn’t match any of the communications already in the database. So I pass the user IDs in an array(5,8) then I have to check it somehow if there is something in the database the matches EXACTLY this combination of UserIDs, in this test it shouldn’t match because I have 5 and 7 not 5 and 8 but using “in” it says it was matched because it found at least one of them… how can I determine that only matches if all numbers in the array matches the table userID?

Issues Importing Excel Data with BelongsTo Relationship in Filament

I am trying to import data from an Excel file into my laravel Filament (V3) application , but I’m having trouble with importing relationships. Specifically, I have a Stock model that has a belongsTo relationship with a Supplier model. During the import, I want to set the supplier_id based on the supplier’s name provided in the Excel file.

Here is the code for my StockImporter class:

<?php

namespace AppFilamentImports;

use AppModelsStock;
use AppModelsSupplier;
use FilamentActionsImportsImportColumn;
use FilamentActionsImportsImporter;
use FilamentActionsImportsModelsImport;

class StockImporter extends Importer
{
    protected static ?string $model = Stock::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('name')
                ->requiredMapping()
                ->rules(['required', 'max:255']),
            ImportColumn::make('description'),
            ImportColumn::make('quantity')
                ->requiredMapping()
                ->numeric()
                ->rules(['required', 'integer']),
            ImportColumn::make('minimum_quantity')
                ->requiredMapping()
                ->numeric()
                ->rules(['required', 'integer']),
            ImportColumn::make('supplier_id')
                ->relationship(resolveUsing: function (string $state): ?Supplier {
                    $supplier = Supplier::query()
                        ->where('name', $state)
                        ->first();

                    return $supplier ? $supplier->id : null;
                }),
            ImportColumn::make('order_id')
                ->rules(['max:255']),
            ImportColumn::make('supplier_order_id')
                ->rules(['max:255']),
            ImportColumn::make('purchase_price')
                ->numeric()
                ->rules(['integer']),
            ImportColumn::make('sale_price')
                ->numeric()
                ->rules(['integer']),
        ];
    }

    public function resolveRecord(): ?Stock
    {
        // return Stock::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        return new Stock();
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Your stock import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';

        if ($failedRowsCount = $import->getFailedRowsCount()) {
            $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
        }

        return $body;
    }
}

quick summary:

  • I am using Filament for handling the import.
  • The Stock model has a belongsTo relationship with the Supplier model.
  • I want to import the supplier_id based on the supplier’s name provided in the Excel file.

Any help or suggestions would be greatly appreciated!

Symfony + doctrine: Can only configure “xml”, “yml”, “php”, “staticphp” or “attribute” through the DoctrineBundle

upgrading symfony from 6 to 7 getting this doctrine error

In AbstractDoctrineExtension.php line 229:
                                                                                                                                                                     
  Can only configure "xml", "yml", "php", "staticphp" or "attribute" through the DoctrineBundle. Use your own bundle to configure other metadata drivers. You can r  
  egister them by adding a new driver to the "doctrine.orm.default_metadata_driver" service definition.            

here is my doctrine.yaml file:

doctrine:
    dbal:
        server_version:    '%env(DATABASE_VERSION)%'
        dbname:            '%env(DATABASE_NAME)%'
        host:              '%env(DATABASE_HOST)%'
        port:              '%env(DATABASE_PORT)%'
        user:              '%env(DATABASE_USER)%'
        password:          '%env(DATABASE_PASSWORD)%'
        driver:            '%env(DATABASE_DRIVER)%'
        charset:            UTF8
        options:
            !php/const PDO::MYSQL_ATTR_SSL_KEY: '%DATABASE_PUB_KEY%'
            !php/const PDO::MYSQL_ATTR_SSL_CERT: '%DATABASE_PRIV_KEY%'
            !php/const PDO::MYSQL_ATTR_SSL_CA: '%DATABASE_CA_CERT%'
            !php/const PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT: false

    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'AppEntity'
                alias: App
        dql:
            numeric_functions:
                rand: DoctrineExtensionsQueryMysqlRand

How to server WordPress site on express?

I am working on a project through which i will be handling multiple WordPress websites through node and express server. I have an express server setup which has an API which allows client to create, update and customize a WordPress website along other things. after creating or updating (which is done through wp cli) the site is stored in a subfolder named website-name in a folder websites. Everything is working perfectly, except the api returns the url:https://localhost/website-name (Yes, I am testing on localhost and i have also tried amazon ec2 instance. result being the same). This url is supposed to open the wordpress site but it doesn’t.

I have also tried using http-proxy but not sure what’s the right way to use it. Also, I have tried keeping the files in static but it too shows the error: Can’t get / url. Any idea, how to serve the wordpress websites using the node and express server?

There are multiple websites, for example:

/websites/website_a_unique_identifier

/websites/website_b_unique_identifier

and inside All the wordpress files.

PHP PUT JSON QUERY [closed]

please anyone can help me to output the json request?
follow this link to create an invoice ? here is the link perfexcrm.themesic.com/apiguide/#api-Invoices-PostInvoice

thanks

need to get the JSON query from this documentation