Override all child theme templates with a plugin

I need to override all of child theme templates woocommerce and parent templates in a plugin. Basically, I’m making couple of copies to my site that has some custom functionalities added via the child theme. So, in order to update all of the sites at once I want to use a plugin instead of a child theme. Because I assume it’s pretty difficult to make child theme do automatically updates. (maybe I’m wrong in this)

I’m using a parent theme that has different versions of woocommerce templates. For example, child-theme/woocommerce/cart/cart-v2.php is a cart template.

This is what I use to override woocommerce templates, but they override woocommerce plugin templates not parent theme templates.

add_filter( 'woocommerce_locate_template', 'woo_adon_plugin_template', 1, 3 );
   function woo_adon_plugin_template( $template, $template_name, $template_path ) {
     global $woocommerce;
     $_template = $template;
     if ( ! $template_path ) 
     $template_path = $woocommerce->template_url;
     
     $plugin_path  = RCW2P_PLUGIN_PATH  . '/templates/woocommerce/';
    
    
    if(file_exists( $plugin_path . $template_name ))
    $template = $plugin_path . $template_name;
    if( ! $template )
    $template = locate_template(
        array(
            $template_path . $template_name,
            $template_name
        )
    );
 
   if( ! $template && file_exists( $plugin_path . $template_name ) )
    $template = $plugin_path . $template_name;
 
   if ( ! $template )
    $template = $_template;
   return $template;
}

With this code I have to have this path for cart page plugin/templates/woocommerce/cart/cart.php
Also, this code doesn’t overrides templates files that are in woocommerce folder, such as taxonomy-product-cat.php

Any help is much appreciated.

How to Paginate Related Table From a Single Request in Laravel

I’m new to Laravel and PHP in general and was wondering how I could paginate the tweets data in my example below:

Route::get("/users/{user}", function (User $user) {
    return $user->only(
        "id",
        "name",
        "username",
        "avatar",
        "profile",
        "location",
        "link",
        "linkText",
        "created_at",
        "tweets"
    );
});

enter image description here

The tweets table is related to user so I could say $user->tweets()->paginate(10); but how can I return that along with my only() method? also, is there a way for me to return multiple stuffs and can still access them on my frontend?

I defined many to many relationship between two table and i successfully ran the migration and seeder… but it didn’t work

I want to create many to many relationships between user and schedule

This is my user model

<?php

namespace AppModels;

use AppModelsMajor;
use AppModelsScore;
use AppModelsSchedule;
use LaravelSanctumHasApiTokens;
use IlluminateNotificationsNotifiable;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentCastsAttribute;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    

    protected $guarded=['id'];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getRouteKeyName()
    {
        return 'name';
    }

    public function score(){
        return $this->hasMany(Score::class);
    }
    
    public function major(){
        return $this->hasOne(Major::class,'id','major_id');
    }

    public function schedule(){
        return $this->belongsToMany(Schedule::class,'schedule_user','user_id','schedule_id');
        // 'schedule_user','user_id','schedule_id'
    }

    protected function type(): Attribute
    {
        return new Attribute(
            get: fn ($value) =>  ["mahasiswa", "dosen","admin"][$value],
        );
    }
}

this is my schedule model

<?php

namespace AppModels;

use AppModelsUser;
use AppModelsCourse;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentFactoriesHasFactory;

class Schedule extends Model
{
    use HasFactory;
    protected $guarded=['id'];

    public function course(){
        return $this->belongsTo(Course::class);
    }
    public function user(){
        return $this->belongsToMany(User::class,'schedule_user','schedule_id','user_id');
    }
    
}

create_users_table

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            // $table->unsignedBigInteger('major_id');
            $table->foreignId('major_id')->constrained('majors');
            // $table->foreign('major_id')->references('id')->on('majors');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->default('password123');
            $table->bigInteger('nrp');
            $table->string('address');
            $table->integer('generation');
            $table->integer('type')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

create_schedules_table

<!-- create_schedules_table -->
<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateSchedulesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schedules', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->nullable();
            $table->foreignId('course_id')->constrained('courses')->nullable();
            $table->timestamps();
            $table->string('Hari');
            $table->string('Jam');
            

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('schedules');
    }
}

