jeudi 23 février 2023

"./composer.json" does not contain valid JSON

[Seld\JsonLint\ParsingException]
  "./composer.json" does not contain valid JSON
  Parse error on line 1:
  \\\\\\\\\\\\\\\\\\\\
  ^
  Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

Those error occur when I try to run composer install on a Copied Laravel project from Remote Desktop Protocol.

Tried the https://jsonlint.com and it return valid.

Here's the composer.json file:

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.0.0",
        "cross-env": "^7.0",
        "jquery": "^3.2",
        "laravel-mix": "^5.0.1",
        "lodash": "^4.17.13",
        "popper.js": "^1.12",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.20.1",
        "sass-loader": "^8.0.0",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    }
}



via Chebli Mohamed

mercredi 22 février 2023

Laravel withTrashed in related model query callback

I am working with an old Laravel 5.7 app, and I'm having a nightmarish issue with fetching trashed related models with a callback function.

My setup is as follows:

$filter_comments = function ($q) use ($parameters) {
$q->whereBetween('dated_at', [$parameters['start'], $parameters['end']]);
$q->where('special_post', 1);
$q->whereIn('image_id', $parameterss['image_list']);
$q->withTrashed();
};

$collection = Post::with(['comments' => $filter_comments]);

The query with its filter works just fine except for the $q->withTrashed() line.

If I dump its internal SQL ($q->toSql() inside the callback function), I can see a blatant contradiction being inserted in my query. Whenever I add the withTrashed() line, Laravel appends a AND 0 = 1 to my query.

select * from `comments` where `comments`.`image_id` in (1,2,3) and `dated_at` between ? and ? and `special_post` = ? and 0 = 1

Both models have correctly defined belongsTo() and hasMany() relationships, and display no other issues. I have also tried adding withTrashed() to the relationship deffintion in the respective model file, but it didn't work either.

