Postman always gives me 404 on my post requests written in laravel. route problem?

I started laravel for learning purposes, I have been working with php for a long time.
So far I only have db, a User Model, a UserController (register and login), my own routes in api.php. Maybe that would be enough.
But Postman always gives me 404 on my post requests written in laravel. if i see in the documentation correctly it should list my own routes on route:list. I don’t see them there.

Someone push me further 🙂 ty

I have restarted the project several times but always get this far. Is my package missing ? Or where should I start to move on ? php code does not indicate an error , php artisan serve starts fine…
On the various composer steps, artisan route: clear, cache has been there already….
Basic get methods work fine (welcome, sanctum/csrf-cookie…)
PHP 8.2.12 , Laravel 11.10.0, Sanctum v4.0.2

Laravel Livewire Categories function affecting another input

I’m trying to get the categories and it’s categories as nested items. Following code works, but the problem is when I input minimum price or maximum price value, only parent categories comes up when content changed on the page.

How can I solve this unexpected behavior?

sidebar.blade.php

<div class="bg-white p-6 border border-border-white rounded-md hidden md:flex md:flex-col md:gap-6 md:max-w-[270px] h-fit">
    <div>
       <p class="capitalize font-semibold">type</p>
       <ul class="mt-3 flex flex-col gap-1">
           <li class="flex items-center gap-2">
               <input type="radio" id="any" wire:model="type" class="accent-purple w-4 h-4" value="any" wire:click="type">
               <label for="any" class="capitalize">any</label>
           </li>
           <li class="flex items-center gap-2">
               <input type="radio" id="auction" wire:model="type" class="accent-purple w-4 h-4" value="auction" wire:click="type">
               <label for="auction" class="capitalize">Auction</label>
           </li>
           <li class="flex items-center gap-2">
               <input type="radio" id="classified" wire:model="type" class="accent-purple w-4 h-4" value="classified" wire:click="type">
               <label for="classified" class="capitalize">classified</label>
           </li>
           selected {{$type}}
       </ul>
   </div> 
    <div>
enter code here
       <p class="capitalize font-semibold">category</p>
       <ul class="mt-3 flex flex-col gap-1">
           <li class="flex items-center gap-2">
               <input type="radio" id="any" wire:model="category" class="accent-purple w-4 h-4" wire:click="category" value="0">
               <label for="any" class="capitalize">any</label>
           </li>
           @foreach ($categories as $category)
               <li class="flex items-center gap-2">
                    <input type="radio" id="classified" wire:model="category" class="accent-purple w-4 h-4" wire:click="category" value="{{ $category->id}}">
                    <label for="classified" class="capitalize">{{ __($category->name) }}</label>
                </li>
                @if(!is_null($category->subcategories))
                <ul class="mt-1 ml-5 flex flex-col gap-1">
                    @foreach ($category->subcategories as $subcategory)
                        <li class="flex items-center gap-2">
                            <input type="radio" id="apperal" wire:model="category" class="accent-purple w-4 h-4" wire:click="category" value="{{ $subcategory->id}}">
                            <label for="apperal" class="capitalize">{{ __($subcategory->name) }}</label> 
                        </li>
                    @endforeach
                </ul>
                @endif
           @endforeach
       </ul>
   </div>
   <div>
       <p class="capitalize font-semibold">price</p>
       <input type="number" wire:model="min_price" wire:model.live="min_price" id="min_price" placeholder="Min Price" class="mt-3 w-full border border-border-white rounded-md p-4 focus:outline-none focus:border-purple">
       @error('min_price')
            <p class="text-sm mt-1 text-red-500">{{ $message}}</p>
       @enderror
       <input type="number" wire:model="max_price" wire:model.live="max_price" id="max_price" placeholder="Max Price" class="mt-1 w-full border border-border-white rounded-md p-4 focus:outline-none focus:border-purple">
   </div>
</div>

Sidebar.php

    <?php

namespace AppLivewireListings;

use LivewireComponent;
use AppModelsCategory;
use LivewireAttributesUrl;
use LivewireAttributesValidate;

class Sidebar extends Component
{
    #[Url]
    public $type = 'any';

    #[Url]
    public $category = 'any';

    #[Url, Validate]
    public $min_price = '';

    #[Url]
    public $max_price = '';

    public $categories;

    public function mount()
    {
        $this->categories = $this->getNestedCategories();
        
    }

