lundi 8 janvier 2024

Laravel 5.3, empty() is treating a zero value as empty in a query

In my Laravel project (version 5.3), I'm sending a param in a URL:

&container=0

But by the time it gets into the PHP function that creates an SQL query, it treats the zero as empty and satisfies the empty string portion of this line:

$containerCL = empty($container) ? '' : "AND SHPTABLE.CNT IN (".implode(',',$container).")";

I do want to send an empty string into the query if no option is chosen for this, but in this case, I need to send the zero value as we have some records identified by that being the actual value. How can I let this catch empty parameters but still use zero as an actual value for the query?



via Chebli Mohamed

dimanche 31 décembre 2023

livewire 3 how to store foreach value using form

hello I'm new for livewire 3 I have table inside form, data table having radio button for yes or no after selecting yes or no I'm going to submit that form that time I want to store fetch detail like id and name along this. now I'm any getting radio button value, me to solve

form page enter image description here my code form

<div class="modal-body">
    <form wire:submit.prevent="Save" autocomplete="off">
      <div class="card card-bordered card-preview table-responsive ">
        <div class="card-inner "> 
          <table class="datatable  table   ">
            <thead>
              <tr>
                <th style=" border: 1px solid black; text-align: center;">SL</th>
                <th style=" border: 1px solid black; text-align: center;">ID No</th> 
                <th style=" border: 1px solid black; text-align: center;">NAME</th>
                <th style=" border: 1px solid black; text-align: center;">YES</th>
                <th style=" border: 1px solid black; text-align: center;">NO</th>
              </tr>
            </thead>
            <tbody> 
 @foreach ($UserDetail as $key=>$UserDetails) 
 @php $ID = 0+$key @endphp
<td style=" border: 1px solid black; text-align: center;">
                
              </td> 
              <td style=" border: 1px solid black; text-align: center;">
                
              </td>
              <td style=" border: 1px solid black; text-align: center;">
                
              </td>
              <td style=" border: 1px solid black; text-align: center;">
                <div class="custom-control custom-control-md custom-radio ">
                  <input type="radio" wire:model="TableInput..data" class="custom-control-input" name="TableInputs[]" id="sv2-preference-fedev" value="YES" required>
                  <label class="custom-control-label" for="sv2-preference-fedev"></label>
                </div>
              </td>
              <td style=" border: 1px solid black; text-align: center;">
                <div style="text-align: center;" class="custom-control custom-control-md custom radio"><input type="radio" wire:model="TableInput..data" class="custom-control-input" name="TableInputs[]" id="sv2-preference-uxdis" value="NO" required>
                  <label class="custom-control-label" for="sv2-preference-uxdis"></label>
                </div>
              </td> 
              </tr> 
      @endforeach 
            </tbody>
          </table>
        </div>
      </div>
      <br>
      <div  >
        <button type="submit" class="btn btn-md btn-primary">SAVE  </button>
      </div>
    </form>
  </div>

Controller class StudentAttendance extends Component {

public $name; 
public $id;  
public $TableInput = [];


public function mount()
{
  $this->User       = User::all();   
}

public function Save() 
{   
    $bel = Data::create([ 
         
        'Id'                     => $value['Id'],
        'name'                   => $value['name'],
        'data'                   => $value['data'],
    ]);
} 
} 

}



via Chebli Mohamed

mercredi 6 décembre 2023

FatalErrorException in Handler.php line 26

While migrating to Laravel 5.0 from 4.2 I am getting this error

FatalErrorException in Handler.php line 26: Uncaught TypeError: Argument 1 passed to App\Exceptions\Handler::report() must be an instance of Exception, instance of Error given, called in \vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php on line 74 and defined in C:\app\Exceptions\Handler.php:26 Stack trace: #0 \vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php(74): App\Exceptions\Handler->report(Object(Error)) #1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Error)) #2 {main} thrown

I have migrated one application from laravel 4.2 to laravel 5.0, placed all the code according to requirement and done composer update command but white executing this I am getting this error.



via Chebli Mohamed

How can I use websockets in Flutter?

I am trying to implement WebSockets for a Laravel-Flutter project. For the Laravel side, I followed these steps. If you see anything wrong or missing, please feel free to say:

https://gist.github.com/emir-ekin-ors/79e670eb6ea970af38c476a8087c19ea

When I test it with Tinker, I can see the event in the dashboard. So I assume the Laravel part is working properly.