create_schecule_user_table.php

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateScheduleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schedule_user', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->foreignId('user_id')->constrained('users')->nullable();
            $table->foreignId('schedule_id')->constrained('schedules')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('schedule_user');
    }
}

here is my controller.. i try to show the user schedule where user’s id=1

<?php

namespace AppHttpControllers;

use AppModelsSchedule;
use AppModelsUser;
use IlluminateHttpRequest;

class ScheduleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        //
        $user=User::find(1);
        return view('schedule.index',[

            'title'=>'Jadwal Kuliah',
            'schedules'=>$user->schedule
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  AppModelsSchedule  $schedule
     * @return IlluminateHttpResponse
     */
    public function show(Schedule $schedule)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppModelsSchedule  $schedule
     * @return IlluminateHttpResponse
     */
    public function edit(Schedule $schedule)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppModelsSchedule  $schedule
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, Schedule $schedule)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  AppModelsSchedule  $schedule
     * @return IlluminateHttpResponse
     */
    public function destroy(Schedule $schedule)
    {
        //
    }
}

and here’s the schedule.index

@extends('dashboard.layouts.main')

@section('container')
<h3>schedule Kuliah {{auth()->user()->name}}</h3>
<table class="table align-items-center justify-content-center mb-0">
    <thead>
      <tr>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Mata Kuliah</th>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Hari</th>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Jam</th>
        <th></th>
      </tr>
    </thead>
    <tbody>

    @foreach ($schedules as $schedule)
      <tr>
        <td>
          <div class="d-flex px-2">
            <div class="my-auto">
              <h6 class="mb-0 text-sm">{{$schedule->course->nama_mata_kuliah}}</h6>
            </div>
          </div>
        </td>
        <td>
          <p class="text-sm font-weight-bold mb-0">{{ $jadwak->hari }}</p>
        </td>
        <td>
          <span class="text-xs font-weight-bold">{{ $schedule->jam }}</span>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>

@endsection

the view not displaying any user’s schedule. When i check in the terminal using php artisan tinker, the Schedule::first()->user returned: all:[]

Create or upgrade json object PHP array

Got this playlist json:

{
  "SyncInterval": 10000,
  "Tasks": [
    {
      "Stream": "LiveApp/playlist1",
      "Blocks": [
        {
          "Id": 201,
          "MaxIterations": 0,
          "Name": "Block-1",
          "Streams": [
            {
              "Type": "vod",
              "Source": "/samba/my/7v2qgkv.mp4"
            },
            {
              "Type": "vod",
              "Source": "/samba/my/7svzmsi.mp4"
            }
          ]
        }
      ]
    }
  ]
}

I want to create a new task with PHP array.
like this:

{
      "Stream": "LiveApp/playlist2",
      "Blocks": [
        {
          "Id": 905,
          "MaxIterations": 0,
          "Name": "Block-1",
          "Streams": [
            {
              "Type": "vod",
              "Source": "/samba/my2/7v2q2343232.mp4"
            }
          ]
        }
      ]
    }

So result will be:

{
  "SyncInterval": 10000,
  "Tasks": [
    {
      "Stream": "LiveApp/playlist1",
      "Blocks": [
        {
          "Id": 201,
          "MaxIterations": 0,
          "Name": "Block-1",
          "Streams": [
            {
              "Type": "vod",
              "Source": "/samba/my/7v2qgkv.mp4"
            },
            {
              "Type": "vod",
              "Source": "/samba/my/7svzmsi.mp4"
            }
          ]
        }
      ]
    },
    {
      "Stream": "LiveApp/playlist2",
      "Blocks": [
        {
          "Id": 905,
          "MaxIterations": 0,
          "Name": "Block-1",
          "Streams": [
            {
              "Type": "vod",
              "Source": "/samba/my2/7v2q2343232.mp4"
            }
          ]
        }
      ]
    }
  ]
}

