iam updating my category and found error The PUT method is not supported for this route. Supported methods: GET, HEAD, POST

I Just wanna to creating some category(i am from indonesia). And i found a bug when i am just try updating my category.

This is my routes

routes

This is my controller

controller

this is my blade

@extends('admin.master')

@section('judul')
    Edit Kategori
@endsection

@section('content')
    <form action="/kategori" method="POST">
        @csrf
        @method('PUT')
        <div class="row">
            <div class="col-lg-8 col-sm-12">
            @if($errors->any())
                <div class="alert alert-danger alert-dismissible mb-3">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <h5><i class="icon fas fa-ban"></i> Error : </h5>
                    @foreach ($errors->all() as $error)
                        {{ $error }}
                    @endforeach
                </div>
            @endif
            <div class="col-lg-8 col-sm-12">
                <div class="form-group">
                    <input type="text" class="form-control" name="judul" id="isi" placeholder="Judul" autocomplete="off" required value="{{ $kategori->judul }}">
                </div>
            </div>
            <div class="col-lg-8 col-sm-12">
                <div class="form-group">
                    <textarea name="isi" id="isi" cols="30" rows="10" placeholder="Isi" class="form-control" style="resize:none;">{{ $kategori->isi }}</textarea>
                </div>
            </div>
            <div class="col-lg-8 col-sm-12">
                <button type="submit" class="btn btn-success">Edit</button>
            </div>
        </div>
    </form>
@endsection

PHP – Get Value from Another Key WIthin Same Object if Match

I want to fetch Member X of tierName into a variable when tierType match apiResponse (return value accodring to clientData that compared with apiResponse).

<?php
$clientData = '[{"tierType":"10","tierName":"Member A","isActive":"1"},{"tierType":"20","tierName":"Member B","isActive":"1"},{"tierType":"30","tierName":"Member C","isActive":"1"}]';
 
 $data = json_decode($clientData, true);
 $apiResponse = 10;
 
 foreach($data as $key=>$value)
 {
    if($apiResponse == $value['tierType'])
    {
        $variable =  "Member A";
        return $variable;
    }   
 }

?>

Is this possible in PHP? I tried $variable = $value['tierName']; but didn’t work.

Thank you in advance.

Getting wordpress menu to open submenu on click on the main menu item

I’ve looked at many of the answers on this website but none of them are working on my website

I have the mobile version working with a workaround code

    window.addEventListener('load', function(){
    var menuItems = document.getElementsByClassName("menu-item-has-children");
    
    /*
     * Bij aanpassing mobiel menu, console.log(menuItems);
     * aanzetten, controleer de indexen van de mobiele menu items
     */
    // console.log(menuItems);
    
    menuItems[5].firstChild.removeAttribute("href");
    menuItems[5].firstChild.setAttribute("href", "#");
    menuItems[5].firstChild.addEventListener('click', (event) => {
        menuItems[5].firstChild.lastChild.click();
    });
    menuItems[6].firstChild.removeAttribute("href");
    menuItems[6].firstChild.setAttribute("href", "#");
    menuItems[6].firstChild.addEventListener('click', (event) => {
        menuItems[6].firstChild.lastChild.click();
    });
    menuItems[7].firstChild.removeAttribute("href");
    menuItems[7].firstChild.setAttribute("href", "#");
    menuItems[7].firstChild.addEventListener('click', (event) => {
        menuItems[7].firstChild.lastChild.click();
    });
    menuItems[8].firstChild.removeAttribute("href");
    menuItems[8].firstChild.setAttribute("href", "#");
    menuItems[8].firstChild.addEventListener('click', (event) => {
        menuItems[8].firstChild.lastChild.click();
    });
    menuItems[9].firstChild.removeAttribute("href");
    menuItems[9].firstChild.setAttribute("href", "#");
    menuItems[9].firstChild.addEventListener('click', (event) => {
        menuItems[9].firstChild.lastChild.click();
    });
});

