Creating a Secure WordPress User-based File Upload System (using ACF)

I am working on implementing a user-based file upload system in WordPress, and I want to ensure that the process is secure for users. Currently, I am using Advanced Custom Fields (ACF) to handle file uploads. When a user uploads a file, I aim to create a custom folder structure with their user_nicename and user_id to organize the files efficiently.

My idea is to create a folder for each user and then check if the folder matches the current user. If it does, the user should be able to see their uploaded files; otherwise, access should be restricted. How can I implement this check effectively and is this safe?

(I use woocommerce for creating accounts.)

What I am trying to do:

  • Upload a file to a custom directory with the user name
  • make the directory only accesible for admins and the loggedin user.

The code that currently handles the uploading of the files.

add_filter('acf/upload_prefilter/key=field_65a6a42f132d2', 'prefilter_avatar_upload');

                        function prefilter_avatar_upload($errors) {
                            add_filter('wp_handle_upload_prefilter', 'avatar_upload_rename');
                            add_filter('upload_dir', 'modify_avatar_upload_dir');
                            return $errors;
                        }
    
                        // Function to modify the upload directory
                        function modify_avatar_upload_dir($uploads_avatars) {
                            $user_id = get_current_user_id();
                            $user_info = get_userdata($user_id);
                            $username = $user_info->user_nicename;
    
                            $uploads_avatars['path'] = $uploads_avatars['basedir'] . '/useruploads/' . $username . $user_id;
                            $uploads_avatars['url']  = $uploads_avatars['baseurl'] . '/useruploads/' . $username . $user_id;
    
                            return $uploads_avatars;
                        }
    
                        function avatar_upload_rename($file) {
                            return $file;
                        }
    
    
    
    
    
    
                    acf_form_head();
                    $options = array(
                        'post_id' => 'user_'.$current_user->ID,
                        'field_groups' => array('group_65a656c14a386'),
                        'form' => true, 
                        'return' => add_query_arg( 'updated', 'true', get_permalink() ), 
                        'html_before_fields' => '',
                        'html_after_fields' => '',
                        'submit_value' => 'Update' 
                    );
                    acf_form( $options );`

I appreciate any guidance or code examples that can help me achieve a secure and user-friendly file upload system in WordPress. Thank you!

Export a Pods Package to a file

I use the pods plugin version 3.0.10 and when I export via the wp cli with the command: wp pods export –all but I get this error:

Error: ‘export’ is not a registered subcommand of ‘pods’. See ‘wp help pods’ for available subcommands. What should I do? I’d like to export all the configs and also be able to import them via the wp cli?

i would like to import and export pods plugin configs via wp clli

pods export –all but I get this error:

Error: ‘export’ is not a registered subcommand of ‘pods’. See ‘wp help pods’ for available subcommands.

Using OOP PHP with MVC architecture to build a simple web page without using frameworks like Doctrine

fellow developers!

I recently started getting into PHP and was trying to build a simple web page using OOP and MVC architecture. There are plenty of tutorials on OOP and MVC out there, but they usually give the same simplified example of a Login System, which is not quite the thing I was looking for. So, I was starting to wonder, maybe I am looking for something, which is not right and should try a different approach.

In my example I will have 3 tables (Users, Books and Lending)

  1. users (user_id, user_name, user_address)
  2. books (book_id, book_name, date_of_release)
  3. lending (lending_id, book_id, user_id, lending_date, return_date)

For each of those entities I’m planning to create separate View, Model and Control classes.

My project structure currently look something like this:

-classes
   -dbh.class.php
-controllers
   -user.controller.class.php
   -book.controller.class.php
   -lending.controller.class.php
-includes
   -autoloading.inc.php
-models
   -user.model.class.php
   -book.model.class.php
   -lending.model.class.php
-views
   -user.view.class.php
   -book.view.class.php
   -lending.view.class.php
-index.php

My models will contain User, Book and Lending classes with setters, getters etc.

The home page will have a button, which will load an information about lendings from JSON file and upload it to the database. Also, I will have a form for fetching the lendings from Database and showing the results using filters.

So, my two questions are:

  1. Which file (or should I say Class) will be responsible for the main logic of the website? Should I build an extra Class (exp. Repository.class) with Model, View and Controller or is there a better way?

  2. When loading the information from JSON file, what is the best approach in doing so using the Entities classes? Right now I am thinking of writing methods inside Lending class which will create User and Book classes and then use their build in methods to update their tables, but for some reason, that approach seems to me too complicated.

I am aware of frameworks like Doctrine, which will handle the Database logic for me, but I was wondering, if there is a more plain PHP way to do this.

Thank you all in advance!

Create a custom wordpress menu shows a list of posts as sub menu based on its parent menu items (categories) and display using a shortcode

I have a custom post-types called products that contain a list of products.

I have created a menu called hierarchical menu in wordpress dashboard > appearance > menus as illustrated below:

Electronics
  -> Camera
  -> Headphones
  -> Tv accessories
Computers
  -> Monitors
  -> Keyboards
  -> Mouse
Stationaries
  -> Pen
  -> Pencil
  -> Notebooks
-> Paper

I need to create and display a custom menu using shortcode for eg., If I click on camera it displays a list of posts from Product post type with categories of electronics, camera as a submenu

Electronics
-> Camera
  --> list of posts with categoreis Electronics / Camera (dynamic)

I am not sure how to go about creating this. I use below code to generate the menu and display using shortcode. But I have zero clue on how to dynamically show the list of posts based on its parent criteria. Any help / Guidance greatly appreciated would be greatly appreciated.

function custom_hierarchical_menu($atts) {
    $menu_html = wp_nav_menu( array(
        'menu'   => 'Hierarchy Desktop Menu',
        'echo'   => false, // Set 'echo' to false to store the HTML in $menu_html
    ) );
}
add_shortcode('customHierarchicalMenu', 'custom_hierarchical_menu');

PHP unzip deflate64

I am currently facing an issue while trying to decompress a ZIP file that utilizes Deflate64 compression in PHP using the ZipArchive class. The extraction process seems to be working well for regular Deflate compression, but encounters difficulties when dealing with Deflate64.

Here’s an example of a successful extraction using regular Deflate compression:

$zip = new ZipArchive();
$zip->open('deflate.zip');
$zip->extractTo('/tmp/test_extract');
(bool) true

However, when attempting to extract a ZIP file that uses Deflate64 compression, the process fails:

$zip = new ZipArchive();
$zip->open('deflate64.zip');
$zip->extractTo('/tmp/test_extract');
(bool) false

Furthermore, checking if Deflate64 compression is supported using ZipArchive::isCompressionMethodSupported returns false:

ZipArchive::isCompressionMethodSupported(ZipArchive::CM_DEFLATE64);
(bool) false

On the other hand, regular Deflate compression is supported:

ZipArchive::isCompressionMethodSupported(ZipArchive::CM_DEFLATE);
(bool) true

I am reaching out to the community to inquire if there is a known solution or workaround to enable the extraction of ZIP files using Deflate64 compression in PHP’s ZipArchive class. Any insights or code snippets that address this issue would be greatly appreciated.

Thank you in advance for your assistance!

PHP Xero API > Ceate Invoice not recieving customer address details

I’m having an issue with XERO Api when creating invoices. It all works fine apart from the addess and contact number do not pull through to XERO. Below is the code I’m using. There are no errors and the contact is created and invoice email sent just no address details. Can anyone see anything I’m missing?

        
       
         
        $xeroTenantId = $this->Storage_model->getSession()['tenant_id'];
        
        
        if ($this->Storage_model->getHasExpired()) {
            $provider = new LeagueOAuth2ClientProviderGenericProvider([
            'clientId'                => 'xxxxxxxxxx',
            'clientSecret'            => 'xxxxxxxxxx',
            'redirectUri'             => 'xxxxxxxxxx.co.uk/callback',
            'urlAuthorize'            => 'https://login.xero.com/identity/connect/authorize',
            'urlAccessToken'          => 'https://identity.xero.com/connect/token',
            'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation'
          ]);

            $newAccessToken = $provider->getAccessToken('refresh_token', [
              'refresh_token' => $this->Storage_model->getRefreshToken()
            ]);

            // Save my token, expiration and refresh token
            $this->Storage_model->setToken(
                $newAccessToken->getToken(),
                $newAccessToken->getExpires(),
                $xeroTenantId,
                $newAccessToken->getRefreshToken(),
                $newAccessToken->getValues()["id_token"] );
          }
        

        $config = XeroAPIXeroPHPConfiguration::getDefaultConfiguration()->setAccessToken( (string)$this->Storage_model->getSession()['token'] );
        
        $apiInstance = new XeroAPIXeroPHPApiAccountingApi(
              new GuzzleHttpClient(),
              $config
          );
            
           
        
            $idempotencyKey = rand()."IDDEMP";
            $summarizeErrors = true;
            $unitdp = 4;
            $dateValue = new DateTime('now');
            $dueDateValue = new DateTime('now');
            $dueDateValue->modify("+1 month");
            
            //test data
            $contact['firstName'] = "Fred";
            $contact['surname'] = "Blogs";
            $contact['email'] = "[email protected]";
            $contact['contactNumber'] = "079671111111";
            $contact['billingAddress1'] = "Address 1";
            $contact['billingAddress2'] = "Address 2";
            $contact['billingAddress3'] = "Address 3";
            $contact['billingAddress4'] = "Address 4";
            $contact['billingPostcode'] = "DT94XX";
            
            //[add a contact]
            $setFirstName = $contact['firstName'];
            $setLastName = $contact['surname'];
            $setEmailAddress = $contact['email'];
            $setContactNumber = $contact['contactNumber'];
         
             $address = array(array(
                'AddressType' => 'STREET',
                'AddressLine1' => $contact['billingAddress1'],
                 'AddressLine2' => $contact['billingAddress2'],
                'City' => $contact['billingAddress3'],
                 'State' => $contact['billingAddress4'],
                'PostalCode' => $contact['billingPostcode']
            ));
         
        
            $contact = new XeroAPIXeroPHPModelsAccountingContact;
            $contact->setName($setFirstName." ".$setLastName)
                ->setFirstName($setFirstName)
                ->setLastName($setLastName)
                ->setEmailAddress($setEmailAddress)
                ->setContactNumber($setContactNumber)
                ->setAddresses($address);
          
            $arr_contacts = [];
            array_push($arr_contacts, $contact);
            
            $contacts = new XeroAPIXeroPHPModelsAccountingContacts;
            $contacts->setContacts($arr_contacts);

            $apiResponse = $apiInstance->createContacts($xeroTenantId,$contacts);
            //[/add a contact]
            $lineItems = array();

            $lineItemTracking = new XeroAPIXeroPHPModelsAccountingLineItemTracking;
            $lineItemTracking->setTrackingCategoryID('00000000-0000-0000-0000-000000000000');
            $lineItemTracking->setTrackingOptionID('00000000-0000-0000-0000-000000000000');
            $lineItemTrackings = [];
            array_push($lineItemTrackings, $lineItemTracking);
            
         foreach($order as $value) {
            $lineItem = new XeroAPIXeroPHPModelsAccountingLineItem;
            $lineItem->setDescription($value['rowTitle']);
            $lineItem->setQuantity($value['rowQty']);
            $lineItem->setUnitAmount($value['rowPrice']);
            $lineItem->setAccountCode('200');
            $lineItem->setTracking($lineItemTrackings);
            array_push($lineItems, $lineItem);
         }
            

            $invoice = new XeroAPIXeroPHPModelsAccountingInvoice;
            $invoice->setType(XeroAPIXeroPHPModelsAccountingInvoice::TYPE_ACCREC);
            $invoice->setContact($contact);
            $invoice->setDate($dateValue);
            $invoice->setDueDate($dueDateValue);
            $invoice->setLineItems($lineItems);
            $invoice->setReference($contact['reference']);
            $invoice->setStatus('AUTHORISED');  //$invoice->setStatus(XeroAPIXeroPHPModelsAccountingInvoice::STATUS_DRAFT);
         
        
        
            $invoices = new XeroAPIXeroPHPModelsAccountingInvoices;
            $arr_invoices = [];
            array_push($arr_invoices, $invoice);
            $invoices->setInvoices($arr_invoices);
            
        
            try {
              $result = $apiInstance->createInvoices($xeroTenantId, $invoices, $idempotencyKey, $summarizeErrors, $unitdp);
              $data = XeroAPIXeroPHPAccountingObjectSerializer::sanitizeForSerialization($result);
             
                //email invoice
                $requestEmpty = new XeroAPIXeroPHPModelsAccountingRequestEmpty;
               
                try {
                    $idempotencyKey = rand()."IDDEMP";  
                    $apiInstance->emailInvoice($xeroTenantId, $invocieID = $data->Invoices[0]->InvoiceID, $requestEmpty, $idempotencyKey);
                    } catch (Exception $e) {
                      echo 'Exception when calling AccountingApi->emailInvoice: ', $e->getMessage(), PHP_EOL;
                    }
                
            } catch (Exception $e) {
              echo 'Exception when calling AccountingApi->createInvoices: ', $e->getMessage(), PHP_EOL;
            }
            
        echo "complete";
        
    }

correct write the second query

I have a big problem because I don’t know how to correctly write the second query. I ask for help.

The table vt_personale has

user_nome 
user_cognome 
user_postazione 
user_coordinatore

The table vt_formaz_corsi has

user_nome (the same of vt_personale but split user_nome e user_cognome) 

and other values

<div class="card-datatable table-responsive pt-0  p-3 w-100" > 
    <table id="emp-table" class="datatables-basic table table-bordered  p-3 w-100" width="100%">
        <thead> 
            <tr>
                <th>Cognome Nome</th>
                <th>Postazione</th>
                <th>Coordinatore</th>
                <th style="max-width:220px">Corso</th>
                <th>Tipo</th>
                <th>Ultimo corso</th>  
                <th>Scadenza</th>
                <th></th>
                <th></th>
            </tr> 
            <tr>
                <th>Cognome Nome</th>
                <th>Postazione</th>
                <th>Coordinatore</th>
                <th style="max-width:220px">Corso</th>
                <th>Tipo</th>
                <th>Ultimo corso</th>
                <th>Scadenza</th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Cognome Nome    </th>
                <th>Postazione</th>
                <th>Coordinatore</th>
                <th style="max-width:220px">Corso</th>
                <th>Tipo</th>
                <th>Ultimo corso</th>
                <th>Scadenza</th>
                <th></th>
                <th></th>
            </tr>
        </tfoot>
        </thead>
        <tbody class="table-border-bottom-0" id="myTable">
            <?php  $num = 0;
            include_once 'main.php';
            $stmt = $DB_con->prepare('SELECT * FROM vt_formaz_corsi ORDER BY user_nome ASC');
            $stmt->execute();
            $Count= $stmt->rowCount();
            if($stmt->rowCount() > 0){
                while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);
            ?>
                <tr>
                    <td class="center"><?php echo $row['user_nome']; ?></td>
                    <?php  // this is the second query that not read
                    $stmtpersonale = $DB_con->prepare("SELECT *  FROM vt_personale as P  INNER JOIN vt_formaz_corsi as C WHERE CONCAT_WS(P.user_cognome, ' ', P.user_nome) = '.(string)$row['user_nome'].'");
                    $stmtpersonale->execute(); $Countpers= $stmtpersonale->rowCount();
                    if($stmtpersonale->rowCount() > 0) {
                    while($row4=$stmtpersonale->fetch(PDO::FETCH_ASSOC)){
                    extract($row4); 
                    ?>
                    <td class="center"><?php echo $row4['user_postazione']; ?></td>
                    <td class="center"><?php echo $row4['user_coordinatore']; ?></td>
                    <?php  } } ?>
                    <td class="center  p-3 w-100" style="width:50%"><?php echo $row['user_corso']; ?></td>
                    <td class="center"><?php echo $row['user_residenziale']; ?></td>
                    <td class="center"><?php echo $result; ?></td>
                    <td class="center"> <?php echo $resultscadenza;?></td>
                    <td class="center"> <?php echo $$differenza;?></td>
                </tr>
            <?php } }else{?>
                    <div class="col-xs-12">
                    <div class="alert alert-warning"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; Nessun dato trovato ... </div>
                    </div>
            <?php}?>
            <?phpob_end_flush();?>
        </tbody> 
    </table>  
</div>

PHP: Find max key which is smaller or equal than a given value [duplicate]

I have a multidimensional array which uses dates in the form of yyyy-mm-dd as its key.
What is the most efficient way of finding the max key that is <= to a given value?

$array (
"2023-01-01" => array (),
"2023-07-25" => array (),
"2023-08-03" => array (),
"2023-09-07" => array (),
)

For example: given the date 2023-08-16, how could I find 2023-08-03 (the max date which is smaller or equal to 2023-08-16)?

images not showing after creating more than 1 header in custom wp theme

Fairly new to this, I have a WordPress custom theme that I have added 2 headers to (header.php and header-hero.php), the headers have been called correctly and are successfully showing on the desired pages, but since setting up the 2 headers I can no longer see any images at all on any pages, EXCEPT for the one image (Hero image) that is being called in the CSS file, all images called in other files aren’t showing. I’m assuming it’s something silly in my image path that needs to change with multiple headers?

Path for default header: /staging_html/wp-content/themes/unilab_theme/header.php
Path for hero header: /staging_html/wp-content/themes/unilab_theme/header-hero.php
path for images: /staging_html/wp-content/themes/unilab_theme/images

Should the new headers be stored somewhere else maybe? not in the unilab_theme folder?

Very grateful for any help!! TIA

should wp_head() have any code in the parentheses? i.e. wp_head(‘hero’) ?

update: login is also playing up since creating the headers (see attached image)

[Custome theme root folder](https://i.stack.imgur.com/FceGk.png)

Set the checkboxes for a Filament Checkboxlist based on another field value and a relationship

I have a Laravel Filament Checkboxlist named contact_ids:

CheckboxList::make('contact_ids')
    ->reactive()
    ->options([])
    ->searchable()
    ->columns(1),

I want to display the checkboxes that appear on this list based on a relationship:

public function contacts(): HasManyThrough {
    return $this->hasManyThrough(Contact::class, Client::class);
}

I’ve tried to add some reactivity to my Select::make('client_id') like this:

Select::make('client_id')
    ->relationship('client', 'name')
    ->searchable(['name'])
    ->preload()
    ->required()
    ->reactive()
    ->createOptionForm(Client::getForm())
    ->afterStateUpdated(function ($set, $state) {
                              // Update the options for the contact_ids CheckboxList based on the selected client
                              $set('contact_ids', []); // Clear the selected contacts when the client changes
                              $contacts = Contact::where('client_id', $state)->pluck('last_name', 'id');
                              $set('contact_ids.options', $contacts); // Update the options for the CheckboxList
                          }),

But this does not update the checkboxlist.

What is the right signature for a data provider?

Is not a real problem but during a pull request I saw a comment a dataProvider like:

public function fooBar()
{
    return [
        ['some', 'data', 'here'],
        ['and', 'here']
    ];
}

And someone commented that method should be static. Documentation says that… “A data provider method must be public and either return an array of arrays or an object that implements the Iterator interface and yields an array for each iteration step.” and no static is mentioned.

Documentation is clear but… Must, or can, be static in some cases? Are there some rules about this stuff that are not in the documentation?

how to display mysql database value id select dropdown in jsgrid

i am trying to show mysql data in select dropdown in jsgrid.
$('#grid_table').jsGrid({ width: "100%", height: "600px", filtering: true, inserting:true, editing: true, sorting: true, paging: true, autoload: true, pageSize: 10, pageButtonCount: 5, deleteConfirm: "Do you really want to delete data?", controller: { loadData: function(filter){ return $.ajax({ type: "GET", url: "fetch.php", data: filter }); }, insertItem: function(item){ return $.ajax({ type: "POST", url: "fetch.php", data:item }); }, updateItem: function(item){ return $.ajax({ type: "PUT", url: "fetch.php", data: item }); }, }, fields: [ { name: "Module_Id", type: "select", width: 150, validate: "required" }, { name: "Module_Name", type: "text", width: 150, validate: "required" }, { name: "View_Rights", type: "select", items: [ { Name: "", Id: '' }, { Name: "Yes", Id: 'Y' }, { Name: "No", Id: 'N' } ], valueField: "Id", textField: "Name", width: 50, validate: "required" }, { name: "Create_Rights", type: "select", items: [ { Name: "", Id: '' }, { Name: "Yes", Id: 'Y' }, { Name: "No", Id: 'N' } ], valueField: "Id", textField: "Name", width: 50, validate: "required" }, { name: "Modify_Rights", type: "select", items: [ { Name: "", Id: '' }, { Name: "Yes", Id: 'Y' }, { Name: "No", Id: 'N' } ], valueField: "Id", textField: "Name", width: 50, validate: "required" }, { name: "Delete_Rights", type: "select", items: [ { Name: "", Id: '' }, { Name: "Yes", Id: 'Y' }, { Name: "No", Id: 'N' } ], valueField: "Id", textField: "Name", width: 50, validate: "required" }, { name: "Print_Rights", type: "select", items: [ { Name: "", Id: '' }, { Name: "Yes", Id: 'Y' }, { Name: "No", Id: 'N' } ], valueField: "Id", textField: "Name", width: 50, validate: "required" }, { type: "control" } ] }); fetch.php <kbd>if($method == 'GET') { $data = array( ':id' => "%" . $_GET['id'] . "%", ':Module_Name' => "%" . $_GET['Module_Name'] . "%", ':View_Rights' => "%" . $_GET['View_Rights'] . "%", ':Create_Rights' => "%" . $_GET['Create_Rights'] . "%", ':Modify_Rights' => "%" . $_GET['Modify_Rights'] . "%", ':Delete_Rights' => "%" . $_GET['Delete_Rights'] . "%", ':Print_Rights' => "%" . $_GET['Print_Rights'] . "%" ); $query = "SELECT * FROM user_detail WHERE User_Name = :User_Name AND Module_Name LIKE :Module_Name AND View_Rights LIKE :View_Rights AND Create_Rights LIKE :Create_Rights AND Modify_Rights LIKE :Modify_Rights AND Delete_Rights LIKE :Delete_Rights AND Print_Rights LIKE :Print_Rights ORDER BY id DESC"; $statement = $connect->prepare($query); $statement->execute($data); $result = $statement->fetchAll(); foreach($result as $row) { $output[] = array( 'id' => $row['id'], 'User_Name' => $row['User_Name'], 'Module_Id' => $row['Module_Id'], 'Module_Name' => $row['Module_Name'], 'View_Rights' => $row['View_Rights'], 'Create_Rights' => $row['Create_Rights'], 'Modify_Rights' => $row['Modify_Rights'], 'Delete_Rights' => $row['Delete_Rights'], 'Print_Rights' => $row['Print_Rights'] //'Created_On' => date('Y-m-d H:i:s',$row['Created_On']) //'Modified_On' => $row['Modified_On'] ); } header("Content-Type: application/json"); echo json_encode($output); } if($method == "POST") { $data = array( ':Module_Name' => $_POST['Module_Name'], ':View_Rights' => $_POST["View_Rights"], ':Create_Rights' => $_POST["Create_Rights"], ':Modify_Rights' => $_POST["Modify_Rights"], ':Delete_Rights' => $_POST["Delete_Rights"], ':Print_Rights' => $_POST["Print_Rights"], ':Created_On' => date('Y-m-d H:i:s') ); $query = "INSERT INTO user_detail (User_Name,Module_Name, View_Rights, Create_Rights, Modify_Rights,Delete_Rights,Print_Rights,Created_On) VALUES (:User_Name, :Module_Name, :View_Rights, :Create_Rights, :Modify_Rights, :Delete_Rights, :Print_Rights, :Created_On)"; $statement = $connect->prepare($query); $statement->execute($data); } if($method == 'PUT') { parse_str(file_get_contents("php://input"), $_PUT); $data = array( ':id' => $_PUT['id'], ':User_Name' => $_PUT['User_Name'], ':Module_Name' => $_PUT['Module_Name'], ':View_Rights' => $_PUT['View_Rights'], ':Create_Rights' => $_PUT['Create_Rights'], ':Modify_Rights' => $_PUT['Modify_Rights'], ':Delete_Rights' => $_PUT['Delete_Rights'], ':Print_Rights' => $_PUT['Print_Rights'], ':Modified_On' => date('Y-m-d H:i:s') ); $query = " UPDATE user_detail SET Module_Name = :Module_Name, View_Rights = :View_Rights, Create_Rights = :Create_Rights, Modify_Rights = :Modify_Rights, Delete_Rights = :Delete_Rights, Print_Rights = :Print_Rights, Modified_On = :Modified_On WHERE id = :id AND User_Name = :User_Name "; $statement = $connect->prepare($query); $statement->execute($data); } Appreciate anyone help me with the codings

Laravel Attempt to read property “alias” on null

Route::get('catalog/{catname}', [MainController::class, 'getCatalog'])->name('catalog.page');
Route::get('catalog/{catname}/{alias}', [MainController::class, 'getItemsForList'])->name('catalog.view.item');

When I click on the link /catalog/table/table-black-and-white, I get an error

Attempt to read property "alias" on null

During development, I connected the database via belongsToMany


AppModelsCatalog

public function items() : BelongsToMany
{
return $this->belongsToMany(Item::class);
}

AppModelsItem
public function catalogs() : BelongsToMany
{
return $this->belongstoMany(Catalog::class);
}

The controller has two entries for outputting information

public function getCatalog($alias)
    {
        $cats = Catalog::where('alias', $alias)->first();
        $cats->items;
        return view('template.sait.page.catalog', compact('cats'))->with('alias', $alias);
    }

    public function getItemsForList($alias)
    {
        $data = Item::where('alias', $alias)->with('catalogs')->first();
        return view('template.sait.page.catalog.view', compact('data'))->with('alias', $alias);
    }

And in the view I display it like this:

@foreach($cats->items as $item)
.....
.....
<a href="{{route(''catalog.view.item'', $item->alias)}}">env</a>

As far as I understand, there is an error in my controller, and apparently I also do not fully indicate the route in the view, since sometimes I still get the error of missing “alias” field

Undefined array key “name”, Undefined array key 0 [duplicate]

I have a variable named $authorSpotlightData , while dd($authorSpotlightData); it returns an array in the same blade file: Now, while i want the data ‘name’ in my

in my blade file : it says Undefined array key “name” also Undefined array key 0.
this is my p tag. Both are not working.

<h5 class="card-title">{{ $authorSpotlightData[0]['name'] }}</h5>
<h5 class="card-title">{{ $authorSpotlightData['name'] }}</h5>

Result Undefined array key “name” also Undefined array key 0.
Some controller code that may be useful are:
Controler Function

public function getRandomAuthorSpotlight()
    {
        $data = $this->getAuthorSpotlightData();

        // Get a random item from the array
        $randomItem = $data[array_rand($data)];
        return view('QuotesPartials.AuthorSpotlight', ['authorSpotlight' => $randomItem]);
    }
**AppServiceProvider**

public function boot()
    {
        // Fetch author spotlight data using the controller method
        $authorSpotlightController = new AuthorSpotlightController();
        $randomItem = $authorSpotlightController->getRandomAuthorSpotlight();
        $data = $randomItem->getData();
        // Share the random item with all views
        view()->share('authorSpotlightData', $data);
    }
*Output of dd($authorSpotlightData);
array:1 [▼ // resources/views/QuotesPartials/AuthorSpotlight.blade.php
  "authorSpotlight" => array:6 [▼
    "id" => 2
    "image1" => "Book1.jpg"
    "image2" => "Book2.jpg"
    "image3" => "Book1.jpg"
    "name" => "Brijesh"
    "description" => "This is Brijesh"
  ]
]*

I tried everything but couldn’t find where the problem is:

I think something is wrong with the AppServiceProvider as this is new to me.
while dd($randomItem[‘name’]); it returned me the name in my controller.php file, But in this AppServiceProvider.php it says Undefined array key “name”. also for and dd($data[‘name’]);

My goal is to have the name of the array and be on my p tag in my blade file.

ApexChart Combo Chart Bar/Line Display issue On Multple Line label And yaxis

Hello all i’m having an issue regarding the Apexchart. I’m creating a combo chart which is combination of bar chart and line chart. The issue here is the multiple set of dataset for line chart. which the Yaxis of the line chart is not reflect to the value of dataset and also the label of the line chart especially for the datasets that have set of 0 value, it appear at top of the chart.enter image description here i highlighted the image with red color which indicate the issue that i facing. i will provide the jsfiddle here jsfiddle.

var options = {
          series: [{
          name: 'All Data',
          type: 'column',
          data: [252600, 203280, 163800, 136458]
        }, {
          name: 'Section1',
          type: 'line',
          data: [0,0,0,0]
        },{
          name: 'Section2',
          type: 'line',
          data: [0,0,0,0]
        },{
          name: 'Section3',
          type: 'line',
          data: [0,0,0,0]
        },{
          name: 'Section4',
          type: 'line',
          data: [29040,16920,0,0]
        },{
          name: 'Section5',
          type: 'line',
          data: [26280,15960,0,7200]
        }],
          chart: {
          height: 450,
          type: 'line',
        },
        title: {
          text: 'Traffic Sources'
        },
        dataLabels: {
          enabled: true,
          enabledOnSeries: [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
        },
        labels: ['11 Jan 2001', '12 Jan 2001', '13 Jan 2001', '14 Jan 2001'],
        xaxis: {
          type: 'datetime'
        },
        yaxis: [{
          title: {
            text: 'All Data',
          },
        
        }, {
          opposite: true,
          title: {
            text: 'Section Data'
          }
        }]
        };

        var chart = new ApexCharts(document.querySelector("#chart"), options);
        chart.render();

i wish its not the Apexchart it self doesn’t support this kind of method. The line chart value should using the opposite side of the Y-axis, but it seem not work in this kind of situation

i did try on the line dataset value without using any 0 value contain in each set of it, and it works. But once the line dataset is contain 0 value in each of dataset, this issue occured.