Laravel Filament adding data to multiple tables

I need to add data to more than one table with belongsToMany in the project I developed with Laravel filament.

Example DB:

  • Category: id, name
  • Anime: id, name, description
  • AnimeCategory: id, category_id, anime_id

Code:

I am getting categoryId not found error in Anime Table.

Found in Anime Resource:

Select::make('categoryId')
    ->label('Kategori seçiniz')
    ->placeholder('Kategori Seçiniz')
    ->required()
    ->multiple()
    ->options(function () {
        return Category::all()->pluck('title', 'id');
    }),

How can I add selected multi-category id data to AnimeCategory table?

Why does this Code to store an Image in my database not work?

so I’m trying now for hours to store an Image in my Database, but I just don’t get it. Currently I’m trying to get the image via file upload from the user, then store in the database as a BLOB. So practically storing the binary data of the image in the database.

<form action="editor.php" class="createBlogForm" autocomplete="off">
                    <input type="text" name="title" placeholder="Title" class="title">
                
                <?php include 'editor.html'; ?>
            </div>
            <div id="catAndSave">
                <select name="categoriesOnCreate" class="categoriesOnCreate">
                    <option value="option1">Option 1</option>
                    <option value="option2" selected="selected">Anderes</option>
                </select>
                <div id="coverImageDiv">
                    <label for="inputTag">
                        Select Cover Photo <br/>
                        <i class="fa fa-2x fa-camera"></i>
                        <input id="inputTag" type="file" name="image"/>
                        <br/>
                        <span id="imageName"></span>
                    </label>
                </div>
                  <script>
                    let input = document.getElementById("inputTag");
                    let imageName = document.getElementById("imageName")
            
                    input.addEventListener("change", ()=>{
                        let inputImage = document.querySelector("input[type=file]").files[0];
            
                        imageName.innerText = inputImage.name;
                    })
                </script>
                <button type="submit" class="blogSave" onclick="save();">Save</button>
                </form>

So this is my form, I know very unstructured and things, but it doesn’t have to be.

When you click on the button this Code should be executed:

<script>
                function save(){
                    var xmlhttp = new XMLHttpRequest();
                    var content = document.getElementsByClassName('content')[0].innerHTML;
                    var title = document.getElementsByClassName('title')[0].value;
                    var category = document.getElementsByClassName('categoriesOnCreate')[0].value;
                    var data = new FormData();
                    data.append("content", content);
                    data.append("title", title);
                    data.append("category", category);
                    const queryString = window.location.search;
                    const urlParams = new URLSearchParams(queryString);
                    const id = urlParams.get('id');
                    xmlhttp.open("POST","editor.php?id=" + id ,true);
                    xmlhttp.send(data);
                    window.location = "http://192.168.56.104/sodablog/editor.php";
                };
            </script>

Doesn’t quite work tho, because it never executes this, because i wrote in my form: action=”editor.php”. But that’s not the point and doesn’t matter, cause that’s not the problem.

The problem is that PHP doesn’t get my file to upload it. Here:

<?php
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    session_start();
    include 'dbconnect.php';

    $content = $_POST['content'];
    $title = $_POST['title'];
    $category = $_POST['category'];

    date_default_timezone_set('Europe/Rome');
    $date = date("YmdHis"); 

  
    $status = 'error'; 
    if(!empty($_FILES["image"]["name"])) { 
        // Get file info 
        $fileName = basename($_FILES["image"]["name"]); 
        $fileType = pathinfo($fileName, PATHINFO_EXTENSION); 
         
        // Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            $image = $_FILES['image']['tmp_name']; 
            $imgContent = addslashes(file_get_contents($image));
         
            // Insert image content into database 
            $insert = $db->query("INSERT INTO `blog_posts`(`coverImage`) VALUES ('$imgContent');");
             
            if($insert){ 
                $status = 'success'; 
                $statusMsg = "File uploaded successfully."; 
            }else{ 
                $statusMsg = "File upload failed, please try again."; 
            }  
        }else{ 
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        } 
    }else{ 
        $statusMsg = 'Please select an image file to upload.'; 
    } 

 
