Error in laravel component ; Undefined variable $acceptIcon

I use Laravel 11 and my component work perfectly in local, but I have error in production

component class:

<?php

namespace AppViewComponentsdashboardcafe;

use Closure;
use IlluminateContractsViewView;
use IlluminateViewComponent;

class VerifyButtons extends Component
{
    public string $acceptIcon;
    public string $rejectIcon;

    public function __construct(public $status, public string $propertyName)
    {
        $this->acceptIcon = asset('assets/images/default-accept.svg');
        $this->rejectIcon = asset('assets/images/default-reject.svg');
        if ($this->status)
            $this->acceptIcon = asset('assets/images/accept.svg');

        if ($this->status === 0)
            $this->rejectIcon = asset('assets/images/reject.svg');
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.dashboard.cafe.verify-buttons');
    }
}

and in blade:

<div class="flex gap-3">
    <img class="w-[28px] cursor-pointer" wire:click="$set('{{$propertyName}}',1)"
         src="{{$acceptIcon}}"/>
    <img class="w-[28px] cursor-pointer" wire:click="$set('{{$propertyName}}',0)"
         src="{{$rejectIcon}}"/>
</div>

Php verison in local and production is 8.3.14

error:

Undefined variable $acceptIcon

Anonymous function in array causes fatal error [duplicate]

I have the following class

<?php

namespace Core;

class Router
{
  public $routes = [
    [
      'url' => '/register',
      'controller' => BASE_PATH . 'controllers/registration/register.get.php',
      'method' => 'GET',
      'middleware' => fn() => true,
    ]
  ];

  public function route()
  {
   //...
  }
}

When I add that middleware key that points to a function, I get the Fatal error: Constant expression contains invalid operations. What I am trying to do is simply create the router, call its route method, and then depending on the current route call the middleware function. What is the right syntax for this sort of thing in PHP?

How can I enable the coupon input box on the customer order pay page?

When a customer clicks on the link to go to their payment page, the ‘Have a Coupon?’ input box does not appear. I haven’t made any adjustments to the templates.

Do you have any ideas on how I can make the coupon input box visible on the customer payment page?

The location I am referring to is:

/checkout/order-pay/<order_id>/?pay_for_order=true&key=<order_key>
Screenshot : https://prnt.sc/-T4dnbDTuPTW

How to determine whether to use query parameters or body in GET requests when integrating with different APIs?

I am working with two different APIs, both using GET requests but handling request data differently:

  1. API 1 requires the data to be sent in the request body, even though the HTTP method is GET.
    Example:

    $config = [
        'method' => 'GET',
        'url' => 'http://example.com/api/endpoint',
        'headers' => [
            'Content-Type' => 'application/json',
        ],
        'body' => [
            'key1' => 'value1',
            'key2' => 'value2',
        ],
    ];
    
  2. API 2 requires the data to be sent as query parameters in the URL.
    Example:

    $config = [
        'method' => 'GET',
        'url' => 'http://example.com/api/endpoint',
        'headers' => [
            'Content-Type' => 'application/json',
        ],
        'query' => [
            'key1' => 'value1',
            'key2' => 'value2',
        ],
    ];
    

Both APIs work with the GET method, but their requirements for passing data are different. This makes it challenging to decide when to use query parameters and when to use the request body for a GET request.

Questions:

  1. How can I determine whether to use query parameters (query) or the request body (body) for a GET request?
  2. Is it common or correct for a GET request to accept data in the body, even though the HTTP specification discourages it?
  3. How can I design a generic HTTP client (e.g., using Guzzle) to handle these differences dynamically based on the API’s requirements?

Any guidance, best practices, or examples would be appreciated!

 $options = ['headers' => $request['headers']];

        if ($request['method'] === 'GET') {
            if ($request['isRequestRawBody']) {
                $options['body'] = json_encode($request['body']);
            } else {
                $options['query'] = $request['body'];
            }
        } else {
            $contentType = $request['headers']['Content-Type'] ?? '';

            switch ($contentType) {
                case 'application/x-www-form-urlencoded':
                    $options['form_params'] = $request['body'];
                    break;
                case 'application/json':
                    $options['json'] = $request['body'];
                    break;
                case 'multipart/form-data':
                    $options['multipart'] = array_map(function ($key, $value) {
                        return ['name' => $key, 'contents' => $value];
                    }, array_keys($request['body']), $request['body']);
                    break;
                default:
                    $options['body'] = $request['body'];
            }
        }

        return $options;

Black Screen Modal Appears in Table Actions on Laravel Filament v3 Resource

I am using Laravel Filament v3 and encountered an issue when generating a resource. I generated the resource using the following command:
php artisan make:filament-resource Anggota --generate