    private function getNestedCategories($parentId = null)
    {
        $categories = Category::where('parent_id', $parentId)->get();
        
        foreach ($categories as $category) {
            $category->subcategories = $this->getNestedCategories($category->id);
        }
        
        return $categories; 
    }

    public function rules()
    {
        return [
            'min_price' => 'numeric|between:1,999999999',
            'max_price' => 'numeric|between:1,999999999',
        ];
    }

    public function render()
    {
        return view('livewire.listings.sidebar', [
            'categories' => $this->categories,
        ]);
    }
}

Category.php

 <?php

namespace AppModels;

use AppStatus;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsBelongsTo;
use IlluminateDatabaseEloquentRelationsHasMany;

class Category extends Model
{
    use HasFactory;

    public function Listings(): HasMany
    {
        return $this->hasMany(Listing::class, 'category_id');
    }

    public function child(): HasMany
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    public function parent(): BelongsTo
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    protected $casts = [
        'is_active' => Status::class,
    ];
}

Laravel Jetstream remembers email verification after deleting the account

Larael 11.10.0, Ubuntu 24.04.
I’m testing the Jetstream email verification feature for registration.

I just setup my .env database and email section in order to match my configuration.
The code is the default one after creating a new project. I enabled the verification feature in User.php:

class User extends Authenticatable implements MustVerifyEmail

Here the step to reproduce the issue:

  1. open http://127.0.0.1:8000 and click on Register
  2. fill the form and submit
  3. wait for the activation email and click on the link
  4. login and open the profile settings
  5. DELETE the account
  6. register again with the same email

I’m expecting the activation email is sent as usual, instead it shows the “Resend email” dialog:

enter image description here

Why (and where) it remembers the deleted account email?
It’s not browser’s side (i.e. cookies) because I deleted them.
I checked in the database (table Users) and the table is empty.

How to avoid this odd behavior?

how to update a user’s table in firestore using Laravel

i have a users table i created and currently i can update the table from edit submit form with just one field (amount) but currently i want to retrieve the users details to the edit submit form so i can review them before updating all the fields

I’m using firestore and laravel, below is my controller

Thanks in advance

// my edit button below
 <td><a href="{{ url('admin/edit-ref-transfer/'.$item['post_id']) }}" class="btn btn-dark">Debit</a></td>


//my route(web.php) code below

 Route::get('edit-ref-transfer/{post_idz}', [AppHttpControllersAdminDashboardController::class, 'edit']);
     Route::put('update-ref-transfer/{post_idz}', [AppHttpControllersAdminDashboardController::class, 'update']);



 //below are my controllers DASHBORDCONTROLLER

public function edit($post_idz)
    {
    $key = $post_idz;
    $addAmountToUserTotals =  app('firebase.firestore')->database()->collection('refWithdrawlz')->document($key);
     if($addAmountToUserTotals)
        {
            return view('admin/edit-ref-transfer',compact('addAmountToUserTotals','key'));
        } else
        {
              return view('admin/ref-transfer')->with('status','error');
        }
    }


   public function update(Request $request, $post_idz)
    {
    $datetime = Carbon::now()->toDateTimeString();
 $cur_date = Carbon::createFromFormat('Y-m-d H:i:s', $datetime)->format('d-m-Y');
  $addAmountToUserTotalszz =  app('firebase.firestore')->database()->collection('refWithdrawlz')->document($post_idz);
      $addAmountToUserTotalszz->update([
                  ['path' => 'amountToPay', 'value' => ((int)$request->amountToPay)],
                  ['path' => 'debitedAmount', 'value' => ((int)$request->amountToPay)],
                  ['path' => 'status', 'value' => ('Debited')],
                  ['path' => 'debitedDate', 'value' => ($cur_date)],
                ]);
                 if($addAmountToUserTotalszz)
        {
            return redirect('admin/ref-transfer')->with('status','Referral point debited successfully');
        } else
        {
              return redirect('admin/ref-transfer')->with('status','Referral point not successfully debited, please try again ');
        }
                
    }

i want to be able to edit users email and other fields and would like to retrieve them then update. i will be glad to get help thanks

Where are PHP extensions/modules stored on MacOS Homebrew installation?

I am currently in the process of trying to integrate a PostgreSQL database into a PHP application.

When I run php -m, it lists a very long list of extensions/modules which are allegedly installed, such as pdo_pgsql. (The extension I wish to use).

