Please how I fetch user account balance, withdrawals, Loans and Transactions to display in the dashboard?

$user = Auth::user();

    $account = $user->account;
    $loans = $user->loans;
    $transactions = $user->transactions;

    return view('User.dashboard', compact('user', 'account', 'loans', 'transactions'));

My controller code:

My view code:
@isset($loans)

                                @foreach($loans as $loan)
                                <div class="widget__status-title text-grey">Transactions</div>
                                <div class="widget__spacer"></div>
                                <div class="widget__trade"><span class="widget__trade-count">{{$loan->amount}}</span>
                                </div>
                                @endforeach
                                @endisset

Please I need it to display pending loans, successful transactions in the dashboard

Deploy Flutter and Laravel php mobile app on the host server

currently I doing a mobile app using flutter as frontend and laravel php as backend, usually i need to serve and open xampp to use the local api and database, so what if I dont want locally anymore, buy a server right? any server suggestion for this kind of situation and how to configure that, this is my first time make the app online.

I try the linode host server and the url could access through browser and shows apache web page but I try to replace my local ipv4 address with server ip to call api online but it always say url not working

Bootstrap component does not want to render in Datatables function

var dt_filter = dt_filter_table.DataTable({
            ajax: {
                url: '/banner/data',
                error: function (xhr, error, thrown) {
                    console.error('DataTables AJAX error:', error);
                    console.log('XHR response:', xhr.responseText);
                }
            },
            // columns: [
            //     { data: 'title' },
            //     { data: 'doctor_id' },
            //     { data: 'create_date' },
            //     { data: 'updated_at' },
            //     { data: 'actions' }
            // ],
            aoColumns: [
                { "data": "title" },
                { "data": "created_at" },
                { "data": 'updated_at' },
                {
                    "mData": "id",
                    "mRender": function (data, type, row) {
                        if (data) {
                            return '<div class="col-sm-6 p-4"><input type="checkbox" class="switch-input" /><span class="switch-toggle-slider"><span class="switch-on" ></span><span class="switch-off"></span></span></div>'
                        }

                    }
                },
                {
                    "mData": "id",
                    "mRender": function (data, type, row) {
                        return "<div class='d-flex justify-content-center'><a class='btn btn-primary me-2' href='banner/detail/" + data + "'>Edit</a><a class='btn btn-danger mr-2 text-white' onclick='deleteConfirm(" + data + ")'>Delete</a></div>";
                    }
                }
            ],
            orderCellsTop: true,
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6 d-flex justify-content-center justify-content-md-end"f>><"table-responsive"t><"row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>'
        });

i have this code for rendering datatable with laravel php. i have a problems when i want to render switch component in second last object in aoColumn property. it always says that the checkbox is always null, my current assu,ption is there is a problem between datatable and bootstrap.
how do i solve this problem?

Remove Product SKU from order details in WooCommerce email notifications

I’ve been trying to remove the product SKU located after the product title in WooCommerce email notifications.

I have tried the following:

function sv_remove_product_page_skus( $enabled ) {
    if ( ! is_admin() && is_product() ) {
        return false;
    }

    return $enabled;
}
add_filter( 'wc_product_sku_enabled', 'sv_remove_product_page_skus' );

But didn’t work, the product SKU remains after the product title.

Only store keys with specific values from json data in php [duplicate]

[{
“service”: “abc”,
“capability”: “s”
},
{
“service”: “def”,
“capability”: “s”
},
{
“service”: “abc”,
“capability”: “v”
},
{
“service”: “def”,
“capability”: “v”
}
]

The api data is returned with capability key and I want that only the data where capability is equal to s should be stored. Whats the best way to do this?
Also I need to show this on the table in html page is it better to do this in php or javascript?