But I want the desktop version to work the same way. The hover function can go if it’s in the way.

I’ve tried this code, but it doesn’t do the trick.

 if(clicked == false){
    document.getElementById("menu-item-has-children").style.display = "none";
    clicked = true;
}else if (clicked == true){
    document.getElementById("menu-item-has-children").style.display = "block";
    clicked = false;
}

The Satelite them is a real @#$ if it comes to the codes. I’ve looked and looked, but I can’t find the code that works the hover anywhere (probably tucked away in a file I’ll never find). But I’m using a child theme anyway, so I can add .php an .js files to overwrite anything. I just haven’t found anything that works. Does anyone have any idea of how I could get this on click show of the sub menu to work?

How To Change The Button Text “Add to cart” in Wooccomerce With The Divi Theme

I am trying to change the Add To Cart text on the product page button to Buy Now
I’ve tried using the function that’s being posted everywhere to solve the issue but somehow that doesn’t seem to do the trick, also using a WordPress plugin is not changing the text.

So far I’ve found the following function

// To change add to cart text on single product page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woocommerce_custom_single_add_to_cart_text' ); 
function woocommerce_custom_single_add_to_cart_text() {
    return __( 'Buy Now', 'woocommerce' ); 
}

// To change add to cart text on product archives(Collection) page
add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_product_add_to_cart_text' );  
function woocommerce_custom_product_add_to_cart_text() {
    return __( 'Buy Now', 'woocommerce' );
}

Adding that to my Code Inserter creates an error and breaks the website.

I think that Divi is overruling the function from somewhere. Any tips or ideas?

undefined variable: article_variable in line 27

I´m currently trying to build a website with oop. For a better view I´ve created a file called Article.class.php. In this file are all functions to get and process the data. Then I´ve the second file called _header where are all instances of the class php files to work with them individualy. My last file is the “my_articles.php” file where my table gets loaded with the data of the class file. When the code gets runned and I open up the website where the table has to be, it shows me the error: undefined variable: article_variable in line 27 and Fatal error: Uncaught Error: Call to a member function my_articles() on null.

Here is the Article.class.php file

public function my_articles(){
    include_once("my_articles.php");
    
    $sql = "SELECT * FROM items ORDER BY item_name DESC";
    $statement = $this->_database_intance->prepare($sql);
    $statement->execute();
    $users = array();

    
    while ($row = $statement->fetch(PDO::FETCH_ASSOC)){
        $users[] = $row;
       
    }
    return $users;

}

Here is the _header.php file (all instances)

#Database Connection:
include('classesDatabase.class.php');
$database_variable = new Database();
$database_instance = $database_variable->connection();


#Article class instance
include('classesArticle.class.php');
$article_variable = new Article($database_instance);
$article_instance = $article_variable->poll();

include('classesUsers.class.php');
$users_variable = new Users($database_instance);
$users_instance = $users_variable->poll_users();

and my last file (my_articles.php) where the data should print out:

<tbody>
    <?php
    include_once('shared_header.php');
    $users = $article_variable->my_articles();
    foreach ($users as $row){
        ?>
        <tr>
            <td><?php echo $row['item_name']; ?></td>
            <td><?php echo $row['amount']; ?></td>
            <td>
                <a href="C:xampphtdocsAufgabeArticlesarticle_details.php?id=<?php echo $row['item_name']; ?>"class="view_button">View</a>
                <a href="edit.php?id=<?php echo $row['item_name']; ?>"class="edit_button">Edit</a>
                <a onclick="return confirm('Are you sure you want to delete this record?');" href="Articlesdelete_article.php?id=<?php echo $row['item_name'];?>"class="delete_button">Delete</a>
            </td>
        </tr>
    
        <?php
    }
    
    ?>
</tbody>

How to print out individual field data on the page instead of the entire table contents