// Display status message 
echo $statusMsg;

    $sql = "INSERT INTO `blog_posts`(`created_at`, `last_updated_at`, `content`, `title`, `category`) 
    VALUES('$date', '$date', '$content', '$title', '$category');";
    $execution = mysqli_query($conn, $sql) or die("Fehler");
?>

For testing you could just here give these lines:

$content = $_POST['content'];
    $title = $_POST['title'];
    $category = $_POST['category'];

a value so no error appears because of these.

But I still get the error: Please select an image file to upload.

I’m new to PHP and JavaScript and Web-development in general, so sorry for the chaotic code.

PHP problems with linking HTML. Doesn’t redirect

Basically my shirt e-commerce website won’t redirect to my html website. Whenever I try to click on the virtual try on button next to the shirt, it doesn’t redirect me to the page instead it just loads and refreshes the current page. Any tips?
Here is my code:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="get">
    <input type="hidden" name="product_id" value="124">
    <input type="submit" value="Virtual Try ON" name="form_virtual_try_on">
</form>

<?php
$product_id = $_GET['product_id'] ?? '';

switch ($product_id) {
  case '124':
    $text = 'Virtual Try On';
    $link = 'vton_ls.html';
    break;
  default:
    $text = '';
    $link = '';
    break;
}

if (isset($_GET['form_virtual_try_on'])) {
  $product_id = $_GET['product_id'];
  if ($product_id == '124') {
    header('Location: vton_ls.html');
    exit;
  } else {
    echo "Invalid product ID";
  }
}
?>

<div class="share">
    <?php echo LANG_VALUE_58; ?> <br>
    <div class="sharethis-inline-share-buttons"></div>
</div>

I tried GET, switch case, and redoing all my codes from scratch but it doesn’t seem to work.

JS onchange event interaction (populate PHP form field) [duplicate]

I would like help to implement an onchange event in a select field of the form where, when changing that field, the new value of the option interacts with PHP/Mysql to change the value of another input field in the form.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <label for="teams">Select your team:</label>
    <select id="team" onchange="selectTeam()">
        <option value="sampa">São Paulo</option>
        <option value="rio">Rio de Janeiro</option>
        <option value="curitiba">Curitiba</option>
        <option value="salvador" selected>Salvador</option>
        <option value="floripa">Florianópolis</option>
    </select>
    <div id="info">

    </div>
</body>
<script>
selectTeam()
function selectTeam(){
    let team = document.getElementById('team').value
    document.getElementById('info').innerHTML = `You have selected ${team} team`
}
</script>
</html>

This code performs the necessary interaction without using a DB query.

I only got local interaction in JS but it would really need interaction with the database.

Thank you very much.

Disable Add To Cart on Variation Change Using contains() function in jQuery

I need to Blur ( remove functionality ) of the Add to Cart button globally for product variations which are Out of stock so assume the jQuery contains() function is the best bet but can’t get this code to work.

I’ve tried checking using the outOfStock but can’t get it to work.

If the product contains the text Out of stock when the variation option is toggled, i need to prevent the add to cart button from working.

add_action('wp_footer', 'outofstock_product_variation_js');
function outofstock_product_variation_js() {
    ?>
    <script type="text/javascript">
    jQuery(function($) {
    
        var addToCartButtonObj = $('.add-to-cart-button');
        var outOfStock         = $("p.stock.in-stock:contains('Out of stock')");

        $('form.variations_form').on('show_variation', function(event, data) { 
        
        if ( ! data.is_in_stock  ) {
            
                addToCartButtonObj.hide();
                
            } else if ( data.is_in_stock  ) {
            
                addToCartButtonObj.show();
            
            }
            
        })
      
    });
    </script>
    <?php
}

Why does my database not want to update data even though it says that it’s connected

I’m new to php and have a school project where I need to make a form and database that will put out the data from said form. Right now my problem is that I can’t update the data inside even though it says that it’s connected to the data base

This is the php file that I’m using to edit the form I’m using