Then, update the array with new “Sources” WHERE the “Stream”: “LiveApp/playlist1” or “Stream”: “LiveApp/playlist2”, as playlist1 and playlist2 where 2 different users.

changing text input value and files input value using ajax

I want to change the value of input-box and file-input-box using ajax.
But the problem is that i am unable to change the image input-box value using change value function in jquery ajax.

the code is like below

<body>
<div class="container">

                    <h3>player Registration</h3>
                    <form action="" method="post" class="form-control" 

enctype="multipart/form-data">
                       Player Name: <input type="text" name="playername" id="playername" class="form-control">
                       <br>
                       Select Team: <select name="teamname" id="teamname" class="form-control">
                           <?php foreach ($arr as $key=>$value):?>
                           <option value="<? echo $arr[$key]['team_id']; ?>"><? echo $arr[$key]['team_name']; ?></option>
                           <?php endforeach; ?>
                       </select>
                       <br>
                       Select Role: <select name="playerrole" id="playerrole" class="form-control">
                           <?php while($row = mysqli_fetch_array($result2)) 
                           echo "<option value='" . $row['role_id'] . "'>" . $row['role_name'] . "</option>";?>
                       </select>
                       <br>
                       player Photo: <input type="file" (change)="onFileChange($event)" name="playerphoto" id="playerphoto" class="form-control">
                       <br>
                       <input type="submit" value="Submit" class="btn btn-primary">
                       <input type="reset" value="Reset"  class="btn btn-warning">
                        </form>
    <table class="table table table-striped">
  <thead>
    <tr>
      <th scope="col">playerid</th>
      <th scope="col">player name</th>
      <th scope="col">player_team_id</th>
      <th scope="col">Player_role_id</th>
      <th scope="col">Player_photo</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
      <?php
      $sql2 = mysqli_query($conn,"select * from player_master");
      $arr3 = mysqli_fetch_all($sql2,MYSQLI_ASSOC);
      foreach ($arr3 as $key => $value): 
        echo '<tr>';
        echo'<td scope="row">' .$arr3 [$key]['player_id'].'</td>';
        echo'<td>' .$arr3 [$key]['player_name'].'</td>';
        echo'<td>' .$arr3 [$key]['player_team_id'].'</td>';
        echo'<td>' .$arr3 [$key]['player_role_id'].'</td>';
        // echo'<td><img style="width:100px;height:80px"src="playerphotos/' .$arr3 [$key]['player_photo'].'"></td>';
        echo'<td>' .$arr3 [$key]['player_photo'].'</td>';
        echo'<td><button class="pledit" value="'. $arr3 [$key]['player_id']. '" >edit</button></td>';
        echo'<td><button class="pldelete" value="'. $arr3 [$key]['player_id']. '" >delete</button</td>';
        echo'</tr>';
      endforeach;
      ?>

  </tbody>

</table>
                    
    </div>
 
</body>
<script src="../../../requirements/jquery.js"></script>
<script>
    $(document).ready(function()
       {
       $('.pledit').click(function(){
           alert('hyy');
        $.ajax({
                url:'edit.php',
                type: "POST",
                dataType: "JSON",
                data :{player_id:$(this).val()},
                success:function(res){
                  console.log(res);            
                  $('#playername').val(res.player_name); 
                  $('#teamname').val(res.player_team_id);
                  $('#playerrole').val(res.player_role_id);
                  $('#playerphoto').val(res.player_photo);               
                }
              })
       })
   });
</script>