The problem is when I try to listen to the channel in Flutter. I can't see anything on the terminal. I tried to follow the documentation of the web_socket_channel package. I am open to all the suggestions since I know nothing about websockets. You can find the Flutter code below:


import 'dart:async';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() {
    runApp(MyApp());
}

class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: MyWebSocketScreen(),
        );
    }
}

class MyWebSocketScreen extends StatefulWidget {
    @override
    _MyWebSocketScreenState createState() => _MyWebSocketScreenState();
}

class _MyWebSocketScreenState extends State<MyWebSocketScreen> {
    late final _channel;
    late StreamSubscription _streamSubscription;

    @override
    void initState() {
        super.initState();
        _channel = WebSocketChannel.connect(Uri.parse('wss://localhost:6001'));
        _streamSubscription = _channel.stream.listen((data) {
            print('Received: $data');
        }, onError: (error) {
            print('Error: $error');
        });
    }

    @override
    Widget build(BuildContext context) {
        return Placeholder();
    }

    @override
    void dispose() {
        _streamSubscription.cancel();
        _channel.sink.close();
        super.dispose();
    }
}

This is the NewMessage class in Laravel if it necessary:


<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

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

    public function broadcastOn(): array
    {
        return [
            new Channel('home'),
        ];
    }
}


via Chebli Mohamed

samedi 2 décembre 2023

I have encrypted data in the database how to decrypt it before displaying in the frontend in crocodic-studio / crudbooster?

I have the following form -