$array = array();
    foreach($jsonarray as $key=>$item) {
    if($key=>$item == "s"){
    $array = array(
    "service" => "",
    "capability" => "",
);
}

If the value of capability = s then only store the data ignore the one with the value v.

With array filter it returns empty array r

$r=array_filter($json_array_list, function($capability, $value) {
      return $capability == "sms";
    }, ARRAY_FILTER_USE_BOTH);
    print_r($r);

On every try I am getting last fetched ID , help me fix it please

This is the code on the one side

<tbody>
                                <? 
                      $select_main = $conn->query("SELECT * FROM channels WHERE parent_id=$package_id ORDER BY id ASC");
                      while($row_main = $select_main->fetch_object()){
                      ?>
                                <tr>
                                    <td><input type="text" name="this_id" value="<? echo $row_main->id; ?>" class="form-control"></td>
                                    <td><? echo $row_main->name; ?></td>
                                    <td><? echo $row_main->type; ?></td>
                                    <td><img src="../logos/<? echo $row_main->logo;?>" style="width: 30px;"></td>
                                    <td><button class="btn btn-danger btn-block" name="delete_vacancy">არხის წაშლა</button></td>
                                    <td><input type="file" name="image"> </td>
                                    <td><button class="btn btn-success btn-block" name="update_logo">ლოგოს განახლება</button></td>
                                </tr>
                                <? } ?>
                            </tbody>

if(isset($_POST["update_logo"])){
    $channel_id = $_POST['this_id'];
$sql = "UPDATE channels SET logo='3333' WHERE id=$channel_id";
         mysqli_query($conn,$sql);

every time it brings up the last id from that fetch, can you help me resolve it?

Issue with [proxy_fcgi:error] [pid 1539011] (70007)The timeout specified has expired

I need assistance on debugging my apache2 + php8.2-fpm.

based on apache2 error log,

there is a lot of error

[proxy_fcgi:error] [pid 1539011] (70007)The timeout specified has expired: [client xx.xx.xx.xx:58990] AH01075: Error dispatching request to : (polling), referer: https://xx.xx.xx/

My current settings for

i am using mpm_worker + apache2 + php8.2-fpm

[php8.2-fpm pool settings]

pm = dynamic
pm.max_children = 133
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500
php_admin_value[memory_limit] = 128M
request_terminate_timeout = 600s

[mpm_worker settings]

[mpm_prefork]
StartServers         5
MinSpareServers      5
MaxSpareServers      10
MaxRequestWorkers    133
MaxConnectionsPerChild 1000

[apache settings]

Timeout 600
ProxyTimeout 600
MaxKeepAliveRequests 100
KeepAliveTimeout 5

[php.ini settings]

max_execution_time = 600

Appreciate if anyone can help to give an idea where to look for in to find the problem.
thanks in advance

Laravel ->with method working local but not on production

I have a function in my controller that sends out a message with the ‘with’ method. It works perfect on my local env but not in the production.

Here is the function i use in my controller:

return redirect()->back()->with('successMsg',trans('users.badges_reset'));

And this is the function i use in my view

@if(Session::has('successMsg'))
    <div class="alert alert-success" role="alert">
    <i class="fas fa-check"></i> {{Session::get('successMsg')}}
    </div>
@endif

The view component is loaded in my other templates via include.

I debugged the session but it doesn’t show up

Slim routing in PHP-DI container

I’m moving a project of mine into Slim Microframework, by using PHP-DI containerization.
I need to POST some JSON data to http://localhost/api/base (XAMPP) and get a confirmation (at least at the beginning).
This is my index.php:

<?php

use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use SlimFactoryAppFactory;
use SlimExceptionHttpMethodNotAllowedException;
use SlimExceptionHttpNotFoundException;
use SlimRoutingRouteContext;
use DIContainerBuilder;

// Set error reporting to display all errors
error_reporting(E_ALL);
ini_set('display_errors', 'On');

// Autoloading using Composer's autoload
require __DIR__ . '/../vendor/autoload.php';

// Include dependencies file
$container = require_once __DIR__ . '/../config/dependencies.php';

// Create Slim app
$app = AppFactory::create();

// Include routes
require __DIR__ . '/../src/routes.php';

$app->run();

This is routes.php:

<?php

use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use AppControllersHotelBaseController;

// Include dependencies file
$container = require_once __DIR__ . '/../config/dependencies.php';

// Define basic route
$app->get('/', function (Request $request, Response $response) {
    $response->getBody()->write('Hello, World!');
    return $response;
});


// Route for handling POST request to /api/base
$app->post('/api/base', function (Request $request, Response $response) use ($container) {
    // Get the HotelBaseController service from the container
    $hotelBaseController = $container->get('HotelBaseController');

    // Call the handlePostRequest method
    return $hotelBaseController->handlePostRequest($request, $response);
});


$app->get('/api/base/', function (Request $request, Response $response) {
    return $response->withStatus(301)->withHeader('Location', '/api/base');
});

This is the dependencies.php:

<?php

use DIContainerBuilder;
// use PsrHttpMessageResponseInterface as Response;
// use PsrHttpMessageServerRequestInterface as Request;

require __DIR__ . '/../vendor/autoload.php';

// Create ContainerBuilder instance
$containerBuilder = new ContainerBuilder();

// Set up your container configuration
$containerBuilder->addDefinitions([
    'HotelBaseController' => DIcreate(AppControllersHotelBaseController::class),
]);

// Build the container
return $containerBuilder->build();

And, finally, this is hotelBaseController.php:

<?php

namespace AppControllers;

use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;

class HotelBaseController {
    public function handlePostRequest(Request $request, Response $response) {
        // Get the JSON data from the request body
        $data = $request->getParsedBody();

        // You can access the individual fields from the JSON data
        $userId = $data['userId'] ?? '';
        $apiKey = $data['apiKey'] ?? '';
        $documentType = $data['document_type'] ?? '';
        $hotelId = $data['hotel_id'] ?? '';
        $hotelName = $data['name'] ?? '';

        $res = 'Who knows';
        
        return $res;
    }
}

?>

When sending any POST request, containing a simple JSON, I get the error:

<b>Fatal error</b>: Uncaught Error: Call to a member function get() on bool in C:xampphtdocssrcroutes.php:20
Stack trace:
#0 C:xampphtdocsvendorslimslimSlimHandlersStrategiesRequestResponse.php(38):
{closure}(Object(SlimHttpServerRequest), Object(SlimHttpResponse), Array)
#1 C:xampphtdocsvendorslimslimSlimRoutingRoute.php(358):
SlimHandlersStrategiesRequestResponse-&gt;__invoke(Object(Closure), Object(SlimHttpServerRequest),
Object(SlimHttpResponse), Array)
#2 C:xampphtdocsvendorslimslimSlimMiddlewareDispatcher.php(65):
SlimRoutingRoute-&gt;handle(Object(SlimHttpServerRequest))
#3 C:xampphtdocsvendorslimslimSlimMiddlewareDispatcher.php(65):
SlimMiddlewareDispatcher-&gt;handle(Object(SlimHttpServerRequest))
#4 C:xampphtdocsvendorslimslimSlimRoutingRoute.php(315):
SlimMiddlewareDispatcher-&gt;handle(Object(SlimHttpServerRequest))
#5 C:xampphtdocsvendorslimslimSlimRoutingRouteRunner.php(68):
SlimRoutingRoute-&gt;run(Object(SlimHttpServerRequest))
#6 C:xampphtdocsvendorslimslimSlimMiddlewareDispatcher.php(65):
SlimRoutingRouteRunner-&gt;handle(Object(SlimHttpServerRequest))
#7 C:xampphtdocsvendorslimslimSlimApp.php(199):
SlimMiddlewareDispatcher-&gt;handle(Object(SlimHttpServerRequest))
#8 C:xampphtdocsvendorslimslimSlimApp.php(183): SlimApp-&gt;handle(Object(SlimHttpServerRequest))
#9 C:xampphtdocspublicindex.php(50): SlimApp-&gt;run()
#10 {main}
thrown in <b>C:xampphtdocssrcroutes.php</b> on line <b>20</b><br />

I would like to understand where am I making a mistake.
Thanks

WordPress server side datatable filtering

I am currently working on a database dat needs to filter a 1.000.000 Products. For this I created 2 wordpress websites. 1 to show the data and 1 for storing the data.

Now I am first building the script in a plugin and displaying it on the data website. But now I keep struggeling with the filtering and I am questioning my current approach to handle over 1.000.000 products. (The products only need to be displayed with a form so it more like a catalog and not really a store.)

So the main question is. Is this the correct approach and is datatables.net a right way of doing this. The second question is how can I fix this filtering problem.

When the filtering is empty and noting is selected in the table I get 0 results so the

<?php
    // Exit if accessed directly.
    defined( 'ABSPATH' ) || exit;

    //encrypt('encrypt', $users[$x][1], $usertokens[$x][2], 'test')
    //decrypt('decrypt', $results[$i]->emergencyemailaddress, $results[$i]->token, 'test');
// Add Post title to custom meta 
add_action( 'transition_post_status', 'duplicate_title', 10, 3 ); 

function duplicate_title( $new, $old, $post ) { 
  if ( $post->post_type == 'autos' ) { 
    update_post_meta( $post->ID, 'd_title', $post->post_title ); 
  } 
}
// Add DataTables Resources
 
function add_datatables_scripts() {
  wp_register_script('datatables', 'https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js', array('jquery'), true);
  wp_enqueue_script('datatables');

  wp_register_script('datatables_bootstrap', 'https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js', array('jquery'), true);
  wp_enqueue_script('datatables_bootstrap');
}
 
function add_datatables_style() {
  wp_register_style('bootstrap_style', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
  wp_enqueue_style('bootstrap_style');

  wp_register_style('datatables_style', 'https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css');
  wp_enqueue_style('datatables_style');
}
 
add_action('wp_enqueue_scripts', 'add_datatables_scripts');
add_action('wp_enqueue_scripts', 'add_datatables_style');

function autos_datatables_scripts() {
  wp_enqueue_script( 'autos_datatables', '/js/autostable.js?ver=1.0', array('jquery'),  true );
  wp_localize_script( 'autos_datatables', 'ajax_url', admin_url('admin-ajax.php?action=autos_datatables') );
}


// Add a function to retrieve available Merk options
function get_merk_options() {
    $terms = get_terms(array(
        'taxonomy' => 'car_merk',
        'hide_empty' => true, // Include even terms with no posts
    ));

    $options = array();
    foreach ($terms as $term) {
        $options[] = $term->name;
    }

    return $options;
}

// Modify your shortcode or HTML to generate checkboxes dynamically
function generate_merk_checkboxes() {
    $merk_options = get_merk_options();

    $dropdown_html = '<div>';
    $dropdown_html .= '<label for="filter-merk">Selecteer merk:</label>';
    $dropdown_html .= '<select id="filter-merk" class="filter-merk">';
    $dropdown_html .= '<option value="">Selecteer merk</option>';

    foreach ($merk_options as $option) {
        $dropdown_html .= '<option value="' . $option . '">' . $option . '</option>';
    }

    $dropdown_html .= '</select>';
    $dropdown_html .= '</div>';

    return $dropdown_html;
}

// Update your autos_datatables function to include the generated checkboxes
function autos_datatables() {
    autos_datatables_scripts(); 

    ob_start(); ?> 
    
    <div>
        <?php echo generate_merk_checkboxes(); ?>
    </div>

    <table id="autostable" class="table table-striped table-hover"> 
        <thead> 
            <tr> 
                <th>Auto title</th>
                <th>brandstof</th>
                <th>Merk</th>
                <th>bouwjaar</th>
                <th>afbeelding</th>
            </tr> 
        </thead> 
    </table> 

    <?php return ob_get_clean(); 
}

add_shortcode ('autos_datatables', 'autos_datatables');

add_action('wp_ajax_autos_datatables', 'datatables_server_side_callback');
add_action('wp_ajax_nopriv_autos_datatables', 'datatables_server_side_callback');


function datatables_server_side_callback() {
    header("Content-Type: application/json");

    $request = $_GET;

    $columns = array(
        0 => 'post_title',
        1 => 'car_brandstof',
        2 => 'car_merk', // Assuming 'Merk' is the third column
        3 => 'car_bouwjaar',
        4 => 'image_0',
    );

    $args = array(
        'post_type' => 'cars',
        'post_status' => 'publish',
        'posts_per_page' => $request['length'],
        'offset' => $request['start'],
        'order' => $request['order'][0]['dir'],
    );

    if ($request['order'][0]['column'] == 0) {
        $args['orderby'] = $columns[$request['order'][0]['column']];
    } elseif ($request['order'][0]['column'] == 1 || $request['order'][0]['column'] == 2) {
        $args['orderby'] = 'meta_value_num';
        $args['meta_key'] = $columns[$request['order'][0]['column']];
    }

// Update the query to handle the merk_filter parameter
if (!empty($request['merk_filter'])) {
    $merk_terms = array_map('sanitize_text_field', $request['merk_filter']);
    $args['tax_query'][] = array(
        'taxonomy' => 'car_merk',
        'field' => 'name',
        'terms' => $merk_terms,
        'operator' => 'IN',
    );
}

// Add condition to include all posts when merk_filter is empty
if (empty($request['merk_filter'])) {
    $args['tax_query'][] = array(
        'taxonomy' => 'car_merk',
        'operator' => 'EXISTS', // Include all posts
    );
}
    // Other meta queries and search query

    $autos_query = new WP_Query($args);
    $totalData = $autos_query->found_posts;
    $data = array();

    if ($autos_query->have_posts()) {
        while ($autos_query->have_posts()) {
            $autos_query->the_post();

            // Your code to populate $data with results
            $nestedData = array();
            $nestedData[] = get_the_title();
            $terms = get_the_terms(get_the_ID(), 'car_brandstof');

            // Brandstof
            if ($terms && !is_wp_error($terms)) {
                $brandstof = array();
                foreach ($terms as $term) {
                    $brandstof[] = $term->name;
                }
                $nestedData[] = implode(', ', $brandstof);
            } else {
                $nestedData[] = '';
            }

            // Get the terms for the 'car_merk' taxonomy
            $merk_terms = get_the_terms(get_the_ID(), 'car_merk');

            if ($merk_terms && !is_wp_error($merk_terms)) {
                $merk = array();
                foreach ($merk_terms as $term) {
                    $merk[] = $term->name;
                }
                $nestedData[] = implode(', ', $merk);
            } else {
                $nestedData[] = 'geen merk';
            }

            // Get the terms for the 'car_merk' taxonomy
            $merk_terms = get_the_terms(get_the_ID(), 'car_bouwjaar');

            if ($merk_terms && !is_wp_error($merk_terms)) {
                $merk = array();
                foreach ($merk_terms as $term) {
                    $merk[] = $term->name;
                }
                $nestedData[] = implode(', ', $merk);
            } else {
                $nestedData[] = '';
            }

            // Get the URL of the first image and decode it from base64
            $image_base64 = get_post_meta(get_the_ID(), 'image_0', true);
            $image_url = 'data:image/jpeg;base64,' . $image_base64;
        
            // Wrap the image URL with an <img> tag
            $image_tag = '<img width="50px" src="' . $image_url . '" alt="' . get_the_title() . '">';
        
            // Add the image tag to the nested data
            $nestedData[] = $image_tag;


            // Add the nested data to the main data array
            $data[] = $nestedData;
        }
        wp_reset_postdata();
        wp_reset_query();
    }

    $json_data = array(
        "draw" => intval($request['draw']),
        "recordsTotal" => intval($totalData),
        "recordsFiltered" => intval($totalData),
        "data" => $data,
    );

    echo json_encode($json_data);
    wp_die();
}
    
?>

Javascript:

$ = jQuery;
$(document).ready(function() {
    // DataTables initialization
    var table = $('#autostable').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": ajax_url,
            "data": function(d) {
                // Get an array of checked Merk values
                var checkedMerks = $('.filter-merk').map(function() {
                    return $(this).val();
                }).get();
                
                // If no selection is made, pass an empty array to the server
                if (checkedMerks.length === 0) {
                    checkedMerks = [''];
                }

                // Add the merk_filter parameter to the data object
                d.merk_filter = checkedMerks;

                return d;
            }
        }
    });

    // Checkbox change event handler
    $(document).on('change', '.filter-merk', function() {
        // Reload DataTables with new filter criteria
        table.ajax.reload();
    });
});