`<?php
include 'koneksi12A3_19.php';
        if (isset($_POST['EDIT'])){
$ID = $_GET['ID'];
$hasilsql = "select * from tableedit_12a3_19 WHERE ID=$ID";
$tampil = mysqli_query($koneksi, "select * from tableedit_12a3_19 where ID='$ID'");
$hasil = mysqli_fetch_array($tampil);}{
?>

<html>
<head>
    <title>Form Pengisian Data</title>
</head>
<body>
    <div class="grid">
        <div class="title">
        </div>
        <div class="header">
            <h2><b>Form Edit Data</b></h2>
        </div>
        <div align=left class="content">
            <form method="POST"action="update12A3_19.php">
                <table border=0>
            <tr>
                <td>nama</td>
                <td><input type="hidden" name="ID">
                
                <input type="text" name="nama"></td>
            </tr>
            <tr>
                <td>nomor</td>
                <td>
                <input type="text" name="nomor"></td>
            </tr>
            <tr>
                <td>alamat</td>
                <td><input type="textarea" name="alamat"></td>
            </tr>
            <tr>
                <td>kota</td>
                <td>
                    <input list="kota" name="kota" placeholder="Input kota" /></label>
                <datalist id="kota">
                <option value="Jakarta Barat">
                <option value="Jakarta Timur">
                <option value="Jakarta Utara">
                <option value="Jakarta Selatan">
                <option value="Jakarta Pusat">
                <option value="Bekasi">
                </datalist></td>
            </tr>
            <tr>
                <td class="form-hobby">Hobby
                </td>
                <td>
                <input type="radio" id="hobby" name="hobby" value="bulutangkis">
                <label for="html">bulutangkis</label><br>
                <input type="radio" id="hobby" name="hobby" value="basket">
                <label for="css">basket</label><br>
                <input type="radio" id="hobby" name="hobby" value="catur">
                <label for="javascript">catur</label><br>
                <input type="radio" id="hobby" name="hobby" value="sepak bola">
                <label for="html">sepak bola</label><br>
                <input type="radio" id="hobby" name="hobby" value="baca buku">
                <label for="css">baca buku</label><br>
            </td>
            </tr>
            <tr>
                <td><input type="submit" value="EDIT"></td>
                <td><input type="reset" value="CANCEL"></td>
            </tr>
                </table>
            </form>
        </div>
</body>
</html>

<?php
}
?>`

and this is the update file that connects the file above with the database

`<?php
include_once("koneksi12A3_19.php");
if(isset($_POST["EDIT"]))
{
$ID = $_POST['ID'];
$nama = $_POST['nama'];
$nomor = $_POST['nomor'];
$alamat = $_POST['alamat'];
$kota = $_POST['kota'];
$hobby = $_POST['hobby'];

$query = "UPDATE tableedit_12a3_19 nama='$nama', nomor='$nomor', alamat='$alamat', kota='$kota', hobby='$hobby', 
WHERE ID='$ID'";
mysqli_query($koneksi, $query);
header('location: tampilanedit12A3_19.php');
}
?>`

I tried putting isset into both the edit and update file because ID couldn’t be identified but now it won’t update the file

enter image description here I want to change the data inside a row like this

Is using PHP magic function __call() a good style? [closed]

I recently came across the use of the PHP magic function and found it quite handy. But after thinking about it for a while, I wonder if using the function is good. I just noticed that debugging is made much more difficult. Also, autocompletion by the IDE is not given.

Questions

  1. Good style
  2. Is there a way around the two disadvantages mentioned above?

The date returned with strtotime with a different time from the database

I’m trying to get the publication date and update date from the database and what appears to me is a correct date but the hour and minutes are incorrect.

my code:

<?php if (mysqli_num_rows($articles) > 0):?>
<table class="comparison_table_admin">
<tr><th>מזהה</th><th class="without_filtering_admin">תמונה ממוזערת</th><th>כותרת</th><th>קטגוריה</th><th>צפיות</th><th>תאריך העלאה</th><th>עדכון אחרון</th>
<?php if(isset($_SESSION['user_is_admin'])):?><th>משתמש</th><?php endif ?>
<th>מצב</th><th class="without_filtering_admin">פתיחה</th><th class="without_filtering_admin">עריכה</th><th class="without_filtering_admin">מחיקה</th></tr>
<tbody class="tbody_in_table_admin" id="search_table">
<?php while($post = mysqli_fetch_assoc($articles)):?>
<?php
$tag_id = $post['tag_id'];
$category_query = "SELECT title FROM categories WHERE id=$tag_id";
$category_result = mysqli_query($connect_db, $category_query);
$category = mysqli_fetch_assoc($category_result);
?>
<tr>
<td><?= $post['id'] ?></td>
<td><img src="/images/<?= $post['thumbnail']?>" alt="<?= $post['title'] ?>"></td>
<td><?= $post['title'] ?></td>
<td><?= $category['title'] ?></td>
<td><?= $post['total_views'] ?></td>
<td data-sort="<?= $post['date_time'] ?>"><?= date("d/m/Y h:m:s",strtotime($post['date_time'])); ?></td>
<td data-sort="<?= $post['update_date_time'] ?>"><?= date("d/m/Y h:m:s",strtotime($post['update_date_time'])); ?></td>
<?php if(isset($_SESSION['user_is_admin'])):?>
<?php $author_id=$post['author_id'];$author_query="SELECT * FROM authors WHERE id=$author_id";$author_result=mysqli_query($connect_db,$author_query);$author=mysqli_fetch_assoc($author_result); ?>
<td><?php echo $author['full_name']?></td>
<?php endif ?>
<td>
<?php if($post['activated']==0){echo'<span class="public_situation_admin" title="המאמר ממתין לאישור המנהל">⏳</span>';}elseif($post['activated']==1){echo'<span class="public_situation_admin" title="המאמר אושר ופורסם">&#128226;</span>';}?>
</td>
<td><a class="new_window_admin" href="/page/<?= $post['id'] ?>/" title="פתיחה בחלון חדש" target="_blank">&#8689;</a></td>
<td><a class="edit_button_admin" href="/admin/edit-post.php?id=<?= $post['id'] ?>">&#9998;</a></td>
<td>
<form action="/admin/delete-post.php?id=<?= $post['id'] ?>" method="post">
<input type="hidden" name="delete_articles" id="delete_articles" value="<?= $post['id'] ?>">
<button class="delete_button_admin" type="submit" onclick="archiveFunction()">&#128465;</button>
</form>
</td>
</tr>
<?php endwhile ?>
</tbody>
</table>
<?php else:?><h2 class="system_notice_h2_admin"><?= "לא פרסמת שום מאמר."?></h2><?php endif?>

This is the code snippet that displays the dates:

<td data-sort="<?= $post['date_time'] ?>"><?= date("d/m/Y h:m:s",strtotime($post['date_time'])) ; ?></td>
<td data-sort="<?= $post['update_date_time'] ?>"><?= date("d/m/Y h:m:s",strtotime($post['update_date_time'])) ; ?></td>

And a picture of my database:
enter image description here

And a picture of my website:
enter image description here

migration to populate existing fields yii2

I have a model and ready-made data in a table. In this model, I added a new field and made a connection with another table.

And in order not to manually fill in these fields for each record, I want to create a migration that will automatically fill in this field for all records.

Relationship table has two fields: post_id and author_id

I’m creating a migration where I get all existing post_id and try to add value to author_id:

public function safeUp()
    {
        /**
         * @var Posts[] $posts
         */
        $posts = Posts::find()->all();
        foreach ($posts as $post) {
            $item = new PostAuthor();
            $item->setAttribute('post_id', $post->id);
            $item->setAttribute('author_id', 2);
            $item->save();
        }
    }

Now everything is working, and all existing posts are given an author_id with a value of 2.

But I would like to refine it a little, author_id can have a value from 1 to 4, and I want different values ​​​​to be added to each post in the migration.

Let’s say the first post gets author_id: 1
The second post will get author_id: 1, author_id: 2
Third post author_id: 1, author_id: 2, author_id: 3
And the fourth post respectively author_id: 1, author_id: 2, author_id: 3, author_id: 4

But how can I do this, because now all my posts will receive the same values

Docker – unable to run supervisor

I try to install supervisor on my local docker container where I run php8.1 and laravel 9.
But I have following error:

'PermissionError: [Errno 13] Permission denied: '/var/log/supervisor/supervisord.log'

