Laravel and React full API : login to site A log me on site B too

I’m using this project to make a full API application : https://github.com/justnixx/laravel-breeze-api-react using Laravel and React (I’m new to react and laravel).

Everything is ok on it, I’ve made the following DNS :
front.project.local:3000 (react frontend)
back.project.local:8000 (laravel backend)

Now I would like to make an administration site, so i duplicated the frontend project and made admin.project.local:3001 so that I have a new site with its own pages for administration.

I’ve configured all for both sites to work with the laravel backend.

Now my problem is, when i log in to front.project.local:3000, it also log me in to admin.project.local:3001 (same browser, 2 differents tabs). I dont want this, I would like each subdomain to have its own session.

In the laravel project i can see in folder storage/framework/sessions that only 1 session file is created for both sites and I dont understand why.

Am I missing something ? Or is it normal that only 1 session file is created ?

Any hints would be appreciated 😉

In both React projects I’m poiting to BACKEND_URL: “back.project.local:8000”
front is requesting to /* or /api/*
admin is requesting to /admin or /api/admin/*

In Laravel project .env I have the following configuration :

    APP_URL="back.project.local:8000"
    FRONTEND_URL="front.project.local:3000"
    FRONTADMIN_URL="admin.project.local:3001"
    ...
    #to prevent cors issues
    SESSION_DOMAIN=".project.local"     SANCTUM_STATEFUL_DOMAINS="localhost:3000,localhost:3001,project.local:3000,admin.project.local:3000,$admin.project.local:3001"

All my research are pointing to the opposite solution : people want shared session, me not.
(edit : removed http:// cause stackoverflow think this is spam)

how can i show relation of a branch to another branch via a branch

I have a schools table with list of schools in it but some schools are related to each other meaning school A can be related to school B and C and in this relation it also means there is a relation between all the schools and one another means it can be it can be like its primary,secondary and high school so they are all one. What i want is how can i store this relation so that when i am in B i can call its branches as C and A, and them same when i am in C i can call on B and A.

What i have tried is i have a school_branches table but in this i have saved initial school and branch school. What now happens is i have shown relation between A and B, and A and C, but no relation between B and C i see that i am going to end up with redundancy so as of now i can only call relation of A to the others but not the other way around, what can i do. I am using laravel.

Deactivating Autoptimize wordpress plugin breaks the website styles

The Autoptimize WordPress plugin was installed before for caching.
But now I want to switch to another cache plugin.SO when I de active the Autoptimize plugin the site is breaking.

I Have tried the following things

  • Cleared server cache
  • Removed /wp-content/cache/autoptimize
  • Cleared cache through php code.
  • Completely deleted plugin after deactivating.

But none of them could move forward me to the goal.

Error: “Unable to call method of non-object object”, when using State Providers in Api Platform

Following the SymfonyCasts tutorial, I attempted to automate the setting of the Creator field of my entity after denormalization with a State Processor class. Since the code provided in the tutorial seemed outdated, I copied and edited the passwordhasher class provided by the documentation.

Here’s my state processor:

namespace AppState;

use AppEntityCommunity;
use ApiPlatformMetadataOperation;
use ApiPlatformStateProcessorInterface;
use SymfonyBundleSecurityBundleSecurity;

final readonly class CommunityCreatorSetter implements ProcessorInterface
{
    public function __construct(
        private ProcessorInterface $processor,
        private Security $security
    ) {
    }
    
    /**
     * @param Community $data
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): Community
    {
        if ($data->getCreator() != null) {
            return $this->processor->process($data, $operation, $uriVariables, $context);
        }

        $data->setCreator($this->security->getUser());

        return $this->processor->process($data, $operation, $uriVariables, $context);
    }
}

Community entity methods:

public function getCreator(): ?User
{
    return $this->creator;
}

public function setCreator(?User $creator): static
{
    $this->creator = $creator;
    if ($creator !== null) {
        $membership = new Membership();
        $membership->setMember($creator);
        $membership->setSubreddit($this);
        $this->members->add($membership);
    }

    return $this;
}

Error on requests:

{
  "@id": "/api/errors/500",
  "@type": "hydra:Error",
  "title": "An error occurred",
  "detail": "Unable to call method "getCreator" of non-object "object".",
  "status": 500,
  "type": "/errors/500",
  "trace": [
    {
      "file": "/app/vendor/symfony/expression-language/Node/BinaryNode.php",
      "line": 103,
      "function": "evaluate",
      "class": "Symfony\Component\ExpressionLanguage\Node\GetAttrNode",
      "type": "->"
    },
    {
      "file": "/app/vendor/symfony/expression-language/Node/BinaryNode.php",
      "line": 118,
      "function": "evaluate",
      "class": "Symfony\Component\ExpressionLanguage\Node\BinaryNode",
      "type": "->"
    },
    {
      "file": "/app/vendor/symfony/expression-language/ExpressionLanguage.php",
      "line": 59,
      "function": "evaluate",
      "class": "Symfony\Component\ExpressionLanguage\Node\BinaryNode",
      "type": "->"
    },
    {
      "file": "/app/vendor/api-platform/core/src/Symfony/Security/ResourceAccessChecker.php",
      "line": 56,
      "function": "evaluate",
      "class": "Symfony\Component\ExpressionLanguage\ExpressionLanguage",
      "type": "->"
    },
    {
      "file": "/app/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",
      "line": 446,
      "function": "isGranted",
      "class": "ApiPlatform\Symfony\Security\ResourceAccessChecker",
      "type": "->"
    },
    {
      "file": "/app/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",
      "line": 430,
      "function": "canAccessAttribute",
      "class": "ApiPlatform\Serializer\AbstractItemNormalizer",
      "type": "->"
    },

It seems there is some error with Item normalization. Do I need to make some custom serializer or annotation to allow symfony to access the methods?

Getting Axios Netwrok Error using phpMyAdmin

I’m practicing trying to insert data into a phpmyadmin mysql database using React.
I’m using Axios for posting.
When i try to post data from my formto the database table i get axios network. Tried searching the net for solution but cannot seem to understand where i’m gone wrong.
This is my coding; any guidance will be appreciated on where what needs to be amended:

    import { useState } from "react";
import axios from "axios";
import {useNavigate} from "react-router-dom";
const cors = require('cors');


function AddStudent(){

   // app.use(cors());

    let history = useNavigate();
    const [student, setStudent] = useState({
        first_name:"",
        last_name:"",
        email:""
    })
    const {first_name, last_name, email} = student;

    const handleChange = (e)=>{
setStudent({...student,[e.target.name]: e.target.value})
    }

    const submitForm = async (e) =>{
        e.preventDefault();

        console.log(student)

        await axios.post("http://localhost/renting_website/insert.php", student)
        .then((result) =>{
console.log(result);
if(result.data.status === 'valid'){
    history('/ListStudent')
}
else{
    alert('There is a problem in adding; please check everything')
}
        })
    }
    return(
        <form onSubmit = {e => submitForm(e)}>

        <div className="box_size">
        <div className="row">
            <div className="col-md-12 text-center">
                <h1>Add Student</h1>
            </div>
         </div>

            <div className="row">

            <div className="col-md-6">First Name</div>
            <div className="col-md-6">
                <input type='text' name='first_name' className="form-control" 
                value ={first_name} onChange={e => handleChange(e)}/>
            </div>
            </div>

            <div className="row">
            <div className="col-md-6">Last Name</div>
            <div className="col-md-6">
                <input type='text' name='last_name' className="form-control" 
                 value ={last_name} onChange={e => handleChange(e)}/>
            </div>
            </div>


<div className="row">
            <div className="col-md-6">Email</div>
            <div className="col-md-6">
                <input type='email' name='email' className="form-control" 
                 value ={email} onChange={e => handleChange(e)}/>
            </div>
</div>

     <div className="row">
     <div className="col-md-12">
                <input type='submit' name='submit' className="btn btn-warning"  value="Add_Student"/>
            </div>
         </div>  

         </div>       
       
 </form>     
    )
}

export default AddStudent;

insert.php

    <?php>
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Origin: http://localhost:3000/");

header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type,
Access-Control-Allow-Headers, Authorization, X-Requsted-With");

include('db-connect.php');

$data = json_decode(file_get_content("php://input"))

$first_name = $data->first_name;
$last_name = $data->last_name;
$email = $data->email;

if($first_name && $last_name && $email){
    $sql = "insert into registration(
        first_name,
        last_name,
        email
        )
    values(
        '$first_name',
        '$last_name',
        '$email'

        )";

        $result = mysqli_connect($con, $sql);
    
        if($result){
            'status' =>'valid'
        );
        echo json_encode($reponse)
        }
        else{
            $reponse=array(
                'status' => 'invalid'
            );
            echo json_encode($reponse)
        }
}
<?>

and the connection.php:

    <?php

$serverName = "localhost";
$userName = "root";
$password = "";
$dbName = "renting";

$con = mysqli_connect($serverName, $userName, $password, $dbName);

?>

enter image description here

Php-mqtt no received message

please help me, why I don’t receive a message after publish, all login, submit details are correct. I send the data, but I do not receive the return message..

try {
        // Create a new instance of an MQTT client and configure it to use the shared broker host and port.
        $client = new MqttClient($host, 1883, $clientID, MqttClient::MQTT_3_1, null);
    
        // Create and configure the connection settings as required.
        $connectionSettings = (new ConnectionSettings)
                ->setUsername($username)
                ->setPassword($password);
    
        // Connect to the broker with the configured connection settings and with a clean session.
        $client->connect($connectionSettings, true);
    
        $handler = function (MqttClient $client, $topic, $message, $messageId, int $qualityOfService, bool $retain) use ($logger) {
           
            
            //Missing received msg
        };
        $client->registerPublishEventHandler($handler);
    
    
        // Publish the message 'Hello world!' on the topic 'foo/bar/baz' using QoS 0.
        $client->publish($topic, $msg, MqttClient::QOS_AT_MOST_ONCE);
    
    
    
        // Gracefully terminate the connection to the broker.
        $client->disconnect();
    } catch (MqttClientException $e) {
        // MqttClientException is the base exception of all exceptions in the library. Catching it will catch all MQTT related exceptions.
        echo "no connected";
    }

How to add fields and change required fields in moodle signup form?

I have a moodle project as a developer and i want to change the sign up form to make it simpler.Bascially, i want to remove the username field and replace it with a full name field and add a phone number field that is not mandatory (required) and remove all the other unnecessary fields or at least set them as not required
sign up form current

I have hid some of the unnecessary features using CSS but i want something more functional, and want to know what files i need to change to make the changes in the backend so that it works as expected when a user signs up.
Any help/advice with this would be greatly appreciated!

How to fix the HTTP error 405 when trying to run connect.php using vs code?

I’m trying to create a registration form that stores all the new data entered by users into a database using xampp phpmyadmin but every time I try to submit the form by clicking on the register button, it returns this error: “This page isn’t working. If the problem continues contact the site owner. HTTP error 405“. I’m on a mac btw.

This is my HTML code:

<!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>Sign Up - Bloom of Psyche</title>
  <link rel="stylesheet" type="text/css" href="register-form.css">

</head>
<body>
  <section>
    <div class="formbox">
      <div class="form-value">
        <form method="post" action="connect.php">
          <h2>SIGN UP</h2>
          <div class="inputbox">
            <input type="text" id="first_name" name="firstName" required>
            <label for="">First Name</label>
          </div>
          <div class="inputbox">
            <input type="text" id="last_name" name="lastName" required>
            <label for="">Last Name</label>
          </div>
          <div class="inputbox">
            <input type="email" id="email_address" name="email" required>
            <label for="">Email</label>
          </div>
          <div class="inputbox">
            <input type="password" id="user_password" name="password" required>
            <label for="">Password</label>
          </div>
          <button>Register</button>
          <div class="login">
            <p>Already have an account? <a href="login-form.html">Log in</a></p>
          </div>
        </form>
      </div>
    </div>
  </section>
  <script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script>
</body>
</html>

and this is my PHP code:

<?php
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    $conn = new mysqli('localhost', 'root', '', 'bloomofpsyche_database');
    if($conn->connect_error){
        die('Connection Failed : '.$conn->connect_error);
    }else{
        $stmt = $conn->prepare("insert into registration(firstName, lastName, email, password) values(?, ?, ?, ?)");
        $stmt->bind_param("ssss", $firstName, $lastName, $email, $password);
        $stmt->execute();
        echo "You have successfully registered!";
        $stmt->close();
        $conn->close();
    }
?>

Variable $_FILES don’t returns value when posting a form from PHP

I am trying to send file info from a PHP form, but it doesn’t appears.

I have a file with this form:

<form action="procesos/procesar_entradas.php" method="post" class="form-horizontal" id="entradasForm" enctype="multipart/form-data">
[...]
<input type="file" accept=".png, .jpeg, .jpg, .gif" name="foto_muestra" id="foto_muestra" class="form-control" />
<input type="file" accept=".png, .jpeg, .jpg, .gif" name="foto_monton" id="foto_monton" class="form-control" />
[...]
<button type="submit" class="btn btn-default">Registrar entrada</button>
</form>

I am uploading two images. When I click submit, I go the action file marked. It reaches here correctly.
But when I try to know about $_FILES, this is empty, but I am using these images. Why does returns it empty?

How can I indicate to the form that I want to get these files this way?:

$_FILES['foto_muestra']
$_FILES['foto_monton']

Thanks in advance, cause it comes empty and I don’t know what to do.

To get $_FILES not empty, with image data sent from form. Multipart is ON.

custom function from a bedrock wp theme, into a standart wp project

i have a custom function (from old bedrock theme) of creating 2 new menus in wp-admin (daily news and monthly news), the posts that are in those menus are collected from a remote server via API token, the posts themselfs exist, they are scheduled. I can open any of them and see the title and date, the thing is that there is no content or images. (on the new theme)

i have tried to install the old theme from bedrock in which was this custom function, it did work perfectly, but i cannot use the old theme, so i don’t know what to do.

Getting 403 error when implementing private channels in Laravel Pusher multi-room chat app

I’m developing a multi-room chat application using Laravel and Pusher. I’m trying to implement private channels for each room, but I’m encountering a 403 error with the message “POST http://127.0.0.1:8000/broadcasting/auth”. I suspect the issue might be related to the custom middleware I’m using.

Here’s my setup:

web.php:

Auth::routes();

Route::get('/', [AppHttpControllersHomeController::class, 'welcome'])->name('welcome');

Route::group(['middleware' => WelcomeMiddleware::class], function () {
  Route::post('/create', [AppHttpControllersHomeController::class, 'create'])->name('create');
  Route::get('/home', [AppHttpControllersHomeController::class, 'home'])->name('home');
  Route::get('/select', [AppHttpControllersHomeController::class, 'select'])->name('select');
  Route::post('/sendMessage', [MessagesController::class, 'index']);
  Route::get('/room/{id}', [AppHttpControllersHomeController::class, 'room'])->name('room');
});

WelcomeMiddleware.php:

class WelcomeMiddleWare
{
  /**
   * Handle an incoming request.
   *
   * @param  Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse)  $next
   */
  public function handle(Request $request, Closure $next): Response
  {
    if (!$request->hasCookie('chat_session')) {
      return redirect()->route('welcome');
    }
    return $next($request);
  }
}