Elementor Form Submission to External API Issue

We have developed a plugin that hooks the Elementor Pro form submission to capture the form data and send it to an external API endpoint. However, we are facing some issues with this integration. The API we have integrated with works well with the Contact Form 7 plugin hook, where it returns an error and stores data in the MySQL server. But, in Elementor, the request is sent successfully and a custom response is received from the API. However, there are no validation errors and the data is not saved in the database, which seems weird.

Here’s the Elementor Pro Form Plugin Hook Code

<?php
 /*
Plugin Name: Elementor Pro Forms API
Description: Custom hook for Elementor Pro forms submission.
Version: 1.5
Author: Haris Khan
*/

// A send custom WebHook
add_action('elementor_pro/forms/new_record', function ($record, $handler) {
    // Make sure it's our form
    $form_name = $record->get_form_settings('form_name');

    // Replace 'Contact_Form' with the name you gave your form
    if ('Contact_Form' !== $form_name) {
        return;
    }

    // Extract form fields
    $raw_fields = $record->get('fields');
    $fields = [];
    foreach ($raw_fields as $id => $field) {
        $fields[$id] = $field['value'];
    }

    // Get user IP address
    $user_info = array();
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $user_info['ip'] = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $user_info['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $user_info['ip'] = $_SERVER['REMOTE_ADDR'];
    }

    // Get user agent
    $user_info['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
    $fields['ipaddress'] = $user_info['ip'];

    // Add source field
    $siteName = get_permalink();
    $fields['source'] = $siteName;

    // Make API request
    $response = wp_remote_post('https://myapi.com/elementor-form', [
        'body' => $fields,
    ]);
    
    if (is_wp_error($response)) {
        // Handle API request error
        $msg = 'There was a problem with the additional webhook.';
        $handler->add_error(0, $msg);
        $handler->add_error_message($msg);
        $handler->is_success = false;
    }

    // Check for errors in the API response
    $api_response = json_decode(wp_remote_retrieve_body($response), true);

    if (isset($api_response['status']) && $api_response['status'] === 'error' && isset($api_response['errors'])) {
        // Add errors to the form submission
        foreach ($api_response['errors'] as $field => $error_message) {
            $handler->add_error($field, $error_message);
        }
        $handler->is_success = false;
    }
}, 10, 2);

also provided the API End Point Code in php

public function elementorForm(){
        try {

            //Rate Limiter 
            // $key = 'user_'. 123;

            // // Set maximum number of requests and time interval (in seconds)
            // $maxRequests = 2;
            // $interval = 60; // 1 minute

            // // Check if the user has exceeded the rate limit
            // if (!$this->rateLimiter->limitRequests($key, $maxRequests, $interval)) {
            //     // Handle the rate limit exceeded error (e.g., show an error message)

            //     $response = [
            //         'status' => 'error',
            //         'message' => 'Throttle exceeded. Please try again later.',
            //     ];
                
            //     return $this->response->setStatusCode(200)->setJSON($response);
            // }

            // Get the input data from the request
            $inputData = $this->request->getPost(); // true: convert to associative array

            // Define validation rules
            $validationRules = [
                'name' => 'required|min_length[3]|max_length[25]|regex_match[/^[a-zA-Z]{3,}(?:s[a-zA-Z]*)?$/]',
                'phone' => 'required|is_unique[tblLead.appPhone]|regex_match[/^[5-9][0-9]{9}$/]|exact_length[10]',
                'channel' => 'required',
                'source' => 'required',
                // 'ipaddress'  => 'required'
            ];

            if (!empty($inputData["email"])) {
                $validationRules['email'] = 'required|valid_email|regex_match[/^[^@&%!#$^?*-_.]{3}[^@&%!#$^?]*(?:.[^@&%!#$^?]+)?@[a-zA-Z]{5,10}+.[a-zA-Z]{2,3}$/]';
            }
        
            $customErrors = [
                'name' => [
                    'required' => 'The name field is required.',
                    'min_length' => 'The name must be at least 3 characters long.',
                    'max_length' => 'The name cannot exceed 25 characters.',
                    'regex_match' => 'Invalid format for the name field.',
                ],
                'phone' => [
                    'required' => 'The phone field is required.',
                    'regex_match' => 'Invalid format for the phone field.',
                    'exact_length' => 'The phone number must be exactly 10 digits long.',
                    'is_unique' => 'The phone number is already registered, Please use a different one.',
                ],
                'channel' =>[
                    'required' => 'The channel field is required.',
                ],
                'source' =>[
                    'required' => 'The source field is required.',
                ],
                // 'ipaddress' =>[
                //     'required' => 'The IP Address field is required.',
                // ]

            ];

            if (!empty($inputData["email"])) {
                $customErrors["email"] = [
                    'required' => 'The email field is required.',
                    'valid_email' => 'Please provide a valid email address.',
                    'regex_match' => 'Invalid format for the email field.',
                ];
            } 

            // Run the validation
            $validation = ConfigServices::validation();
            $validation->setRules($validationRules, $customErrors);

            if (!$validation->run($inputData)) {
                // Validation failed, return JSON response with custom errors
                $errors = $validation->getErrors();
                $response = [
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $errors,
                ];
                return $this->response->setStatusCode(400)->setJSON($response);
            }

            $userModel = new UserModel();
            // $result = $userModel->insert($inputData);
            $result = $userModel->insertUser($inputData);
        
            if($result != null){
                $response = [
                    "message"=>"Data Successfully Inserted",
                    "result"=>$result
                ];

                return $this->response->setStatusCode(200)->setJSON($response);
            }
    
        }catch (Exception $e) {
            $response = [
                "message"=>"Something went wrong.",
            ];
            return $this->response->setStatusCode(400)->setJSON($response);
        }   
    }

Our pro forms data is not being set in the MYSQL DB despite the API response suggesting otherwise.

PHP – Exporting database records directly into CSV file

I am trying to export a dataset of rows into a csv/txt file with a single query as explained here or here, by executing a Laravel PHP script on a WSL environment with no root user.

The issues I found are the same as mentioned in those posts, but I can’t get my mind into solving it.

When first executing a similar SQL query into MySQL like:

SELECT * INTO OUTFILE "/tmp/activities_export.csv" FIELDS TERMINATED BY "," LINES TERMINATED BY "n" FROM posts;

I receive

Error Code: 1. Can’t create/write to file ‘tmpposts.csv’ (Errcode: 2 – No such file or directory)

Whatever the directory is (I’ve tried with plenty of them) except for the MySQL default directory, which I won’t have access to once deployed.

The file exists and is empty, so I guess it’s the same permissions issue, so far I check:

  • show grants shows GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION
  • SHOW VARIABLES LIKE "secure_file_priv"; which returns null
  • GRANT FILE ON *.* TO 'root'@'localhost'; (As a test) and results are the same, no changes.
  • I tried executing the PHP script with root user, same results.

Any ideas what is missing or what steps are to be done?

How do i logout the user logged in using socialte if he logs in from another browser?

I have implemented socialite login using Google and LinkedIn. My requirements are that I need to have the user only be able to login from one device at a time, so in case the user logs in using another device the first logged in device will be logged out.

I have two types of users, ones that login using a normal sign up process and the ones that use Socialite login. If a user has used the same email on a normal sign up and he wants to login using google or linked-in his account will be the same.

I have two tables one for admins and one for users as well, and two different models.

If my user signs in using his username and password I managed to make it work using the following code:

In session.php

    'expire_on_close' => true,

In CustomDatabaseSessionHandler.php

<?php

namespace AppExtensions;

use IlluminateContractsAuthGuard;
use IlluminateContractsContainerBindingResolutionException;
use IlluminateSessionDatabaseSessionHandler;

class CustomDatabaseSessionHandler extends DatabaseSessionHandler
{

    /**
     * Add the user information to the session payload.
     *
     * @param array $payload
     * @return $this
     * @throws BindingResolutionException
     */
    protected function addUserInformation(&$payload): static
    {
        if ($this->container->bound(Guard::class)) {
            info(($this->user() ? get_class($this->user()) : null));
            $payload['userable_type'] = $this->user() ? get_class($this->user()) : null;
            $payload['userable_id'] = $this->userId();
        }

        return $this;
    }

    /**
     * Get the currently authenticated user's ID.
     *
     * @return mixed
     * @throws BindingResolutionException
     */
    protected function user(): mixed
    {
        return $this->container->make(Guard::class)->user();
    }
}

In AppServiceProvider

        Session::extend('custom-database', function ($app) {
            $table = $app['config']['session.table'];
            $lifetime = $app['config']['session.lifetime'];
            $connection = $app['db']->connection($app['config']['session.connection']);

            return new CustomDatabaseSessionHandler($connection, $table, $lifetime, $app);
        });

Changed the SESSION_DRIVER in .env to ‘custom-database’

Created a LoginListener with the following code:

<?php

namespace AppListeners;

use IlluminateSupportFacadesDB;

class LoginListener
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(object $event): void
    {
        $user = $event->user;
        DB::table('sessions')->where('userable_id', $user->id)->where('userable_type', get_class($user))->delete();
    }
}