The resource generation completed successfully, but I am experiencing strange behavior in the table view of the generated resource. Specifically:

  • When I perform a search, apply a filter, change the number of items displayed, or navigate to another page in the table, a black screen modal immediately appears.
  • To view the updated data (e.g., navigating to page 2), I have to manually reload the page. After reloading, the table correctly shows the intended data (e.g., page 2).

I didn’t modify anything from the default generated resource
Environment Details:

Here is what I have tried so far:

  • Ensuring that JavaScript and CSS assets are up to date.
  • Clearing cache using php artisan cache:clear and php artisan view:clear.
  • Rechecking the generated code, but I didn’t modify anything from the default generated resource.

Target class [admin] does not exist Problem in Laravel Version 11.36.1 and php version 6.2.12

I am trying to create a login system where both admin and users can log in using the same form. The problem is when I log in with admin credentials, the URL redirects correctly to admin/dashboard, but I see the error:

Target class [admin] does not exist

Here is the relevant code:

Admin Controller

<?php
// appHttpControllersAdminAdminController.php

namespace AppHttpControllersAdmin;

use AppHttpControllersController;
use IlluminateHttpRequest;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware('admin');
    }

    public function dashboard()
    {
        return view('admin.dashboard');
    }
}

User Dashboard Controller

<?php
// appHttpControllersDashboardController.php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $user = auth()->user();
        $recentOrders = $user->cartItems()
            ->with('product')
            ->latest()
            ->take(5)
            ->get();

        return view('dashboard', compact('recentOrders'));
    }
}

Authenticated Session Controller

<?php
// appHttpControllersAuthAuthenticatedSessionController.php

namespace AppHttpControllersAuth;

use AppHttpControllersController;
use AppHttpRequestsAuthLoginRequest;
use IlluminateHttpRedirectResponse;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateViewView;

class AuthenticatedSessionController extends Controller
{
    public function create(): View
    {
        return view('auth.login');
    }

    public function store(LoginRequest $request)
    {
        $request->authenticate();
        $request->session()->regenerate();

        if (Auth::user()->isAdmin()) {
            return redirect()->intended(route('admin.dashboard'));
        }

        return redirect()->intended(route('dashboard'));
    }

    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}

User Model

<?php
// appModelsUser.php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'is_admin',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'is_admin' => 'boolean',
    ];

    public function cartItems()
    {
        return $this->hasMany(CartItem::class);
    }

    public function isAdmin()
    {
        return $this->is_admin;
    }
}

Kernel Middleware

<?php
// appHttpKernel.php

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        IlluminateHttpMiddlewareTrustProxies::class,
        IlluminateHttpMiddlewareHandleCors::class,
        IlluminateFoundationHttpMiddlewarePreventRequestsDuringMaintenance::class,
        IlluminateHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            IlluminateRoutingMiddlewareThrottleRequests::class . ':api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
    ];

    protected $middlewareAliases = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
        'admin' => AppHttpMiddlewareAdminMiddleware::class,
    ];
}

Routes

<?php
// routes/web.php

use AppHttpControllersAdminAdminController;
use AppHttpControllersDashboardController;
use IlluminateSupportFacadesRoute;

Route::get('/', [HomeController::class, 'index'])->name('home');

require __DIR__.'/auth.php';

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
});

Route::middleware(['auth', 'admin'])->group(function () {
    Route::get('/admin/dashboard', [AdminController::class, 'dashboard'])->name('admin.dashboard');
});

I’ve confirmed that the middleware and route definitions seem fine. What am I missing here? How can I fix the Target class [admin] does not exist error?

Any help or guidance would be greatly appreciated!

I am tired to find out where the problem is occur.

laravel 11_ Backback

I have an issue where I uploaded my Laravel 11 project to InfinityFree hosting and used Backpack to create a dashboard for managing my website. However, when I navigate to the admin panel link, and after successfully logging in, I try to view the data stored in the database, but I encounter a 419 Page Expired error.

I have tried many solutions without success. Can anyone help me resolve this issue?

Note: I also tried disabling CSRF verification, but that did not work either.

disabling CSRF verification.
I tried searching for solutions online and implementing suggestions.
I have checked Laravel’s and Backpack’s configurations, session settings, or routes.
I expected the 419 error to stop appearing.

Hide a from non-members

I’m writing a PHP script which allows my users to create their own pages and get a URL hosted on my hosting service. After the user creates their page, they get a link to a page which includes a navbar (containing Navbar) and the page itself. Now, they can share this page anywhere they want by copying the link my script gave them.

The problem is, everyone else also sees the navbar which is intended only for the creator of that page (such as edit page, etc.).

Here is how my script checks if the user is logged in (I can’t change this)

if (!isset($_SESSION['userid']) || empty($_SESSION['userid'])) {
// If not logged in, redirect to the login page
header("Location: login.php");
exit();
}

Here is how the script gets the User ID:

$userid = $_SESSION["userid"];
$getuserdata = mysql_query("Select email, mtype, joindate from ".$prefix."members where Id=$userid");
$useremail = mysql_result($getuserdata, 0, "email");
$mtype = mysql_result($getuserdata, 0, "mtype");

and this is the code I am using show the only if $mtype is 0:

// Determine if the current user is the creator of the page
$isCreator = ($userid == $page['user_id']);

// Add the header only if the current user is the creator
if ($isCreator) {
$pageContent .= "
<header class='bg-light p-3 " . ($mtype == 0 ? "hidden-header" : "") . "'>
<div class='container'>
<a href='/members.php' class='btn btn-primary'>Dashboard</a>
<a href='/instagram_embed_start.php' class='btn btn-secondary'>Edit Page</a>
<a href='/signup.php?rid=<?php echo $userid; ?>' class='btn btn-success'>Create Yours</a>
</div>
</header>";
}

// Add CSS to hide the header if the user is not a member
$pageContent .= "
<style>
.hidden-header {
display: none !important;
}
</style>";

In reality, I want all users except for the creator of the page to NOT see this part. Obviously, this is because they won’t have the ability to edit the page in the first place. Any insights will be highly appreciated.

Laravel validate index array of object

Is there anyway to validate the index array of objects in laravel with the validator?
Here is my post data:

[
    {
        "order_id": 601696,
        "is_delay": 0,
        "ship_date": null,
        "times": 1,
        "warehouse_id": 237,
        "ship_type": 1,
        "package": [
            {
                "sku": "JD-XL102",
                "order_item_id": 772447,
                "qty": 2
            }
        ]
    },
    {
        "order_id": 601696,
        "is_delay": 0,
        "ship_date": null,
        "times": 1,
        "warehouse_id": 251,
        "ship_type": 1,
        "package": [
            {
                "sku": "JD-D16",
                "order_item_id": 772447,
                "qty": 1
            },
            {
                "sku": "JD-D16-GC",
                "order_item_id": 772448,
                "qty": 1
            }
        ]
    }
]

Then i want to validate it like this :

public function rules()
{
    return [
        '*.*.order_id'      => 'required|integer',
        '*.*.is_delay'      => 'required|boolean',
        '*.*.ship_date'     => 'nullable|datetime',
        '*.*.times'         => 'required|integer|min:1',
        '*.*.warehouse_id'  => 'required|integer',
        '*.*.ship_type'     => 'required|integer',
        '*.*.package'       => 'required|array',
        '*.*.package.*.sku' => 'required|string',
        '*.*.package.*.qty' => 'required|integer|min:1',
    ];
}

Howevere it not works.
I know i can add a prefix field to fix it, but i just want to know if laravel support the index array to validate without the prefix key?

{
    "rows": [
        {...}
    ]
}
public function rules()
{
    return [
        'row'                 => 'required|array',
        'row.*.order_id'      => 'required|integer',
        'row.*.is_delay'      => 'required|boolean',
        'row.*.ship_date'     => 'nullable|datetime',
        'row.*.times'         => 'required|integer|min:1',
        'row.*.warehouse_id'  => 'required|integer',
        'row.*.ship_type'     => 'required|integer',
        'row.*.package'       => 'required|array',
        'row.*.package.*.sku' => 'required|string',
        'row.*.package.*.qty' => 'required|integer|min:1',
    ];
}

PHP version: v7.4.33

Laravel version: v6.20.44

Is it possible to filter woocommerce product tags programmatically?

I am using tags for some product display filtering, grouping them into specific groups. At the same time I am displaying product tags on product pages for SEO purposes so I end up with a bunch of tags that are not that good looking for the customer. Is it possible to programmatically remove them before displaying for the customer?

ChatGPT is offering a filter that does not exist or I can not find documentation for it:

function exclude_specific_tags_from_display($tags, $product) {
    // Define tags to exclude
    $excluded_tags = array('shop-by-birthday-gift-tote-bag');
    
    // Filter out the excluded tags
    $tags = array_filter($tags, function($tag) use ($excluded_tags) {
        return !in_array($tag->slug, $excluded_tags);
    });

    return $tags;
}

add_filter('woocommerce_product_get_tags', 'exclude_specific_tags_from_display', 10, 2);

And this of course does not work as expected.

Multiple conditions in array for comparison?

I am trying to check conditions inside foreach for a dynamic array.

My Array:

Array
(
    [0] => Array
        (
            [type] => target_id
            [operator] => Equals
            [value] => 13
            [operation] => OR
        )
    [1] => Array
        (
            [type] => target_id
            [operator] => Equals
            [value] => 14
            [operation] => OR
        )
    [2] => Array
        (
            [type] => target_id
            [operator] => Equals
            [value] => 15
            [operation] => OR
        )
)

Say I have a variable:

$target_id = 14;

I want to check this way

$override = false;

foreach($array as $key => $value){
    if($value["type"] == "target_id" && $value["operator"] == "Equals"){
        if($target_id == $value["value"]){
            $override = true;
        }
    }
}

If I generate a filter string, it would look like: 13 == 14 OR 14 == 14 OR 14 == 15

So my logic would be if(13 == 14 OR 14 == 14 OR 14 == 15)

I am not sure how to add the operation condition inside foreach. Can anyone point me to the right direction please?

there is a issue occurs while creating segment


 $response = $client->lists->createSegment("46ec78750d", [
    'name' => $request->name,
    'options' => [
        'match' => 'any',
        'conditions' => [
            [
                'condition_type' => 'EmailAddress',
                'field' => 'merge0',
                'op' => 'in',
                'value' => $emails
            ]
        ]
    ]
]);

I am trying to create a segment in Mailchimp using their API. Above’s the code I’m using

However, I encounter the following error:

Error creating segment: Client error: `POST https://us12.api.mailchimp.com/3.0/lists/46ec78750d/segments`resulted in a `400 Bad Request`response: {
    "type": "https://mailchimp.com/developer/marketing/docs/errors/",
    "title": "Invalid Resource",
    "status": 400,
    "detail": "The r (truncated...)

Route 404 in laravel11. Is there any rule to prioritize route in web.php

My issue is, even if I added route in web.php then also it gives me 404 not found.

My route file as below.

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersStudentController;

Route::get('/students', [StudentController::class, 'index'])->name('students.index');
Route::get('students/export/excel', [StudentController::class, 'exportExcel'])->name('students.export.excel');
Route::get('students/export/pdf', [StudentController::class, 'exportPdf'])->name('students.export.pdf');
Route::get('students/{student}', [StudentController::class, 'show'])->name('students.show');
Route::get('/students/create', [StudentController::class, 'create'])->name('students.create');
Route::post('/students/store', [StudentController::class, 'store'])->name('students.store');

If I add my route
Route::get('/students/create', [StudentController::class, 'create'])->name('students.create');
below the route
Route::get('students/{student}', [StudentController::class, 'show'])->name('students.show');
it gives me 404 and if I add my route above the
Route::get('students/{student}', [StudentController::class, 'show'])->name('students.show');
it works fine.

How is it possible? Can anyone explain this or provide the some link so I can understand the how it works?

Thanks in Advance. 🙂

how a class call with this format? [duplicate]

hi I clone a php library from github but xampp get this error:
Fatal error: Uncaught Error: Class “PHPUnitFrameworkTestCase” not found in C:xampphtdocsbrowsertestsBrowserTest.php:12 Stack trace: #0 {main} thrown in C:xampphtdocsbrowsertestsBrowserTest.php on line 12

I not exper but someone can help to me

Getting this error in the below code >> Fatal error: Uncaught ArgumentCountError:

Getting this error in the below code

Warning: Cannot modify header information – headers already sent by (output started at /home/kvkprose/public_html/index.php:48) in /home/kvkprose/public_html/header.php on line 15

Warning: Cannot modify header information – headers already sent by (output started at /home/kvkprose/public_html/index.php:48) in /home/kvkprose/public_html/header.php on line 16

Warning: Cannot modify header information – headers already sent by (output started at /home/kvkprose/public_html/index.php:48) in /home/kvkprose/public_html/header.php on line 17

Warning: Cannot modify header information – headers already sent by (output started at /home/kvkprose/public_html/index.php:48) in /home/kvkprose/public_html/header.php on line 18

$connection = new mysqli("127.0.0.1","*******","******","*********");

if ($connection->connect_error) 
{
    die("Connection failed: " . $connection->connect_error);
}

function exe_query($conn, $query) 
{ 
  $result = mysqli_query($conn, $query); 

  if (!$result) 
  { 
    die("Query failed: " . mysqli_error($conn)); 
  }

  $rows = [];
  while ($row = mysqli_fetch_assoc($result))
  { 
    $rows[] = $row; 
  }

  return $rows; 
}


$company_data=exe_query($connection, "select * from tbl_admin");
 $contact_data=exe_query($connection,"select * from tbl_contact");
 $about_data=exe_query($connection,"select * from tbl_about where id=3");
 $social_data=exe_query($connection,"select * from tbl_social where id=1");
        $full_name  = $_SERVER['PHP_SELF'];
        $name_array = explode('/',$full_name);
        $count      = count($name_array);
        $page_name  = $name_array[$count-1];


        header("Strict-Transport-Security:max-age=63072000");
        header("X-XSS-Protection: 1; mode=block");
        header('X-Content-Type-Options: nosniff');
        header("Expect-CT: enforce; max-age=30; report-uri='**********");

        $mypage=explode(".",$page_name);