However, when I edit my php.ini file and uncomment the extension=pdo_pgsql line, enabling the extension, PHP will start throwing errors at me constantly:

PHP Warning: PHP Startup: Unable to load dynamic library ‘pdo_pgsql’
(tried: /usr/local/lib/php/pecl/20230831/pdo_pgsql

Obviously, the problem here is that my php.ini file is stating extension_dir="/usr/local/lib/php/pecl/20230831", and even from looking there myself, that folder is empty.

Are the extensions/modules which the php -m command said are installed actually installed? If so, where could they be found (so that I can point my php.ini file’s extension_dir line there).

I am running macOS Sonoma 14.5, and I installed PHP using Homebrew, it is version 8.3.8.

I have tried using the UNIX terminal command find . -name "*pgsql*" -exec ls -ld {} ; to search for the extension, yet have found nothing.

Running php -m returns

[PHP Modules]
bcmath
bz2
calendar
Core
ctype
curl
date
dba
dom
exif
FFI
fileinfo
filter
ftp
gd
gettext
gmp
hash
iconv
intl
json
ldap
libxml
mbstring
mysqli
mysqlnd
odbc
openssl
pcntl
pcre
PDO
pdo_dblib
pdo_mysql
PDO_ODBC
pdo_pgsql
pdo_sqlite
pgsql
Phar
posix
pq
pspell
random
raphf
readline
Reflection
session
shmop
SimpleXML
soap
sockets
sodium
SPL
sqlite3
standard
sysvmsg
sysvsem
sysvshm
tidy
tokenizer
xml
xmlreader
xmlwriter
xsl
Zend OPcache
zip
zlib

[Zend Modules]
Zend OPcache

And the full error which PHP gives me is

PHP Warning: PHP Startup: Unable to load dynamic library ‘pdo_pgsql’
(tried: /usr/local/lib/php/pecl/20230831/pdo_pgsql
(dlopen(/usr/local/lib/php/pecl/20230831/pdo_pgsql, 0x0009): tried:
‘/usr/local/lib/php/pecl/20230831/pdo_pgsql’ (no such file),
‘/System/Volumes/Preboot/Cryptexes/OS/usr/local/lib/php/pecl/20230831/pdo_pgsql’
(no such file), ‘/usr/local/lib/php/pecl/20230831/pdo_pgsql’ (no such
file)), /usr/local/lib/php/pecl/20230831/pdo_pgsql.so
(dlopen(/usr/local/lib/php/pecl/20230831/pdo_pgsql.so, 0x0009): tried:
‘/usr/local/lib/php/pecl/20230831/pdo_pgsql.so’ (no such file),
‘/System/Volumes/Preboot/Cryptexes/OS/usr/local/lib/php/pecl/20230831/pdo_pgsql.so’
(no such file), ‘/usr/local/lib/php/pecl/20230831/pdo_pgsql.so’ (no
such file))) in Unknown on line 0

Warning: PHP Startup: Unable to load dynamic library ‘pdo_pgsql’
(tried: /usr/local/lib/php/pecl/20230831/pdo_pgsql
(dlopen(/usr/local/lib/php/pecl/20230831/pdo_pgsql, 0x0009): tried:
‘/usr/local/lib/php/pecl/20230831/pdo_pgsql’ (no such file),
‘/System/Volumes/Preboot/Cryptexes/OS/usr/local/lib/php/pecl/20230831/pdo_pgsql’
(no such file), ‘/usr/local/lib/php/pecl/20230831/pdo_pgsql’ (no such
file)), /usr/local/lib/php/pecl/20230831/pdo_pgsql.so
(dlopen(/usr/local/lib/php/pecl/20230831/pdo_pgsql.so, 0x0009): tried:
‘/usr/local/lib/php/pecl/20230831/pdo_pgsql.so’ (no such file),
‘/System/Volumes/Preboot/Cryptexes/OS/usr/local/lib/php/pecl/20230831/pdo_pgsql.so’
(no such file), ‘/usr/local/lib/php/pecl/20230831/pdo_pgsql.so’ (no
such file))) in Unknown on line 0 [PHP Modules]

Need to Fix: Call to a member function real_escape_string()

I’ve created a login/register system in php, however I am receiving the call to member error, and Im unsure on how to fix it? I am simply trying to check that the password the user inputted into signup.php is the same as the hashed and original password in signup_user.php.

Here is my code:

sigin.php
<?php
ini_set("display_errors", "1");
ini_set("display_startup_errors", "1");
error_reporting(E_ALL);

$is_invalid = false;

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $mysqli = require __DIR__ . "/connection.php";

    $sql = sprintf("SELECT * FROM users
            WHERE user_name = '%s'",
            # prevent sql injection(below)
            $mysqli->real_escape_string($_POST["Username"]));

    $result = $mysqli->query($sql);

    $user = $result->fetch_assoc();

    if ($user) {

       if (password_verify($_POST["Password"], $user["password_hash"])) {

        session_start();

        session_regenerate_id();

        $_SESSION["id"] = $user["user_id"];
        echo "Successful Login :) ... redirecting";
        exit;
       }
    }

    $is_invalid = true;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Login to your account</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Roboto|Courgette|Pacifico:400,700" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/signin.css">
</head>
<body>
<div class="signin-form">
    <form action="" method="post">
        <div class="form-header">
            <h2>Sign In</h2>
            <p>Login to MyChat</p>
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="text" class="form-control" name="Username" autocomplete="off" required="required">
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" class="form-control" placeholder="Password" name="Password" autocomplete="off" required="required">
        </div>
        <div class="small">Forgot password? <a href="forgot_pass.php">Click Here</a></div><br>
        <div class="form-group">
            <button type="submit" class="btn btn-primary btn-block btn-lg" name="sign_in">Sign in</button>
        </div>
        <?php #include("signin_user.php"); ?>   
    </form>
    <div class="text-center small" style='color:#67428B;'>Don't have an account? <a href="signup.php">Create one</a></div>
</div>
</body>
</html>    
connection.php
<?php
$con = mysqli_connect("localhost","root","","ecom") or die("Connection was not established");
?>
signup_user.php
<?php
ini_set("display_errors", "1");
ini_set("display_startup_errors", "1");
error_reporting(E_ALL);


#include("/connection.php");
include("/Applications/XAMPP/xamppfiles/htdocs/Ecom/chat/code/connection.php");


    if(isset($_POST['sign_up'])){
        
    # password hash:

    $password = $_POST['user_pass'];
    $confirm_password = $_POST['confirm_user_pass'];
    $pin = $_POST['user_pin'];
    $confirm_pin = $_POST['confirm_user_pin'];
    
    $password_hash = password_hash($password, PASSWORD_DEFAULT);
    $confirm_password_hash = password_hash($confirm_password, PASSWORD_DEFAULT);
    $pin_hash = password_hash($pin, PASSWORD_DEFAULT);
    $confirm_pin_hash = password_hash($confirm_pin, PASSWORD_DEFAULT);
    
    # pass hash data & POST data to db:

    $name = htmlentities(mysqli_real_escape_string($con,$_POST['user_name']));
    $pass = htmlentities(mysqli_real_escape_string($con,$password_hash));
    $confirm_pass = htmlentities(mysqli_real_escape_string($con,$confirm_password_hash));
    $pin = htmlentities(mysqli_real_escape_string($con,$pin_hash));
    $confirm_pin = htmlentities(mysqli_real_escape_string($con,$confirm_pin_hash));
    $rand = rand(1, 3); //Random number between 1 and 3

    # Register Validation
    if(empty($name)){
        echo "<script>alert('Username is required')</script>";
    }
    if(strlen($name) < 3) {
        echo "<script>alert('Username must be 3 - 30 characters')</script>";
        exit();
    }elseif(strlen($name) > 30) {
        echo "<script>alert('Username must be 3 - 30 characters')</script>";
        exit();
    }
    if(strlen($_POST['user_pass'])<12){
        echo "<script>alert('Password must be at least 12 characters')</script>";
        exit();
    }
    if(! preg_match("/[A-Z]/i", $_POST["user_pass"])){
        echo "<script>alert('Password must contain at least one capital letter')</script>";
        exit();
    }
    if (! preg_match("/[0-9]/", $_POST["user_pass"])) {
        echo "<script>alert('Password must contain at least one number')</script>";
        exit();
    }
    if (! preg_match("/[^a-zA-Z0-9]/", $_POST["user_pass"])) {
        echo "<script>alert('Password must contain at least one symbol')</script>";
        exit();
    }
    if ($_POST["user_pass"] !== $_POST["confirm_user_pass"]) {
        echo "<script>alert('Password must match')</script>";
        exit();
    }
    if (! is_numeric($_POST["user_pin"])) {
        echo "<script>alert('Pin must contain numbers only')</script>";
        exit();
    }
    if ($_POST["user_pin"] !== $_POST["confirm_user_pin"]) {
        echo "<script>alert('Pin must match')</script>";
        exit();
    }

    # Check for duplicate Username
    $check_username = "select * from users where user_name='$name'";
    $run_username = mysqli_query($con,$check_username);

    $check = mysqli_num_rows($run_username);

    if($check==1){

    echo "<script>alert('Username already exist, please try another!')</script>";
    echo "<script>window.open('signup.php','_self')</script>";
    exit();
    }
    }   

    # Pass php variable into sql db
    $insert = "insert into users (user_name,
                                user_pass,
                                confirm_user_pass,
                                user_pin,
                                confirm_user_pin)
                values ('$name',
                        '$pass',
                        '$confirm_pass',
                        '$pin',
                        '$confirm_pin')";

    $query = mysqli_query($con,$insert);

    # Register confirmation
    if($query){
    echo "<script>alert('Congratulations $name, your account has been created successfully.')</script>";
    echo "<script>window.open('signin.php','_self')</script>";
    }
    else {
    echo "<script>alert('Registration failed, try again!')</script>";
    echo "<script>window.open('signup.php','_self')</script>";
    }
}
?>