so how can i change the $(‘#playerphoto’).val(res.player_photo);
except the file input everything else working fine..
please help.

check lenght strings when read file php

i´m trying to read a text file with telefone number inside this.

I need check if this phone number contains 9 or more digits or 16 digit or less.

my problem it´s that when i do this check, never entry in this condition and return error in my log… i´m edit code that it´s not mine and i don´t very well his logic.

i´m trying this:

case "fichero":

                        $log = "";

                        $fichero = $_FILES["lista_numeros"];

                        $fichero_valido = $this->validar_fichero();

 

                        if ($fichero_valido){

                            $lines = file($fichero["tmp_name"]);

                            $callers = array();

 

                            foreach ($lines as $line_num => $line){

                                $number = "";

                                $datos = $lines[$line_num];

                                if (strpos($datos,"rn") !== false && $line >= 9 && $datos <= 16){

                                    $number = substr($datos, 0, strpos($datos, "rn"));

                                }

                                else{

                                    $number = $datos;

                                }

 

                                // Se asigna el numero

                                if (is_numeric($number)){

                                    //array_push($callers, array("numero" => $number, "id_lista" => $id, "id_grupo"=> $lista->ID_GRUPO));

                                    array_push($callers, array("numero" => $number)); //, "id_lista" => $id, "id_grupo"=> $lista->ID_GRUPO));

                                }

                                else{

                                    $log .= "Línea " .$line_num. ": '" .$number. "' no es numéricorn";

                                }

                            }

 

                            // Fichero de error

                            if ($log != ""){

                                $this->load->helper("file");

                                if (write_file($this->config->item("path_logs"). "log_" .$id. ".txt", $log)){

                                    $msg_error_log = "Ha habido errores al insertar la lista de números [<a href='" .base_url(). "callers/log/" .$id. "'>Descargar log errores</a>]";

                                }

                                // else{

                                //  $msg_error_log = "No se ha podido crear el fichero de errores";

                                // }

                            }

                            else{

                                if (!empty($callers)){

                                    $lista = $this->Lista_model->obtener_lista($id);

                                    $num_aniadidos = $this->insertarListaTelefonosCallerID($callers, $id, $lista->ID_GRUPO);

                                    if ($num_aniadidos > 0){

                                        $msg_info2 = "Se han insertado correctamente a la lista " .$num_aniadidos ." números";

                                    }

                                    else{

                                        $msg_info2 = "No se encontraron teléfonos nuevos para añadir";

                                    }

                                }

                            }

                        }

                        break;

always entry in this block:

else{
    $log .= "Línea " .$line_num. ": '" .$number. "' no es numéricorn";
}

i don´t know that i´m doing wrong

laravel backpack list reoder button

It not reoder button delete

use BackpackCRUDappHttpControllersOperationsListOperation;
    use BackpackCRUDappHttpControllersOperationsShowOperation;
    use BackpackCRUDappHttpControllersOperationsCreateOperation { store as traitStore; }
    use BackpackCRUDappHttpControllersOperationsUpdateOperation { update as traitUpdate;  }
    use BackpackCRUDappHttpControllersOperationsFetchOperation;
    use BackpackCRUDappHttpControllersOperationsDeleteOperation;

It will reoder button delete

 **use BackpackCRUDappHttpControllersOperationsListOperation;
use BackpackCRUDappHttpControllersOperationsShowOperation;
use BackpackCRUDappHttpControllersOperationsCreateOperation { store as traitStore; }
use BackpackCRUDappHttpControllersOperationsUpdateOperation { update as traitUpdate;  }
use BackpackCRUDappHttpControllersOperationsFetchOperation;**
use BackpackCRUDappHttpControllersOperationsDeleteOperation;

Google Cloud Functions PHP 7.4 ignore HTTP requests body longer than around 16000 characters

this question could be a duplicate of this question

I use a HTTP POST request to send a JSON text to my Google Cloud Function running PHP. Here is the example of the codes:

<?php
use PsrHttpMessageServerRequestInterface;
use GoogleCloudFunctionsFunctionsFramework;
FunctionsFramework::http('insertbdd', 'insertbdd');

function insertbdd(ServerRequestInterface $request)
{
    $body = $request->getBody()->getContents();
    $size = (int) $_SERVER['CONTENT_LENGTH'];
    fwrite($log, "body : ".$body."n");
    fwrite($log, "size : ".$size."n");
    if (!empty($body)) {
        // save to database
    } else {
        die()
    }
}

When I try to pass a JSON file of which length is shorter than about 16000 characters, everything is fine, but if the size of the file surpass 16000 characters, I got nothing, the body is empty and the CONTENT_LENGTH is 0.

I am pretty sure the problem is on the receiver side, as I tried to send the JSON by PHP Curl, Postman and the test of Google Cloud Function.

In the other question Sandeep Vokkareni mentioned that the reason is the payload of PHP function being larger than 16kb. However I couldn’t find any information about this 16kb payload online. Any link please ?

Any help will be much appreciated. Thanks in advance

Trait “CviebrockEloquentSluggableSluggable” not found [closed]

Trait “CviebrockEloquentSluggableSluggable” not found
Laravel 9.14.1

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use CarbonCarbon;
use CviebrockEloquentSluggableSluggable;

class Quiz extends Model
{
    use HasFactory;
    use Sluggable;

    protected $fillable=['title','description','finished_at'];
    protected $dates = ['finished_at'];

    public function getFinishedAtAttribute($date){
        return $date ? Carbon::parse($date) : null;
    }

    public function questions(){
        return $this->hasMany('AppModelsQuestion');        
    }

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }
}