MessagesController.php

public function index(Request $request)
  {
    $name_id = session()->get("name_id");
    $name = session()->get("name");
    $room_id = Name::where('id', $name_id)->first()->room_id;
    logger("index ", ['channel' => $room_id]);
    event(new Chat(
      $name,
      $request->input('message'),
      $room_id,
    ));

    return true;
  }

Events/Chat.php

public function __construct($username, $message, $room_id)
  {
    $this->username = $username;
    $this->message = $message;
    $this->room_id = $room_id;
  }

  /**
   * Get the channels the event should broadcast on.
   *
   * @return array<int, IlluminateBroadcastingChannel>
   */
  public function broadcastOn(): array
  {
    return [
      // new PrivateChannel('room' . $this->room_id),
      new PrivateChannel('room'),
    ];
  }

I tried the following setup I found online, but I still get a 403 error:

channels.php

Broadcast::routes(['middleware' => WelcomeMiddleware::class], function () {
  Broadcast::channel('room', function () {
    return true;
  });
});

BroadcastServiceProvider.php

public function boot(): void
  {
    Broadcast::routes(['middleware' => WelcomeMiddleware::class]);
    require base_path('routes/channels.php');
  }

I’m super noob of Laravel and Pusher and I’m not sure how breadcasting works.

Any help on resolving this issue would be greatly appreciated. Thank you!