Make a page only viewable when logged in

i need help in making my dashboard only accessible when the admin is logged in.

Hello!.. I am creating a school website to improve my html skills. I’ve created home page, about us, and everything that will be in a normal school website. i have created the admin login page too and stored it in (/admin) folder. when the admin enters the correct username and password, he will be redirected to (/admin/dashboard). but the problem is i can still access the dashboard without logging in by visiting (/admin/dashboard). Now how can i make the dashboard only accessible when logged in? (btw im using XAMPP Apache Server, and phpMyAdmin)

My Login Page HTML Code (in case if needed):

<!DOCTYPE html>
<html>

<head>
      <title>Admin - Sri Swarna Vidhyashram</title>
      <link rel="stylesheet" href="css/style.css">
      <link rel="icon" type="image/x-icon" href="../assets/images/logo.png">
</head>

<body>
      <div class="main">
            <img src="../assets/images/ssv.png" height="110"><br>
            <form action="login.php" method="POST">
                  <label for="username">Username:</label>
                  <input type="text" 
                         id="username" 
                         name="username" 
                         placeholder="Enter your Username" required>

                  <label for="password">Password:</label>
                  <input type="password"
                         id="password" 
                         name="password"
                         placeholder="Enter your Password" required>

                  <div class="wrap">
                        <button type="submit">Submit</button>
                  </div>
            </form>
      </div>