Error Message

Laravel Auth extend redirect if unauthorized

I’m authorizing my users using the Cognito Hosted UI from a custom guard. However the only way I can get the user redirected to the Hosted UI is by setting the headers myself, like so:

header("Location: https://{$this->domain}/login?scope=email+openid&$query");
exit;

However this is the wrong way to redirect within Laravel. If I attempt to use redirect()->away() then nothing happens, my protected page gets loaded regardless.

Here is my authenticate method, removed the rest of the code as it’s irrelevant:

// CognitoUserProvider.php

public function authenticate()
{
    redirect()->away("https://{$this->domain}/login?scope=email+openid&$query");
}
// AuthServiceProvider.php

public function boot()
{
    $this->registerPolicies();
    
    Auth::extend('cognito', static function () {
        return new CognitoUserProvider();
    });
}

Disabling load-styles.php file in WordPress

I want to override the WordPress admin style for forms in my plugin. I would like to exclude the load-styles.php forms file. I tried to deregister the file by wp_deregister_style(‘wp-admin’); but this doesn’t work.

I would really appreciate any help if you know how to deregister the file.

Thanks!

Symfony 5.4 EasyAdmin4 CSV Import & Filters

I have a question about the Admin Dashboard part. Is there any way to do a CSV Import button through either an extension without having to actually make a CSV Upload File FormType and so on?

Another question still related to the EasyAdmin 4 Bundle, is there any way to create a URL with some set-up filters? (e.g: status = $entity->getStatus() from another CRUDController)?

I tried generating the URL as it follows:

 $certificateEntriesUrl = $this->adminUrlGenerator
            ->setController(CertificateEntryCrudController::class)
            ->set('filters', [
                'certificate' => [
                    'value' => fn(Certificate $certificate) => $certificate->getReference(),
                    'comparison' => '='
                ]
            ])
            ->generateUrl();

Then I added the code like this:

    ->add(Crud::PAGE_DETAIL, Action::new(
        'CertificateEntries Display',
        'Voir toutes les attestations pour cette déclaration',
        'fa-solid fa-table-rows')
        ->linkToUrl($certificateEntriesUrl));

I found some similar posts about the 2nd question up there but it doesn’t work in Symfony 5.4, or I might have made some mistakes which I can’t see, I’m still a beginner in all this.

Laravel – Seeing Symfony Exception page instead of Spatie Ignition

In my composer file I have "spatie/laravel-ignition": "^1.2" however when an exception is thrown I am seeing the Symfony exception page rather than Ignition (shown below).

.env has the following:

APP_ENV="local"
APP_DEBUG="true"

Config files are published and contain default value.

Am I missing something really obvious to get this up and running?

enter image description here

The CSS is not working on Tables in my HTML File

I’m trying to built a website for my project where the CSS seems to be working for every content of the html file except the table
The Html:

 <table class='table-full'>
            <tr>
                <th>S.N</th>
                <th>Full Name</th>
                <th>Username</th>
                <th>Action</th>
            </tr>
            <tr>
                <td>1</td>
                <td>ABC</td>
                <td>abc</td>
                <td>
                    Update admin
                    Delete admin
                </td>
            </tr>
        </table>

The CSS:

}
.table-full{
    width: 100%;
}