So I have this php code that gets results from a MySQL database and cache them using Memcached. I need help taking control of how I print the results on the page.

From the code below, i need help on how I can print something like this:

        echo "<br> id: ". $row["product_id"]
. " - Name: ". $row["product_name"]. " "  
. " - Price: ". $row["retail_price"] . "<br>";

This is the code I need to be modified :

<?php

header("Content-Type:application/json");

try {

    $db_name     = 'test_db';
    $db_user     = 'test_db_user';
    $db_password = 'EXAMPLE_PASSWORD';
    $db_host     = 'localhost';

    $memcache = new Memcache();
    $memcache->addServer("127.0.0.1", 11211);

    $sql = 'SELECT
            product_id,
            product_name,
            retail_price
            FROM products
           ';

    $key = md5($sql);

    $cached_data = $memcache->get($key);

    $response = [];

    if ($cached_data != null) {

        $response['Memcache Data'] = $cached_data;

    } else {

        $pdo = new PDO("mysql:host=" . $db_host  . ";dbname=" . $db_name, $db_user, $db_password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        $stmt = $pdo->prepare($sql);
        $stmt->execute();

        $products = [];

        while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
            $products[] = $row;
        }

        $memcache->set($key, $products, false, 5);

        $response['MySQL Data'] =  $products;

    }

    echo json_encode($response, JSON_PRETTY_PRINT) . "n";

} catch(PDOException $e) {
    $error = [];
    $error['message'] = $e->getMessage();
    echo json_encode($error, JSON_PRETTY_PRINT) . "n";
}

How to display custom taxonomies and their terms

I created Custom Post Types and taxonomies for them on the site. I need to list these taxonomies and their terms. How can i do this? For example, I created two , one for taxonomies, and the second for terms

function pediatric_create_post_type() {
  register_post_type( 'speakers', 
      array(
        'labels' => array(
        'name' => __( 'Speakers' ),
        'singular_name' => __( 'Speaker' ),
      ),
       'public' => true,
       'has_archive' => true,
       'supports' => array( 'thumbnail', 'title', 'editor' ),
      )
  );    
    
  register_taxonomy(
  'positions',
  'speakers',
      array(
      'label' => ( 'Positions' ),
      'hierarchical' => true,
      )
  );
    
  register_taxonomy(
  'countries',
  'speakers',
      array(
      'label' => ( 'Countries' ),
      'hierarchical' => true,
      )
  );
}
add_action( 'init', 'pediatric_create_post_type' );
<div class="speakers-filter">
  <ul class="speakers-tax">
    <li></li>
  </ul>
  <ul class="speakers-tax_terms">
    <li></li>
  </ul>
</div>

Is this good way to do Image Upload system logic?

I am working on web page where I want to use drag an drop image upload system with options for remove and sort images before upload.

I would like to ask you about your opinion.

I do not know if this system will have some troubles in future bcz all systems which I found have different logic, which was based on upload images immediately after drop to dropzone via PHP to server folder.

My system is based mainly on JS and images will be upload to folder AFTER whole form (other data about user as name, phone, etc) is filled in. Maybe it is normal way, but I did not find it yet.

I will be very thankful even if you help me find some other problems. Also I hope it can help someone who is building own system.

Here is my code:

JS:

/* DRAG AND DROP IMG UPLOAD */

// preventing page from redirecting
$("html").on("dragover", function(e) {
    e.preventDefault();
    e.stopPropagation();
});

$("html").on("drop", function(e) { e.preventDefault(); e.stopPropagation(); });

// Drag enter
$('.add-item__upload-area').on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
});

// Drag over
$('.add-item__upload-area').on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('.add-item__dropzone').css({border: '2px dashed #111'});
});

$('.add-item__upload-area').on('dragleave', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('.add-item__dropzone').css({border: '2px dashed #888'});

});