$this->form[] = ['label'=>'Client Name','name'=>'client_id','type'=>'select','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'client,client_name','datatable_where'=>'status=1'];
$this->form[] = ['label'=>'Client Code','name'=>'user_id','type'=>'select','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'cms_users,name','datatable_where'=>'id_cms_privileges = 3 and blocked=0','parent_select'=>'client_id'];

cms_users,name is encrypted using the laravel encryption - Crypt::encryptString($postdata['name'], env('ENC_KEY'));

Now the problem is when I am clicking on the Client name dropdown I get the encrypted value in the Client Code dropdown.

I want to decrypt the value before displaying to the Client Code dropdown. How to solve this issue??

enter image description here



via Chebli Mohamed

vendredi 1 décembre 2023

Laravel validation regex depends upon dependent answer

We have 2 questions 'temp_id_type' with Select Options 'A','B', 'C' 'temp_id' text field

Validation rule required on temp_id

  • requied_if:temp_id_type,A,B,C Also I need regex rule on temp_id
  • if temp_id_type=A - regex should match: ^[0-9]{13}$
  • if temp_id_type=B - regex should match: ^[0-9]{13,20}$
  • if temp_id_type=C - regex should match: ^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,35}$


via Chebli Mohamed

mercredi 29 novembre 2023

Getting data from database in jquery

I want to get yeniseries values ​​from the database, i can use the API but I don't know what I should add to the javascript code, I would be happy if you help me.

var yeniSeries = [50, 80, 30];

window.addEventListener("load", function () {
  try {
    var grafikYapilandirma = {
      chart: {
        type: "donut",
        width: 370,
        height: 430,
      },
      colors: ["#622bd7", "#e2a03f", "#e7515a", "#e2a03f"],
      dataLabels: {
        enabled: false,
      },
      legend: {
        position: "bottom",
        horizontalAlign: "center",
        fontSize: "14px",
        markers: {
          width: 10,
          height: 10,
          offsetX: -5,
          offsetY: 0,
        },
        itemMargin: {
          horizontal: 10,
          vertical: 30,
        },
      },
      plotOptions: {
        pie: {
          donut: {
            size: "75%",
            background: "transparent",
            labels: {
              show: true,
              name: {
                show: true,
                fontSize: "29px",
                fontFamily: "Nunito, sans-serif",
                color: undefined,
                offsetY: -10,
              },
              value: {
                show: true,
                fontSize: "26px",
                fontFamily: "Nunito, sans-serif",
                color: "#1ad271",
                offsetY: 16,
                formatter: function (t) {
                  return t;
                },
              },
              total: {
                show: true,
                showAlways: true,
                label: "Total",
                color: "#888ea8",
                formatter: function (t) {
                  return t.globals.seriesTotals.reduce(function (n, e) {
                    return n + e;
                  }, 0);
                },
              },
            },
          },
        },
      },
      stroke: {
        show: true,
        width: 15,
        colors: "#0e1726",
      },
      series: yeniSeries,
      labels: ["Online", "Offline", "Rest"],
      responsive: [
        { breakpoint: 1440, options: { chart: { width: 325 } } },
        { breakpoint: 1199, options: { chart: { width: 380 } } },
        { breakpoint: 575, options: { chart: { width: 320 } } },
      ],
    };

    var grafik = new ApexCharts(
      document.querySelector("#chart-2"),
      grafikYapilandirma,
    );

    grafik.render();

    document
      .querySelector(".theme-toggle")
      .addEventListener("click", function () {
        var yeniSeries = [200, 300, 500];

        grafik.updateOptions({ series: yeniSeries });
      });
  } catch (hata) {
    console.log(hata);
  }
});

I would appreciate it if you could help, thank you



via Chebli Mohamed

mardi 28 novembre 2023

"Resolving Country Code Bug: How to Fix the country code?"

 <div class="form-group">
                     <label class="form-label required"></label>
                                <input  class="form-control mobilenumber @error('mobile') is-invalid @enderror phone"
                                    type="tel" id="number" name="mobile" onkeypress='validate(event)'>

                                <input type="hidden" id="code" name="countrycode" value="1">

                                @error('mobile')
                                    <div class="invalid-feedback d-block">
                                        
                                    </div>
                                @enderror
                            </div>

Here i want my country code will be bangladesh and it will be fixed.



via Chebli Mohamed

Selenium Appium App Crashed And Returns A Failed Cases

So I have a Selenium Appium Python script for my testing purpose. I created the UI website using Laravel.

My script consists of around 3 test cases:

def test_login_success
def test_less_phone_number
def test_more_phone_number

this is my LoginScriptController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class LoginScriptController extends Controller
{
    public function runLoginScript()
    {
        $command = 'pytest ../automation/app.py -k "test_login_success or test_less_phone_number or test_more_phone_number" 2>&1';
        exec($command, $output, $returnCode);

        if ($returnCode === 0) {
            return response('Script executed successfully', 200);
        } else {
            return response('Script encountered an error', 500);
        }
    }
}

When I click the button "Run test" on my website UI, the app always breaks down (crashed) and the first test case stopped (returns a Failed status). I already tried running it manually from my terminal using pytest app.py -k "test_login_success or test_less_phone_number or test_more_phone_number" but it works ok (returns PASSED status for all cases).

I can't find what's making my app breaks down



via Chebli Mohamed

jeudi 23 novembre 2023

How to print Api response data as collection

I was trying to print API response data as collection on blade for that i have used following line

$customers =   collect(json_decode($response, true));

But whenever i tried to print with following code:

 @foreach($customers as $row)
    <tr>
      <td> </td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  @endforeach 

it shows bellow error, What's the problem here?

Attempt to read property "first_name" on array

Here is the API response:

Illuminate\Support\Collection {#341 ▼ // app\Http\Controllers\IntegrationController.php:61
  #items: array:1 [▼
    "customers" => array:3 [▼
      0 => array:27 [▼
        "id" => 6895839936762
        "email" => "russel.winfield@example.com"
        "accepts_marketing" => false
        "created_at" => "2023-10-20T11:06:26-04:00"
        "updated_at" => "2023-10-20T11:06:26-04:00"
        "first_name" => "Russell"
        "last_name" => "Winfield"
        "orders_count" => 0
        "state" => "disabled"
        "total_spent" => "0.00"
        "last_order_id" => null
        "note" => "This customer is created with most available fields"
        "verified_email" => true
        "multipass_identifier" => null
        "tax_exempt" => false
        "tags" => "VIP"
        "last_order_name" => null
        "currency" => "USD"
        "phone" => "+16135550135"
        "addresses" => array:1 [▶]
        "accepts_marketing_updated_at" => "2023-10-20T11:06:26-04:00"
        "marketing_opt_in_level" => null
        "tax_exemptions" => []
        "email_marketing_consent" => array:3 [▶]
        "sms_marketing_consent" => array:4 [▶]
        "admin_graphql_api_id" => "gid://shopify/Customer/6895839936762"
        "default_address" => array:17 [▶]
      ]
      1 => array:26 [▶]
      2 => array:26 [▶]
    ]
  ]
  #escapeWhenCastingToString: false
}


via Chebli Mohamed

Laravel notification via method changes not coming in toMail method

I have one class where I calculate variables in via method and the same variable I want to use in toMail method but it's always null in the toMail Method. any idea why?

class FinancialQuestionnaireSubmissionNotification extends Notification implements ShouldQueue
{
    use Queueable,SerializesModels, GlobalMailHelperTrait;