This is my config:
supervisor.conf

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/artisan queue:work
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
numprocs=1
redirect_stderr=true
stdout_logfile=/var/www/html/storage/logs/worker.log
stopwaitsecs=3600
stdout_logfile_maxbytes=5MB

php dockerfile:

FROM php:8.1.13-fpm

RUN apt-get update && apt-get install -y 
        libfreetype6-dev 
        libjpeg62-turbo-dev 
        libpng-dev 
        nano 
        libxslt1.1 
        libxslt1-dev 
        unzip 
        git 
        gnupg 
        libpq-dev 
        libzip-dev 
        iputils-ping 
        supervisor 
    && docker-php-ext-install zip 
    gd 
    mysqli pdo pdo_mysql  
    && docker-php-ext-enable pdo_mysql 
    && docker-php-ext-configure gd --with-freetype --with-jpeg 
    && docker-php-ext-configure intl 
    
RUN echo "memory_limit='512M'" >> /usr/local/etc/php/conf.d/php-extra.ini;

ENV PHP_IDE_CONFIG "serverName=new_app"

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin --filename=composer --version=2.3.8 && chmod +x /usr/bin/composer

# Set timezone
RUN rm /etc/localtime 
    && ln -s /usr/share/zoneinfo/Europe/Warsaw /etc/localtime 
    && "date" 
    && printf '[PHP]ndate.timezone = "Europe/Warsaw"n' > /usr/local/etc/php/conf.d/tzone.ini 

RUN usermod -aG docker $USER
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]

WORKDIR /var/www/html

How can I fix it?

Regards.

WordPress post offset is affecting admin area

I’m trying to get a post offset to work on category and tag archives with a couple of category exclusions.

I have 3 functions. The first creats a custom loop which is inserted via shortcode and contains 3 posts, and the other two functions offset the main query by 3 and fix the pagination as per this codex article

It seems to work where it should, except it’s also offsetting posts in the backend admin area for all post types and I can’t work out how to stop that happening.

For clarity, posts should be offset by 3 on category and tag archives only, excluding the categories added to the array.

function archive_loop_shortcode() {
$current_archive = get_queried_object();

$args = array(
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => 3,
    'tax_query'      => array(
        array(
            'taxonomy' => $current_archive->taxonomy,
            'field'    => 'term_id',
            'terms'    => $current_archive->term_id,
        ),
    ),
);

$archive_query = null;
$archive_query = new WP_query($args);
echo '<div class="kb-custom-archive-loop"><div class="kb-custom-archive-loop-inner">';
if($archive_query->have_posts()):
    while($archive_query->have_posts()) : $archive_query->the_post();
        $custom = get_post_custom( get_the_ID() );
    echo '<article>';
    echo '<figure><a href="' . get_permalink() . '"><div>' . get_the_post_thumbnail() . '</div></a></figure>';
          echo '<a href="' . get_permalink() . '"><h2>' . get_the_title() . '</h2></a>';
    echo '</article>';
    endwhile;
    wp_reset_postdata();
else :
_e( 'Sorry, no posts matched your criteria.' );
endif;
echo "</div></div>";
}

add_shortcode( 'archive_loop', 'archive_loop_shortcode' );

add_action('pre_get_posts', 'myprefix_query_offset', 1 );
function myprefix_query_offset(&$query) {
    if ( ! is_admin() && ! is_home() && ! is_search() && ! is_author() && ! $query->is_main_query() ) {
    if ( ! is_category(array('28770','28688')) || is_tag() ) {
    return;
    }
}

$offset = 3;
$ppp = get_option('posts_per_page');

if ( $query->is_paged ) {

    $page_offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );

    $query->set('offset', $page_offset );

}
else {

    $query->set('offset',$offset);

    }
}


add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
function myprefix_adjust_offset_pagination($found_posts, $query) {

$offset = 3;

if ( ! is_admin() && ! is_home() && ! is_search() && ! is_author() && ! $query->is_main_query() ) {
    if ( ! is_category(array('28770','28688')) || is_tag() ) {
    return $found_posts - $offset;
    }
  }
return $found_posts;
}