// Open file browser
$('.add-item__add-photo-btn').click(function() {
    $('#input-files').trigger('click'); // execute input type file after click on button
    event.preventDefault();
});

// create object to keep img files for modification
var data = {};


// Files added by drop to dropzone area
$('.add-item__upload-area').on('drop', function (e) {
    e.stopPropagation();
    e.preventDefault();

    var totalFiles = e.originalEvent.dataTransfer.files.length;

    // fill form by files from input
    for (var i = 0; i < totalFiles; i++) {

        var file = e.originalEvent.dataTransfer.files[i]; // Get list of the files dropped to area

        // fill object for file modifications by img files
        data['file_'+i] = file;

        // create temp url to img object for creating thumbnail and append img with temp src to thumbnail__wraper div
        $('.thumbnail__wrapper').append('<div class="thumbnail" id="file_'+ i +'"><img class="imageThumb" src="' + URL.createObjectURL(file) + '" title="' + file.name + '"/><br/><a class="remove">Zmazať</a></div>');

        $('.add-item__add-photo-btn-area').find('p').hide();
    }

});

// Files added by selecting in file browser
$('#input-files').on('change', function(){

    var totalFiles = $('#input-files')[0].files.length; // get number of uploaded files from input element

    // modify ordering of fields inside data object according to order from sortable ui
    for (var i = 0; i < totalFiles; i++) {
        // By appending [0] to the jQuery object will return the first DOM element. Get <input> element from object.
        var file = $('#input-files')[0].files[i]; // Get first file from list of files selected with the <input type="file">

        // fill object for file modifications by img files
        data['file_'+i] = file;

        // create temp url to img object for creating thumbnail and append img with temp src to thumbnail__wraper div
        $('.thumbnail__wrapper').append('<div class="thumbnail" id="file_'+ i +'"><img class="imageThumb" src="' + URL.createObjectURL(file) + '" title="' + file.name + '"/><br/><a class="remove">Zmazať</a></div>');

        $('.add-item__add-photo-btn-area').find('p').hide();
    }

    //console.log(data);
    //uploadData(formData); // send data via ajax to upload.php

});

// Remove field of data obj after click on remove button
$('.add-item__dropzone').on('click','.remove', function() {
    // remove choosen field
    delete data[$(this).parent().attr('id')];
    $(this).parent('.thumbnail').remove();
    //console.log($(this).parent().attr('id'));
    //console.log(data);
});

// Make images sortable
$('.thumbnail__wrapper').sortable({
    axis: 'x', // axis in which sort is possible
    update: function (event, ui) {
        // get all ids (item-1, ....) from li elements (setted as sortable) of list in form item[]=1&item[]=2

        var reorderList = $(this).sortable('serialize');

        //console.log(reorderList);
        // fill FormData object by files from data array after order change
        var formData = new FormData();
        var dataLength = Object.keys(data).length;

        //console.log(data);
        data = changeOrder(data, reorderList);
        //console.log(data);

    }
})

// Change order of files inside object data
function changeOrder(obj, order) {
    var newObject = {};
    // if the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.
    var matches = order.match(/=/g);
    var count = matches.length;
    // file[]=1&file[]=0&file[]=2 => ["file[]=1", "file[]=0", "file[]=2"]
    var arrayOfOrderValues = order.split('&');

    // console.log(arrayOfOrderValues);
    for (var i = 0; i < count; i++) {

        // get values in appropriate format ["file[]=1", "file[]=0", "file[]=2"] => file_1, file_0, file_2
        orderKey = 'file_' + arrayOfOrderValues[i].substring(arrayOfOrderValues[i].lastIndexOf("=") + 1);

        // console.log(orderKeyValue);
        // check if object contains key(property) as orderKeyValue and then do next step
        if(obj.hasOwnProperty(orderKey)) {
            // fill value of obj['file_1'] to newObject['file_0'] - ex. in first loop
            newObject['file_'+i] = obj[orderKey];
        }

    }
    return newObject;
}