</body>

</html>

And the PHP Script:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "login";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

echo "Connected successfully"; // Debugging message

// Retrieve username and password from the form
$username = $_POST['username'];
$password = $_POST['password'];

echo "Username: " . $username . "<br>"; // Debugging message
echo "Password: " . $password . "<br>"; // Debugging message

// Query to check if the provided credentials are correct
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // If the user exists, display welcome message
    header("Location:dashboard.html");
} else {
    // If the user doesn't exist or the password is incorrect, show error message
    header("Location:error.html");
}

$conn->close();
?>

Thx in advance! 🙂

how to fix Fatal error: Uncaught Error: Undefined constant “q” in C:xampphtdocs1web.php:15 Stack trace: #0 {main} thrown in C:xampphtdocs1

i am trying to make the php website to work
but it tell me Warning: Undefined variable $q in C:xampphtdocs1amyweb2.php on line 27

<?php
echo "hello"."<br>"."this is the website"."<br>"."<br>"
?>
<html>
<body>
  <form action="myweb.py" method="POST">
    what is your name: <input type="text" name="q"><br><br>
    what is your emall: <input type="text" name="w"><br>
    <input type="submit"> 
  </form>
</body>
</html>

<?php
$fp = fopen('q.txt', 'w');
if ($fp === false) {
    echo "Error opening the file";
} else {
    fwrite($fp, $q);
    fclose($fp);
}
?>

i tried to make $q = none in the start so win i type an input it change before it write the txt file but
it didn’t work

Doctrine DB Migration that matches existing DB Setup