I have added the following to services.php

    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('APP_URL') . '/oauth/google/callback',
    ],
    'linkedin-openid' => [
        'client_id' => env('LINKEDIN_CLIENT_ID'),
        'client_secret' => env('LINKEDIN_CLIENT_SECRET'),
        'redirect' => env('APP_URL') . '/oauth/linkedin_openid/callback',
    ],

My problem is whenever i close the browser it’s not logging out, and whenever i am logging in using another device it’s not logging out, this problem is happening only when using the socialite login.

Main tab doesn’t retain authenticated state after authenticating user in popup window using Laravel Socialite

I am working on a project with TALL Stack where I implemented OAuth2 using Laravel Socialite package. Initially, I made a simple link with the redirect uri. This approach works fine and the user gets authenticated with google seamlessly and gets redirected to the intended route. Currently I want to have the Google OAuth2 authentication page to open in a popup window and once the user is authenticated, the popup window closes then the main tab or window redirects the user to the intended route after authentication. The problem I am facing now is, the user gets authenticated within the popup window and the window closes after authentication. However, the main window does not retain the authenticated state of the user. As a result, the redirection doesn’t occur. Let me also mention that this only happens the first time the user gets authenticated. Once you authenticate the user subsequently, the redirection occurs within the popup window and the popup doesn’t close automatically. This indicates that the user actually get’s authenticated but only within the popup and not the main tab or window.