    public Lead $lead;
    public $code;

    public function __construct(Lead $lead)
    {
        $this->lead = $lead->fresh();         
                          
    }
    public function via($notifiable)
    {

        $this->code = 'xyz';            
       
        return ['mail'];
    }
    /**
     * Get the mail representation of the notification.
     */
    public function toMail($notifiable)
    {                    
        dd($this->code);
    }   

    /**
     * Get the array representation of the notification.
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

here my $this->code is always null why even after setting that variable in via method!



via Chebli Mohamed

mardi 21 novembre 2023

Laravel Nova Panel Form Fields Update issue

I am working on nova panel in localhost.. When i perform update my form fields that time i will see this warning...

"Another user has updated this resource since this page was loaded. Please refresh the page and try again."

any solution for that?

I will perform cache clear operation

php artisan config:clear

php artisan route:clear

php artisan view:clear


via Chebli Mohamed

samedi 18 novembre 2023

Quantized feature maps with Kmeans, then visualize them on the original image

I extracted feature maps using ResNet, then quantized (segmented) using Kmeans. Now I want to visualize the quantized feature maps (labels) on the input image. Does anyone have an idea how I can do this?

 model = models.resnet18(weights='ResNet18_Weights.DEFAULT')
    model_children = list(model.children())
    feature_extractor = torch.nn.Sequential(\*list(model.children())\[:-2\])

    feature_extractor.eval()

    image_path = 'image.jpg'
    transform = transforms.Compose(\[
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(mean=0., std=1.)
    \])
    image = transform(Image.open(image_path)).unsqueeze(0)

    with torch.no_grad():
    feature_maps = feature_extractor(image)

    feature = feature_maps.squeeze(0)
    feature = feature.view(512, -1)
    feature = feature.detach().numpy()
    feature= np.transpose(feature)

    \#Kmeans Algorithm
    num_clusters = 10
    kmeans = KMeans(n_clusters=num_clusters,n_init='auto', random_state=0).fit(feature)

    labels = kmeans.labels\_
    labels= labels.reshape(7,7)
    plt.imshow(labels)
    plt.show()


via Chebli Mohamed

vendredi 17 novembre 2023

Laravel 5.8: Laravel Passport API Authentication Issue Outside php artisan serve

I am encountering an authentication problem with my Laravel API when attempting to run it without using php artisan serve. I have implemented Passport for authentication.

The authentication process works seamlessly when using php artisan serve and accessing http://127.0.0.1:8000/api/login in tools like Insomnia. However, I am facing issues when trying to run the Laravel backend independently and connecting it to an Angular frontend.

Despite exploring various solutions suggested online, including updating the .htaccess files in both the root and public folders, the API consistently returns an "unauthenticated" error.

I would appreciate any guidance or assistance in resolving this issue. If anyone has encountered a similar problem or can provide insights into how to make Laravel Passport authentication work outside of php artisan serve, your help would be greatly appreciated.

Thank you in advance for your time and assistance.

  • Updated the .htaccess files in both the root and public folders as recommended in online resources.
  • Checked the Laravel Passport configuration for any misconfigurations.
  • Verified that the Laravel backend is accessible outside of php artisan serve.
  • Ensured that the Angular frontend is making requests to the correct API endpoints.
  • Checked for any relevant error messages in the Laravel logs.

Expectation:

I expected the Laravel Passport authentication to work seamlessly when the backend is accessed independently (without using php artisan serve) from my Angular frontend. However, despite these efforts, the API consistently returns an "unauthenticated" error.



via Chebli Mohamed

dimanche 12 novembre 2023

Laravel project code not refelcting changes to view files

I created a laravel(5.1.3) project with breeze as the starter kit. I am planning to use the react as frontend to this project. I run the 'php artisan serve' command. The boiler plate template is working but any changes to files /resources/js/Pages/Welcome.jsx or /resources/views/welcome.blade.php is not reflecting. I have tried

  1. clearing the storage/framework/views folder ,
  2. run command php artisan view:clear ,
  3. run command php artisan config:clear ,
  4. run command composer dump-autoload ,

Still no change to the initial view. What am I doing wrong?

And I configured to make react as frontend library so I don't need the welcome.blade.php file right?



via Chebli Mohamed

samedi 11 novembre 2023

How to send multiple data from view to controller laravel

i want to send data from view to controller ..i.e. 1st card click send id =5 , 2nd card click send id = 6 etc...I can't find answer anywhere on google ...any help will be appreciated...thanks

i tried sendind the variable even aaray by form ..but i am not able to get the desired output.As i said i want to send data on card conditions ..for card 1 send id = 5 , card 2 send id = 6 ..so on

Here is my Code ...

@foreach ($role as $d)
      <form class="form-signin" id="agentPassword" method="POST" action="">
         
        <div class="card_dash card-1" onClick='submitDetailsForm()'>
          <h3>    
          
          <img src="/assets_web/app-icon/icon/web-icon/bix42_" id="role" alt="img">
            <input type="hidden" name="roleInfo[]" value="">
            <!-- <input type="hidden" name="role" value=""> -->
          </h3>
        </div>
      </form>
      @endforeach

the id value in already in $d[1] ...its even better if i can send the whole array $d.



via Chebli Mohamed

Hii i am create a new laravel project in laravel 5.1.3 version and my php version is 8.2.12.please help me to solve this errors

Problem 1 - laravel/framework[v10.10.0, ..., v10.31.0] require league/flysystem ^3.8.0 -> satisfiable by league/flysystem[3.8.0, ..., 3.19.0]. - league/flysystem[3.3.0, ..., 3.14.0] require league/mime-type-detection ^1.0.0 -> satisfiable by league/mime-type-detection[1.0.0, ..., 1.14.0]. - league/flysystem[3.15.0, ..., 3.19.0] require league/flysystem-local ^3.0.0 -> satisfiable by league/flysystem-local[3.15.0, 3.16.0, 3.18.0, 3.19.0]. - league/mime-type-detection[1.0.0, ..., 1.3.0] require php ^7.2 -> your php version (8.2.12) does not satisfy that requirement. - league/mime-type-detection[1.4.0, ..., 1.14.0] require ext-fileinfo * -> it is missing from your system. Install or enable PHP's fileinfo extension. - league/flysystem-local[3.15.0, ..., 3.19.0] require ext-fileinfo * -> it is missing from your system. Install or enable PHP's fileinfo extension. - Root composer.json requires laravel/framework ^10.10 -> satisfiable by laravel/framework[v10.10.0, ..., v10.31.0].

To enable extensions, verify that they are enabled in your .ini files: - C:\Program Files\php-8.2.12\php.ini

Hii i am create a new laravel project in laravel 5.1.3 version and my php version is 8.2.12.please help me to solve this errors. i have enabled the file-info extension then also same error.



via Chebli Mohamed

dimanche 5 novembre 2023

Get all children categories of a collection of categories without using foreach in Laravel

so I have this codes in my Category model. What it does is, you give it a single category collection and it will return all children category ids of that category in a one dimensional array of ids that can be used in a whereIn query.

private $descendants = [];

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

public function children()
    {
        return $this->subcategories()->with('children');
    }

public function hasChildren(){
        if($this->children->count()){
            return true;
        }

        return false;
    }

public function findDescendants(Category $category){
        $this->descendants[] = $category->id;

        if($category->hasChildren()){
            foreach($category->children as $child){
                $this->findDescendants($child);
            }
        }
    }

public function getDescendants(Category $category){
        $this->findDescendants($category);
        return $this->descendants;
}

Usage:

$category = Category::where('id',$id)->first();
$children_ids = [];
$children_ids = $category->getDescendants($category);

It works. It is very useful in my filter. But when it comes to getting children ids of multiple categories, I had to use foreach loop and I had to call getDescendants multiple times thus creating multiple queries. What I want to accomplish are:

  1. To improve performance how to do it in a single query without the need of using foreach loop? Where I want to feed it not just a single category but a collection of categories, and then it should return all children category ids of those categories.
  2. How to return not just children ids but entire collection of children categories?

What usage I had in mind (please feel free to suggest a better approach)

Getting children ids from category collections:

$category = Category::where('parent_id',$id)->get();
$children_ids = [];
$children_ids = $category->getDescendants($category);

Getting children collection from category collections.

$category = Category::where('parent_id',$id)->get();
$children_ids = [];
$children_ids = $category->getDescendants($category);

Please help me accomplish this. Thank you.



via Chebli Mohamed

display students data rank wise as similar to e-commerce website [closed]

I have to display the data of students as it is shown in e-commerce website like amazon. First image of the student, then below it name and then the rank of the student. The number of students is dynamic. I am fetching it from database. But how can I present data in such fashion without using html table. Is there any other way to present data row column format without using table? How can I do it in Laravel?



via Chebli Mohamed