I have a Database that was created in a Node App with Sequilize.
I am moving the whole app from node to php 8.3 and Symfony 6.4 + doctrine.
When trying to adapt the entities to Doctrine and run the migrations Doctrine is recreating some fields and also the FK. I want to avoid this to happen but I am not sure what else I should be doing…

The Entities in the NodeApp looks like this:

module.exports = (sequelize, DataTypes) => {
    class CognitoUser extends Model {
        static associate (models) {
            CognitoUser.belongsTo(models.UserProfile, {
                foreignKey: 'userProfileUuid',
                onUpdate: 'CASCADE',
                onDelete: 'RESTRICT'
            });
        }
...
CognitoUser.init({
        UserPoolId: {
            type: DataTypes.STRING,
            primaryKey: true,
            allowNull: false
        },
        Username: {
            type: DataTypes.STRING,
            primaryKey: true,
            allowNull: false
        },
        UserEmail: DataTypes.STRING,
        UserCreateDate: DataTypes.DATE,
        UserLastModifiedDate: DataTypes.DATE,
        UserStatus: DataTypes.STRING,
        Enabled: DataTypes.BOOLEAN,
        // MixedCase for Cognito native, camelCase for everything else
        customSwitchToEmailFlow: DataTypes.BOOLEAN,
        cognitoSyncedAt: DataTypes.DATE,
        userProfileUuid: {
            type: DataTypes.UUID,
            allowNull: false
        }
    }, { sequelize, modelName: 'CognitoUser', tableName: 'CognitoUser', timestamps: false });
    return CognitoUser;

the UserProfile entity looks like this:

module.exports = (sequelize, DataTypes) => {
    class UserProfile extends Model {
        static associate (models) {
            UserProfile.hasOne(models.CognitoUser, { foreignKey: 'userProfileUuid' }); // -> CognitoUser kriegt ne Spalte
            UserProfile.belongsTo(models.CoreCustomer, {
                foreignKey: 'coreCustomerUuid'
            });
            UserProfile.hasMany(models.UserProductRole, { foreignKey: 'userProfileUuid' });
        }
    }
    UserProfile.init({
        uuid: {
            type: DataTypes.UUID,
            primaryKey: true,
            allowNull: false,
            defaultValue: DataTypes.UUIDV4
        }
    }, { sequelize, modelName: 'UserProfile', tableName: 'UserProfile' });
    return UserProfile;
};

The tables that are being generated by the Sqlize migration look like this:


CREATE TABLE `CognitoUser` (
  `UserPoolId` varchar(255) NOT NULL,
  `Username` varchar(255) NOT NULL,
  `UserEmail` varchar(255) DEFAULT NULL,
  `UserCreateDate` datetime DEFAULT NULL,
  `UserLastModifiedDate` datetime DEFAULT NULL,
  `UserStatus` varchar(255) DEFAULT NULL,
  `Enabled` tinyint(1) DEFAULT NULL,
  `cognitoSyncedAt` datetime DEFAULT NULL,
  `userProfileUuid` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
  `customSwitchToEmailFlow` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`UserPoolId`,`Username`),
  KEY `userProfileUuid` (`userProfileUuid`),
  CONSTRAINT `CognitoUser_ibfk_1` FOREIGN KEY (`userProfileUuid`) REFERENCES `UserProfile` (`uuid`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;

and the UserProfile Table:

CREATE TABLE `UserProfile` (
  `uuid` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `coreCustomerUuid` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
  PRIMARY KEY (`uuid`),
  KEY `coreCustomerUuid` (`coreCustomerUuid`),
  CONSTRAINT `UserProfile_ibfk_1` FOREIGN KEY (`coreCustomerUuid`) REFERENCES `CoreCustomer` (`uuid`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;

The entities in Doctrine are defined like this:

#[ORMEntity]
#[ORMTable(name:"CognitoUser")]
#[ORMIndex(name: 'userProfileUuid', columns: ['userProfileUuid'])]
class CognitoUser
{
    #[ORMId]
    #[ORMColumn(type: "string", length: 255)]
    private string $UserPoolId;

    #[ORMId]
    #[ORMColumn(type:"string", length: 255)]
    private string $Username;

    #[ORMColumn(type:"string", length: 255, nullable: true)]
    private ?string $UserEmail = null;

    #[ORMColumn(length: 255, nullable: true)]
    private ?DateTime $UserCreateDate = null;

    #[ORMColumn(length: 255, nullable: true)]
    private ?DateTime $UserLastModifiedDate = null;

    #[ORMColumn(length: 255, nullable: true)]
    private ?string $UserStatus = null;

    #[ORMColumn(nullable: true)]
    private ?bool $Enabled = null;

    #[ORMColumn(type: "boolean", nullable: true)]
    private ?bool $customSwitchToEmailFlow = null;

    #[ORMColumn(nullable: true)]
    private ?DateTime $cognitoSyncedAt = null;

    #[ORMManyToOne(targetEntity: UserProfile::class, inversedBy: 'cognitoUsers')]
    #[ORMJoinColumn(
        name:"userProfileUuid",
        referencedColumnName: "uuid",
        nullable: false,
        columnDefinition: "CHAR(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL"
    )]
    private ?UserProfile $userProfileUuid = null;

and the UserProfile Entity looks like this:

#[ORMEntity]
class UserProfile
{
    use DefaultEntityPropertiesTrait;

    #[ORMId]
    #[ORMColumn(
        type: "string",
        length: 36,
        options: ["fixed"=>true],
        columnDefinition: "CHAR(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL"
    )]
    private ?string $uuid = null;

    /**
     * @var Collection<int, CognitoUser>
     */
    #[ORMOneToMany(targetEntity: CognitoUser::class, mappedBy: 'userProfileUuid')]
    private Collection $cognitoUsers;

    /**
     * @var Collection<int, UserProductRole>
     */
    #[ORMOneToMany(targetEntity: UserProductRole::class, mappedBy: 'userProfileUuid')]
    private Collection $userProductRoles;


    #[ORMManyToOne(inversedBy: 'userProfiles')]
    #[ORMJoinColumn(name: "coreCustomerUuid", referencedColumnName: "uuid", nullable: true)]
    private ?CoreCustomer $coreCustomerUuid = null;

    public function __construct()
    {
        $this->cognitoUsers = new ArrayCollection();
        $this->userProductRoles = new ArrayCollection();
    }

I have also made this changes in doctrine.yaml file:

doctrine:
    dbal:
    ...
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_bin

When running the command make:migration I am getting the following which I am trying to avoid:

$this->addSql('ALTER TABLE CognitoUser DROP FOREIGN KEY CognitoUser_ibfk_1');
$this->addSql('ALTER TABLE CognitoUser CHANGE userProfileUuid userProfileUuid CHAR(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL');
$this->addSql('ALTER TABLE CognitoUser ADD CONSTRAINT FK_60B8CF0DD034F61E FOREIGN KEY (userProfileUuid) REFERENCES UserProfile (uuid)');

How do i reset the variable in setInterval js

I am having problem in which I want to logout user if there is no activity within 180 seconds if there is any then it will reset the timer but the problem is the timer is not resetting I checked through logs here my code
if ($isManager || $isAdmin) { ?> var total_session_time = 180; // In seconds. After this interval of time if user is ideal then clock timer will start in seconds //var total_session_time = 50000;//180; // In seconds. After this interval of time if user is ideal then clock timer will start in seconds var clock_time_start = total_session_time + 1; var idleTime = 0; $(document).ready(function() { // alert('hello'); // console.log('total_session_time->' + total_session_time) //idleTime = $('#idleTime').val(); var sms_access_page = $('#sms_page_access').val(); // get val. for handle the logic of sms page will not logout. // console.log('sms_accss_if_value - '+sms_access_page); var idleInterval = setInterval(function() { if ($('#idleTime').val()) { idleTime = $('#idleTime').val(); } else { idleTime = 0; } if ($('#pauseLogoutScript').val() == 0) { idleTime = parseInt(idleTime) + 5; // as interval is of 5 seconds added 5. } //console.log('idleTime ->'+idleTime); $('#idleTime').val(idleTime); if (idleTime > total_session_time) { count = clock_time_start - idleTime; // console.log('count ->' + count); if (count <= 0) { if (sms_access_page != '' && sms_access_page == '7') { console.log('sms page will not logout- ' + sms_access_page); } else { console.log('logging out'); window.location = 'index.php?r=site/logout' //return; } } } }, 5000); // 1000 = 1 sec $(this).mousemove(function(e) { $('#idleTime').val(''); }); $(this).keypress(function(e) { $('#idleTime').val(''); }); }); <?php } ?>

Thank You in advance!

I want to reset the idleTime variable

Php dispay date if exists in database [closed]

<?php

session_start(); // Start or resume the session

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


require_once '../db.php';
date_default_timezone_set("Asia/Calcutta");


if(isset($_POST['email'])) {
    $email = $conn->real_escape_string($_POST['email']);
    $sql = "SELECT date FROM jagran WHERE email = '$email'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        echo $row['date'];
    } else {
        echo "";
    }
}

here is the php code for connection and a query to fetch data from database

below is the html button code & java script i am using.

<script>
$(document).ready(function(){
    $('#email').on('blur', function(){
        var email = $(this).val();
        if(email) {
            $.ajax({
                url: 'check_email.php',
                method: 'POST',
                data: { email: email },
                success: function(response){
                    if(response) {
                        $('#date-display').html('<div class="alert alert-warning">Caution: This email has been registered on ' + response + '.</div>');
                    } else {
                        $('#date-display').html('<div class="alert alert-danger">Email not found.</div>');
                    }
                },
                error: function(){
                    $('#date-display').html('<div class="alert alert-danger">Error checking email.</div>');
                }
            });
        }
    });
});
</script>
<div class="col-md-6 mb-1 mb-md-2">
                                        <label class="form-label required">Email </label>
                                        <input type="email" class="form-control" id="email" name="email" required>
                                        <div id="email-message" class="mt-2"></div>
                                    </div>

I have a form which also have a email input field. I want to display date from the database table when user enters its email it it will be checked if it exists in the database table the date related to the email will get displayed. this is a booking form for a room so that is the reason why i need it.

I can’t fetch from a php file to javascript

I am currently trying to output data from my php file into javascript, but I get this error:
(https://i.sstatic.net/9QL2o1bK.png)

script.js file:

fetch('./index.php', {
        method: 'post'
      }).then(response => {
         return response.text();
      }).then(response => {
         document.getElementById("status").innerHTML = response
      });

index.php file:

<?php
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return $ip;
?>

I was expecting the php file I fetched to output the ip address, but that didn’t work and return 405 error.

file_get_contents(C:ProgramDataComposerSetupbin): Failed to open stream: Permission denied

(https://i.sstatic.net/T0oyzBJj.png)
I got an error when I tried to import the package using Composer. That’s when I observed the issue

I tried to import the package, but I’m facing an issue. I tried some commands like ‘php artisan cache:clear’, ‘chmod -R 777 storage vendor’, and ‘composer dump-autoload’. However, it showed an error: ‘Could not open input file: artisan’

Add span tag to anchor text, but not to anchor link if the word present in link as well

Add span tag to anchor text, not to anchor link

This is for search in PHP.
Search is working fine for other fileds, but, title field has link as well.
Example:
$htmlContent = ‘Testing for html tags‘;
So, whenever user search for the keyword “testing”, I have added span tag, but its added to link as well, as the word present there as well.
I want to exclude link, but not the link text.

href link and anchor text will be dynamic.
I just want to add tag for Testing for html tags.
Can somebody help?

phpexcel cell value not showing up in excel file

For a legacy application I have to use PHPExcel and populate an existing Excel file(Excel5 format). A particular cell value starts disappearing in final excel file randomly. File is generated successfully without any errors but employee name is not populated in random rows. I tried it on PHP7.3 and PHP8.2, but same errors persists.

Here is the code I use to populate excel file

require_once dirname(__FILE__). '/../../php/PHPExcel/PHPExcel.php';     
$inputFileName = 'Template.xls';

// Read the existing excel file
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

$row=3;
for($i=0;$i<count($data);$i++){
            $row++;
            $objPHPExcel->getActiveSheet()
                        ->setCellValueExplicit('A'.$row, $data[$i]['code'],  PHPExcel_Cell_DataType::TYPE_STRING)
                        ->setCellValueExplicit('B'.$row, $data[$i]['employee_name'],  PHPExcel_Cell_DataType::TYPE_STRING)
                        ->setCellValueExplicit('C'.$row, $data[$i]['category_name'],  PHPExcel_Cell_DataType::TYPE_STRING);
}

If I insert following line in loop then employee name shows up properly in excel file

$data[$i]['employee_name']='123-'.$data[$i]['employee_name'];

If I use 12- then employee name disappears in some rows and if I use 1- then employee_name in some more rows go blank. I also tried with UTF encoding but the result was same. If I add * in place of *123- then also employee name goes away. It looks like if and only if I used some numeric prefix to the field only then it gets displayed.

What am I doing wrong, please help.