This is the link for redirecting to the OAuth2 page

<a href="javascript:void(0);" onclick="openOAuthPopup()" class="w-full py-3 md:py-5 rounded-2xl border-2 border-green-500 hover:border-2 hover:border-green-700 flex justify-center items-center">
  <img class="w-6 mx-3" src="{{ asset('images/google.png') }}" alt=""> Sign up with Google
</a>

In the JS, I open the pop up window for OAuth2 authentication then listen for an event from the popup window for a successful authentication and then redirect the user to the dashboard.

function openOAuthPopup() {
     var popup = window.open('/auth/redirect', 'popup', 'width=700, height=700');

     // Listen for messages from the popup
     window.addEventListener('message', function(event) {
     if (event.origin !== "{{ url('/') }}") // Replace with your domain
         return;

         if (event.data === 'authenticated') {
             window.location.href = '/dashboard';
         }
     }, false);
}

Below is the php method for handling the callback

public function callback(): View
    {
        $googleUser = Socialite::driver('google')->stateless()->user();
        //Handle user registration or login
        ...

        return view('livewire.auth.oauth_callback');
    }

Within the view livewire.auth.oauth_callback, I had simple script that sends a message to the opener window and then closes the popup window.

// When the popup loads this view, send a message to the opener window
window.onload = function() {
      window.opener.postMessage("authenticated", "{{ url('/') }");
      window.close(); // Close the popup window
}

I don’t know if this has got anything to do with session. My config/session.php has everything in default.

What I’m I doing wrongly? Also, is there a better approach to this?