I am aware of some related bugs with previous Laravel versions (https://github.com/laravel/framework/issues/11860) but as far as I know, they are fixed for Laravel 5.7

I would really appreciate some feedback!

Thanks in advance!



via Chebli Mohamed

Swift mailer changed setting with default when queue:work

I have a swift mailer in Laravel 5.8 and it sends an email with the user SMTP setting. It works well manually, but when I use this within the queue, the mailer setting is reverted to the default setting.

The code is like this

if ($own_stmp) {
    $transport = (new Swift_SmtpTransport($user->mail_host, $user->mail_port))
        ->setUsername($user->mail_username)
        ->setPassword($user->mail_password);
} else {
    $transport = (new Swift_SmtpTransport(\Config::get('mail.host'), \Config::get('mail.port')))
        ->setUsername(\Config::get('mail.username'))
        ->setPassword(\Config::get('mail.password'));
}

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
    
// Create a message
if ($own_stmp) {
    $message = (new Swift_Message($subject))
        ->setFrom([$user->mail_from_address => $agent->name])
        ->setTo([$lead->email => $lead->name])
        ->setReplyTo($agent->email)
        ->addPart($content, 'text/html');
} else {
    $message = (new Swift_Message($subject))
        ->setFrom([\Config::get('mail.from.address') => $agent->name])
        ->setTo([$lead->email => $lead->name])
        ->setReplyTo($agent->email)
        ->addPart($content, 'text/html');
}

// Send the message
$result = $mailer->send($message);

As you can see, it changes email setting by $own_smtp flag.

This is really working well, but when I use this with

php artisan queue:work

It is skipped custom user setting and send with default setting.

What is wrong? How to solve this?



via Chebli Mohamed

mardi 21 février 2023

is there a way to test data update failure in laravel unit test

I'm doing the unit testing in Laravel. I wrote a test for the if function (data store). but I want to know how to write test for else part. when data save is failure, an error message return.

    public function store(Request $request)
    {
        $user = $this->user->create($request->all());

        if ($user) {
            return response()->json([
                'message' => 'Data saved successfully,
                'data' => [
                    'user' => $user
                ]
            ]);
        } else {
            return response()->json([
                'message' => 'Data save failed.'
            ], 400);
        }
    }


via Chebli Mohamed

lundi 20 février 2023

What is the correct process flow to find a controller file, blade file and model file from chrome's inspect window laravel

I am an intern currently working with some laravel project. I was assigned a simple taks to find and edit value in a controller file. But I am not able to quickly locate the file I want. What is the best and proper way to find something from frontend in backed using chrome's inspect window, like I want to find a controller file for the url. How to find it it using inspect window. Others say I should use inspect window to find it, but not how. Help please. Thanks in advance.

I initially tried finding the controller file using an "all files search" function in sublime text. For example, int to an add page, saw a text field there, went or the project folder, searched using "all files search, ctrl+shift+f", located the text, then backtracked every single component used there and finally found the controller file. But it is taking too much time and I am not able to find some files where the actual names and the names I am seeing in frontend is different.



via Chebli Mohamed

dimanche 19 février 2023

How can I send a value from one table to another table at the same level inside the blade

I have two tables I want to pass the values that are selected from the first table in the third field as shown in the figure

enter image description here

note: that there is a button that adds a new input row by jquery on click (Add Cells)

//here first table code in blade

<table class="table table-bordered table_field4" id="table_field4" style ="overflow-x: auto;white-space: nowrap;">
                                                                        <thead>
                                                                        <tr class="thead-dark">
                                                                            <th> #</th>
                                                                            <th style="width: 250px; !important">first</th>
                                                                            <th style="width: 250px; !important">second </th>

                                                                            <th style="width: 200px; !important">third</th>


                                                                            <th style="width: 200px; !important"></th>
                                                                        </tr>
                                                                        </thead>
                                                                        <tbody>
                                                                        <tr class="trr">
                                                                            <?php $x=1;?>

                                                                            <td>1</td>
                                                                            <td style="display:none;"><input type="text"  name="prod_idd[]" style="display:none;" value=""></td>

                                                                            <td>
                                                                                <input type="text" style="width: 250px; !important" class="sub_code form-control getAllCode putCode" name="sub_code[]">
                                                                                @error('sub_code.*')
                                                                                <div class="alert alert-danger" role="alert">
                                                                                
                                                                                </div>
                                                                                @enderror
                                                                            </td>
                                                                            <!-- heeree -->
                                                                            <td>
                                                                                <input type="text" style="width: 250px; !important" class=" form-control  " name="count_pices[]">
                                                                                @error('.*')
                                                                                <div class="alert alert-danger" role="alert">
                                                                                
                                                                                </div>
                                                                                @enderror
                                                                            </td>
                                                                            <td>
                                                                                <select style="width: 150px; !important"   class="form-control getUnit"
                                                                                        name="unit_id[]">
                                                                                        @foreach ($units as $unit)
                                                                                            <option value="" name="">
                                                                                            </option>
                                                                                        @endforeach
                                                                                    </select>
                                                                            </td>


                                                                            <td style="width: 200px; !important"><input type="button" class="btn btn-success" name="add4" id="add4" value="Add Cells" ></td>
                                                                        </tr>
                                                                        </tbody>
                                                                        <tfoot>
                                                                        <tr>

                                                                        </tr>
                                                                        </tfoot>
                                                                    </table>

// jquery to add new row for first table that have column (third)

$('#add4').click(function(){
          var  size = $('#table_field4 tbody').children().length +1;
          var html = '<tr class="trr">'+'<td>'+size+'</td>'+'<td style="display:none;"><input type="text"  name="prod_idd[]" style="display:none;" value=""></td><td><input type="text" class="form-control sub_code putCode" name="sub_code[]"></td><td><input type="text" class="count_pices form-control" name="count_pices[]"></td><td><select style="width: 150px; !important"   class="form-control getUnit" name="unit_id[]">@foreach ($units as $unit)<option value="" name=""></option>@endforeach</select></td><td><input type="button" class="btn btn-danger" name="remove" id="remove" value="delete" style="color:black;background-color:red;"></td></tr>';
            $('#table_field4').append(html);
            // var rowCount = $('#table_field4 .trr').length;

            // console.log(rowCount);
        });

        $('#table_field4').on('click','#remove',function(){
            $(this).closest('tr').remove();
        });

The first part related to the first table has been completed The following is the second table that is created by calculating the number of rows in the first table and creating equal rows using JQuery.

//here second table enter image description here

//second table in blade

                                                                    <table class="table table-bordered table_field5" id="table_field5" style ="overflow-x: auto;white-space: nowrap;">
                                                                        <thead>
                                                                        <tr class="thead-dark">
                                                                            
                                                                            <th style="width: 100px; !important">C</th>
                                                                            <th style="width: 100px; !important">الكويت</th>
                                                                            <th style="width: 100px; !important">A</th>
                                                                    
                                                                        </tr>
                                                                        </thead>
                                                                        <tbody>
                                                                            <tr>
                                                                                                                                                   
                                                                            <td ><input type="text" name="" ></td>
                                                                            <td ><input type="text" name="" ></td>
                                                                            <td ><input type="text" name="" ></td>                                                                           
                                                                    </tr>
                                                                        </tbody>
                                                                        <tfoot>
                                                                        <tr>

                                                                        </tr>
                                                                        </tfoot>
                                                                    </table>

Here is the jquery code that counts the number of rows in the first table and adds rows equal to it according to the number of columns in the second table

$('#add4').click(function(){
    var rowCount = $('#table_field4 .trr').length + 1;
    var rowCountone = $('#table_field4 .trr').length ;
          var  size = $('#table_field4 .trr').length + 1;
          var html = '<tr>'+'<td><input type="text" value="" ></td><td ><input type="text" name="value[]" ></td><td ><input type="text" name="value[]" ></td></tr>';

          $('#table_field5').append(html);

        });


via Chebli Mohamed

Laravel SSE start sending the events after long time

I am integrating the SSE with laravel 5.7 on a server in php 7.4 (prod&local) but locally I receive the events without problem, unfortunately the client can wait up to 10 minutes to start receiving the events. And especially on the server side according to my logs, it starts sending the events as soon as the connection is opened, I wonder what could be blocking (or buffering) the results for sending them to after some time what can crash my server in prod.

Controller

public function index()
{
    return response()->stream(function () {
            try{
                while(true){
                    Log::info("in".now());
                    echo "data: " . now() . "\n\n";
                    ob_flush();
                    flush();
                    Log::info("out".now());
                    sleep(3);
                }
                                    
            }catch(\Exception $e){
                Log::error($e->getMessage());
            }
            if (connection_aborted()) {break;}


    }, 200, [
        'Content-Type' => 'text/event-stream',
        'Cache-Control' => 'no-cache',
        'Connection' => 'keep-alive'
    ]);
}

Javascript

<script>
  window.onload= function(){
    console.log('loaded')
  var source = new EventSource('');
  source.addEventListener("message", function(event) {
    const trans = event.data;
    console.log(Date(),trans)

  });
  source.onerror = (e)=>{
    console.log(e)
  }
</script>


via Chebli Mohamed