// Sending AJAX request and upload file
function uploadData(formdata){

    $.ajax({
        url: '_inc/upload.php',
        type: 'post',
        data: formdata,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function(response){
            //addThumbnail(response); // if success - create thumbnail
        }
    })
}

$('.test').on('submit', function() {
    event.preventDefault();

    var formData = new FormData(); // Create form
    console.log(data);

    var count = Object.keys(data).length; // count fields of object

    for (var i = 0; i < count; i++) {
        formData.append('files[]', data['file_'+i]); // append data to form -> (key, value), file[0] first file from list of files !!! key must have [] for array
    }
    console.log(count);

    uploadData(formData); // send data via ajax to upload.php

})

PHP:

<?php

require($_SERVER['DOCUMENT_ROOT'] . '/bazar/_inc/DBController.php'); 
// inicialize object
$db_handler = new DBController();

// get total number of files in file list
$total_files = count($_FILES['files']['name']);
// array(5) { ["name"]=> array(2) { [0]=> string(23) "IMG_20190916_105311.jpg" [1]=> string(19) "20180525_115635.jpg" } ["type"]=> array(2) { [0]=> string(10) "image/jpeg" [1]=> string(10) "image/jpeg" } ["tmp_name"]=> array(2) { [0]=> string(28) "/home/gm016900/tmp/phpdU58AU" [1]=> string(28) "/home/gm016900/tmp/phpIqWoaQ" } ["error"]=> array(2) { [0]=> int(0) [1]=> int(0) } ["size"]=> array(2) { [0]=> int(306091) [1]=> int(2315700) } }

// Create array for jQuery information
$return_arr = array();

$images_names = array_filter($_FILES['files']['name']); // filter just values for $key = name
// -> array(2) { [0]=> string(23) "IMG_20190916_105311.jpg" [1]=> string(19) "20180525_115635.jpg" }
//var_dump($images_names);

/* BATCH FILE UPLOAD */