Simplesamlphp | Invalid Destination URL Error

I’m trying to setup simplesamlphp in my localhost and I installed the latest 2.1.1 version and done few basic configuration in config.php. Then I tried to hit the url getting this below error.

SimpleSAMLErrorError: UNHANDLEDEXCEPTION
Backtrace:
1 src/SimpleSAML/Error/ExceptionHandler.php:32
(SimpleSAMLErrorExceptionHandler::customExceptionHandler)
0 [builtin] (N/A)
Caused by: SimpleSAMLErrorException: Invalid destination URL:
http://myloc_sp_drupalsaml.com/simplesaml/module.php/core/welcome
Backtrace:
2 src/SimpleSAML/Utils/HTTP.php:221 (SimpleSAMLUtilsHTTP::redirect)
1 src/SimpleSAML/Utils/HTTP.php:955 (SimpleSAMLUtilsHTTP::redirectTrustedURL)
0 public/index.php:16 (N/A)

Note: Machine linux AWS and trying to setup it for my Drupal 10 application

enter image description here

Any help please.

magento demo api 403

   $url = 'https://magento2-demo.magebit.com/rest/V1/integration/admin/token';

    $data = [
        'username' => 'magebit',
        'password' => 'Demo123'
    ];

    $response = Http::post($url, $data);

    if ($response->successful()) {
        $token = $response->body();

        return $token;
    } else {
        return $response->status();
    }

while calling this api using demo credentials it’s showing 403 error why?

I try to get access token for magento api form magento demo. But it’s showing an error 403. Is it possible to access token from magento demo?

How to pass a token to a protected route (a method in class) in Laravel

I am writing phpunit tests in Laravel.

I log in successfully into the application using the folloiwng code:

$response = $this->json('POST', 'login', 
      [
        'user_name'  =>  $username,
        'password'  =>  $password ,
     ]);

 $response->assertStatus(200); // This is ok and passes the test -- is green

I get the following results when I dd $response:

+original: array:5 [
  "status" => 200
  "data" => array:4 [
    "token_type" => "Bearer"
    "expires_in" => 7200
    "access_token" =>     "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOi...snipped"
    "refresh_token" => "def50200eb65ae708701e58c732140ea2efca0083...snipped"

When I invoke a protected method called doSomething as follows

$token = "Bearer and I hardcode the access token above"

$response = $this->json('POST', 'doSomething', [
        'token' => $token
     ]);
     
     dd($response);

I get the following message:

 "{"status":401,"message":"Unauthenticated.Token invalid or expired. Please login or refresh token to   proceed"}"

Question:

  1. How can I pass the valid token I received from the successful login to the doSomething method and all the other routes I want to test?