// if $_FILES contains image then do foreach
if ( !empty($images_names) ) {
    for($i = 0; $i < $total_files; $i++) {

        // Get reference to uploaded image
        $image_file = $_FILES["files"];

        // Get image name
        $image_name = $_FILES["files"]["name"][$i];

        // Get file size
        $image_size = $_FILES["files"]["size"][$i];


        /* BASIC CONTROL */

        // Exit if no file uploaded or image name contains unvalid characters /, \
        if ( ( !strpos($image_name, '/') || !strpos($image_name, '\') ) && isset($image_file) ) {
            // define variables if image in correct format is uploaded
            $errors = array();
            $maxsize = 10485760;
            $acceptable = array(
                'image/jpeg',
                'image/jpg',
                'image/gif',
                'image/png'
            );
        } else {
            die('No image uploaded.');
        }

        // Exit if image file is zero bytes or if image size is more then 10 MB
        if (getimagesize($image_file["tmp_name"][$i]) <= 0) {
            die('Uploaded file has no contents.');
        } elseif ($image_size >= $maxsize) {
            die('Image is too large. Image must be less than 10 megabytes.');
        }

        // Determine the type of an image int|false
        $image_type = exif_imagetype($image_file["tmp_name"][$i]);

        // Exit if is not a valid image file or image has not supported type
        if (!$image_type) {
            die('Uploaded file is not an image.');
        } elseif ( !in_array($image_file["type"][$i], $acceptable) ) {
            die('Image has not supported type JPG, PNG, GIF.');
        } else {
            $src = "default.png";
        }


        /* CREATE RANDOM IMAGE NAME INSTEDAOF $_FILES['files']['name'] */

        // Get file extension based on file type, to prepend a dot we pass true as the second parameter
        $image_extension = image_type_to_extension($image_type, true);

        // Create a unique image name
        $random_image_name = bin2hex(random_bytes(16)) . $image_extension;


        /* DEFINE LOCATION */

        // 1st create adress with new img random name
        $relative_location = "/bazar/assets/img/photos/".$random_image_name;

        $absolute_location = dirname(__DIR__, 2).$relative_location;

        //var_dump($image_file["tmp_name"][$i]);
        //var_dump($absolute_location);


        /* MOVE TEMP IMG TO PHOTOS FOLDER */

        // 2nd move img with tmp_name to new location under new random name added from 1st step
        if (move_uploaded_file($image_file["tmp_name"][$i], $absolute_location)) {

            $item_id = 1; 

            $src = $relative_location;

            $query = "INSERT INTO photos (item_id, file_name) VALUES (?, ?)";

            $inserted = $db_handler->runQuery( $query, 'is', array($item_id, $src) );
            
            var_dump($inserted);
            
            //$return_arr .= array("name" => $random_image_name,"size" => $image_size, "src"=> $src);
        }

    }
}

//echo json_encode($return_arr);


How to exclude/include specific database columns when eager-loading a nested model in Laravel 8?

To keep things simple, I’ll give an example in code to what I’m trying to Achieve.

Let’s assume that we have a model called User with the following code:

class User 
{
   public function posts()
    {
        return $this->hasOne(Post::class);
    }

}

And the Post model look something like this.

  class Post
    {
       public function comments()
        {
            return $this->hasMany(Comment::class);
        }
    
    }

And now what I want to be able to do is for example:

$user = Auth::user();
$comments = $user->post->comments; //here, I only want the "comment_id" and "comment_content" fields to be included, not all the Comment Model fields !

Archive page does not connect to Custom Post Type

I have a Custom Post Type with Speaker. I want to create an archive page where all speakers will be displayed. I have created an archive-speaker.php page template. In the admin panel, I created the Speakers Page page and specified the template – archive-speaker.php I connect the styles for each page separately. Right now is_post_type_archive( ‘speaker’ ) doesn’t work. It does not see the archive page. How can this be resolved?

// add styles
if (is_post_type_archive('speaker')) {
  wp_enqueue_style('speakers-styles', get_stylesheet_directory_uri().
    '/styles/speakers_style.css');
}

// Custom Post Type
 register_post_type( 'speaker', 
      array(
        'labels' => array(
        'name' => __( 'Speakers' ),
        'singular_name' => __( 'speaker' )
      ),
       'public' => true,
       'has_archive' => true,
       'rewrite' => array( 'slug' => 'speaker' ),
      )
  );

WAMP php version is not recognized – composer error

I run Laravel 9 on Windows 10.

Everything worked find until installed this package:
https://spatie.be/docs/laravel-livewire-wizard/v1/introduction

and now I get this error in the browser when trying to browse my site:
Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version “>= 8.1.0”. You are running 8.0.13. in C:wamp64wwwhighland9.localvendorcomposerplatform_check.php on line 24

After googling it I check all of these:

php version on Wamp shows 8.1.0

phpinfo() shows 8.1.0

localhost in the browser shows php version 8.1.0

Windows path points to: c:wamp64binphp8.1.0

cmd php -v shows: 8.1.0

In my composer.json file:

it was:

"require": {
        "php": "^8.0.2",

I changed it to:

"php":"^8.1.0"

and ran composer update

I tried removing the package like this:

composer remove vendor/spatie/laravel-livewire-wizard

It said there’s nothing to remove.

I renamed the folder to laravel-livewire-wizardDEL

I removed the line:

“spatie/laravel-livewire-wizard”: “^1.1”,

from composer.json and ran composer update

Nothing helps, still get this error.

Can someone please help?

Can’t understand how $data is used [closed]

That’s a php code in w3schools where they’re validating form data. Everything is good till I encounter this $data parameter passed to test_input function to represent the form data. I don’t understand how the parameter represents the whole form data with out anywhere where we are shown the $data variable== form data. I don’t see the logic there.