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 send an email with user smtp setting. It works well manually, but when I use this within queue, mailer setting is reverted to default setting. 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

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

vendredi 17 février 2023

destroy doesn't invoked, instead it executed show method in controller

laravel 5.8 and php 7.4

this only happen after I deploy the project on the server

I made delete request like this

enter image description here

response

enter image description here


web.php

Route::group(['prefix' => 'admin', 'middleware' => 'auth', /*'middleware' => ['auth','administrator'] ,*/ 'namespace' => 'admin', 'as' => 'admin.'], function () {
    Route::resource('/sellers', 'SellerController');

});

SellerController.php

class SellerController extends Controller
{
 public function show(Request $request, $id)
    {

        return ['msg' => 'it is show method '];
    }
   public function destroy(Request $request, $id)
    {
        if ($request->ajax()) {
            if ($request->user()->cannot('destroy', Seller::class)) {
                return ['error' => 'unauthorized'];
            }
            try {
                $teams = DB::table('team_user')->where('user_id', $id)->delete();
                $deleted = $this->model_instance::findOrFail($id);
                $deleted->delete();
                $deleted->name = " [archived]  $deleted->name #$id";
                $deleted->save();

                if ($deleted) {
                    $log_message = trans('sellers.delete_log') . '#' . $id;
                    logActivity($log_message);
                    return response()->json(['status' => 'success', 'message' => 'deleted_successfully']);
                } else {
                    return response()->json(['status' => 'fail', 'message' => 'fail_while_delete']);
                }
            } catch (\Exception $ex) {
                DB::rollBack();
                dd($ex->getMessage());
                Log::error($ex->getMessage());
                return redirect()->route($this->index_route)->with('error', $this->error_message);
            }
        }
        return redirect()->route($this->index_route);
    }

}

in my local server it works fine



via Chebli Mohamed

jeudi 16 février 2023

Argument 1 passed to Jenssegers\Mongodb\Query\Builder::__construct(),of Jenssegers\Mongodb\Connection,Illuminate\Database\MySqlConnection

whenever I want to login my page, this error came, but I added my mongodb database with my project, what's the issue?

I just want login my page with my mongodb database, where i mentioned everything



via Chebli Mohamed

mardi 14 février 2023

Pest package of laravel

The pest package of laravel can push that package on live site what is best practice can i push it or not can anyone help me on that.

I install the pest laravel automation testing package on local setup of automation testing and logical testing can i push that package to live site what are the pros and cons.



via Chebli Mohamed

samedi 11 février 2023

laravel compare from array in controller with if lease condition

I'm trying to compare array getting from two different inputs and compare it in controller if both value same then pass TRUE if Not pass FALSE.

I tried below method but I was getting error and error pointing to below code

 if ($request->ANSWER[$i] === $request->OPTION[$i]) 
          
                {
                 $data->ANSWER_STATUS = "1"; 
                 } else {
                 $data->ANSWER_STATUS = "0"; 
                 } 

Error Code

Trying to access array offset on value of type null

my array pater looks

 "Question" => array:2 [▼
   0 => "html full form"
   1 => "water formula in science"
  ]
  "ANSWER" => array:2 [▼  //COMPARE 
    0 => "Hypertext Markup Language"
    1 => "h2O"
  ]
  "OPTION" => array:2 [▼  //COMPARE 
    0 => "Markup Language"
    1 => "h2O"
  ]

CONTROLLER

    public function Store_Answer(Request $request)
   {
        $Questioncount= $request->Question;
         
         if ($Questioncount) {
         
         for ($i=0; $i <count($request->Question); $i++) {
         $data = New OnlineExminAnswer();
 
             if ($request->ANSWER[$i] === $request->OPTION[$i]) 
              
                    {
                     $data->ANSWER_STATUS = "1"; 
                     } else {
                     $data->ANSWER_STATUS = "0"; 
                     } 
                     
               $data->question = $request->Question [$i];           
        $data->save();
         } 
         } 
 
        return back()->with('success',' Successfully .');
 
   }


via Chebli Mohamed

vendredi 10 février 2023

XMLHttpRequest on Laravel to complete fields based on user input

I have been trying to create an XMLHttpRequest to fetch data on mySQL based on 2 tables, but I can't get it to work properly as the beginner I am, so after a few days I wanna ask you for help

This is how I tried to do this, I'll change a few names as the code belongs to a company, they'll be highlighted with "*":

form

        <div class="col-md-3">
        <div class="position-relative form-group">
            <label class="">*number* - *name*</label>
            <select name="*first input*" id="*first input*" required="required" placeholder="" onchange="GetDetail(this.value)" class="form-control *select class*">
                <option></option>
                @foreach($properties as $prop)
                    <option  value="">  - </option>
                @endforeach
            </select>    
            </select>

this is the XMLHttpRequest function:

function GetDetail(str) {
    if (str.length == 0) {
        document.getElementById("*column1*").value = "";
        document.getElementById("*column2*").value = "";
        document.getElementById("*column3*").value = "";
        document.getElementById("*column4*").value = "";
        document.getElementById("*column5*").value = "";
        document.getElementById("*column6*").value = "";
        document.getElementById("*column7*").value = "";
        document.getElementById("*column8*").value = "";
        document.getElementById("*column9*").value = "";
        document.getElementById("*column10*").value = "";
        return;
    }
    else {

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {

            if (this.readyState == 4 && 
                    this.status == 200) {
                        
                var myObj = JSON.parse(this.responseText);

                document.getElementById("*column1*").value = myObj[0];
                document.getElementById("*column2*").value = myObj[1];                 
                document.getElementById("*column3*").value = myObj[2];
                document.getElementById("*column4*").value = myObj[3];
                document.getElementById("*column5*").value = myObj[4];
                document.getElementById("*column6*").value = myObj[5];
                document.getElementById("*column7*").value = myObj[6];
                document.getElementById("*column8*").value = myObj[7];
                document.getElementById("*column9*").value = myObj[8];
                document.getElementById("*column10*").value = myObj[9];    
            }else{
                console.log();("error " + xmlhttp.status);
            }
        };

        xmlhttp.open("GET", "client/for-ajax.blade.php/" +str, true);

        xmlhttp.send();
    }
}

and this is the for-ajax file, which was originally .php, but I tried changing it to .blade.php:

<?php

$prop_id = $_REQUEST['property_id'];
  
$conn = mysqli_connect("localhost", "*user*", "*password*", "d*atabase*");

$property_id = "SELECT `id` FROM `*table1*`";

if ($property_id !== "") {
       
    $query = mysqli_query($conn, "SELECT `*column1*`, `*column2*`, `*column3*`, `*column4*`, `*column5*`, `*column6*`, `*column7*`, `*column8*`, `*column9*`, `*column10*` FROM `*table2*` WHERE property_id='$property_id'");
  
    $row = mysqli_fetch_array($query);
    $*column1* = $row["*column1*"];
    $*column2* = $row["*column2*"];
    $*column3* = $row["*column3*"];
    $*column4* = $row["*column4*"];
    $*column5* = $row["*column5*"];
    $*column6* = $row["*column6*"];
    $*column7* = $row["*column7*"];
    $*column8* = $row["*column8*"];
    $*column9* = $row["*column9*"];
    $*column10* = $row["*column10*"];

}

$result = array("$*column1*", "$*column2*", "$*column3*", "$*column4*", "$*column5*", "$*column6*", "$*column7*", "$*column8*", "$*column9*", "$*column10*");
  
$myJSON = json_encode($result);
echo $myJSON;
?>

At first I was getting a 404, then I created a view for that url "client/for-ajax.blade.php/" and now I get a syntax error on the console:

Uncaught SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON
    at JSON.parse (<anonymous>)
    at GetDetail.xmlhttp.onreadystatechange


via Chebli Mohamed

laravel controller if else condition for array value

I'm Trying to pass value 1 for if equal value 0 for if not equal in columan ANSWER_STATUS using if and else condition in controller, i was tried two different methods but it was giving error help me to fix this.

ARRYR value

 "Question" => array:2 [▼
    0 => "html full form"
    1 => "water formula in science"
  ]
  "ANSWER" => array:2 [▼  //THIS ARRAY CONTAINING ALL RIGHT ANSWER
    0 => "Hypertext Markup Language"
    1 => "h2O"
  ]
  "OPTION" => array:2 [▼  //THIS ARRAY STUDENTS ANSWER 
    0 => "Markup Language"
    1 => h2O"
  ]
]

my controller method 1

public function Store_Answer(Request $request)
{
    $count = $request->Question;
    if ($count) {
        for ($i = 0; $i < count($request->Question); $i++) {
            $data = new OnlineExminAnswer();
            $data->ANSWER_STATUS = $request->ANSWER[$i] == $request->OPTION[$i] ? 1 : 0;
            $data->question = $request->Question[$i];
            $data->answer = $request->OPTION[$i];
            $data->save();
        }
    }
}

error

Trying to access array offset on value of type null

my controller method 2

 public function Store_Answer(Request $request)
    {
        $count = $request->Question;
        if ($count) {
            for ($i = 0; $i < count($request->Question); $i++) {
                $data = new OnlineExminAnswer();
                     if ($request->ANSWER[$i] == $request->OPTION[$i]) 
                     {
                     $data->ANSWER_STATUS = "1"; 
                     } else {
                     $data->ANSWER_STATUS = "0"; 
                     }  
                $data->question = $request->Question[$i];
                $data->answer = $request->OPTION[$i];
                $data->save();
            }
        }
    }

error

    Trying to access array offset on value of type null


via Chebli Mohamed

jeudi 9 février 2023

syntax error, unexpected token "}" LARAVEL

I got error in my Laravel controller that says syntax error, unexpected token "}", i have checked every line but couldn't identified the error reason.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Dompdf\Dompdf;

class WordController extends Controller
{
    public function importForm()
    {
        return view('import');
    }

    public function importWord(Request $request)
    {
        $file_path = $request->file('word_file')->getRealPath();

        try {
            $word = new COM("Word.Application") or die("Unable to instantiate Word");
            $word->Visible = 0;
            $word->Documents->Open($file_path);
            $content = $word->ActiveDocument->Content->Text;
            $word->Quit();
            $word = null;
            unset($word);
        } catch (Exception $e) {
            return redirect()->back()->with('error', 'An error occurred while importing the Word document');
        }

        $dompdf = new Dompdf();
        $dompdf->loadHtml($content);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        return $dompdf->stream();
        }
}


via Chebli Mohamed

mercredi 8 février 2023

laravel 5.1 installation issue with php 7.1 , cannot install carbon 2

  • composer install error on carbon 1 is deprecated SO, how can i run my vagrant with laravel 5.1 with carbon 1 and I have try find from stackoverflow and other site but no helps comes up . every thing is done but shows carbon 1 is deprecated


via Chebli Mohamed

mardi 7 février 2023

500 Internal Server Error in Laravel query error when i die dump the data appears but the console show ther error

 $shipments =DB::table('users')
    ->select('users.fname')
    //  ->where('invnum.doctype','=',5)
    //  ->where('invnum.docstate','=',4)
   
    
     ->get();

     dd($shipments);

i have an issue with my laravel application which just started abruptly am getting the below error enter image description here

The data is displays in dd but when i have a query with a lot of data it doesn't and am getting the error i have tried to add cors but the error doent go away what could be the issue the laravel logs shows no error. I understand 500 is not an actual error but the server could not find appropriate response



via Chebli Mohamed

Datadog: Manual Instrumentation in Laravel 5

I'm trying to manually add datadog tracing for my method in laravel. This involves creating a span on top of existing spans. I read this issue and tried both solutions but neither worked.

In the first approach, I ended up getting errors about dd_trace not being found (in my provider) even though dd_trace was up and running. I tried using \DDTrace\trace_method but I got errors about DDTrace not being found even though i could use DDTrace in my controller

In the second approach, I did not get any errors but nothing showed up in my datadog UI.

Not sure why this is happening. Any help would be much appreciated! Thanks



via Chebli Mohamed

lundi 6 février 2023

forceDelete method not working as expected in laravel 5 project (can't delete model from the database)

I working (editing) on project base on laravel 5.8 in the database I have "contacts" table main columns are :

( id ,name, .. ,deleted_at , deleted_by agency_id contactable_id ... )

so when is use $model->delete() for soft delete it will work very well

before delete ( id :1 ,name: 'name', .. ,deleted_at : null , deleted_by :null agency_id : 1 contactable_id : 1)

after delete ( id :1 ,name: 'name', .. ,deleted_at : (dateValue) , deleted_by :1 agency_id : 1 contactable_id : 1)

class ContactController extends Controller
{
 public function delete(Request $request)
    {


        if ($request->ajax()) {
            \Log::info($request->contact_id);
            try {
                $deleted = $this->model_instance::find($request->contact_id)->delete();
            } catch (\Exception $ex) {
                \Log::info($ex->getMessage());
            }
            if ($deleted) {
                $log_message = trans('contacts.delete_log') . '#' . $request->contact_id;
                //logActivity($log_message);
                return response()->json(['status' => 'success', 'message' => 'deleted_successfully']);
            } else {
                return response()->json(['status' => 'fail', 'message' => 'fail_while_delete']);
            }
        }

        return redirect()->route($this->index_route);
    }
}

so when is use $model->forceDelete() for delete for ever from the database (forceDelete) it will not work as expected but will fill deleted_by with user number and keep deleted_at with null value

before force delete ( id :1 ,name: 'name', .. ,deleted_at : null , deleted_by :null agency_id : 1 contactable_id : 1)

after force delete ( id :1 ,name: 'name', .. ,deleted_at : null , deleted_by :1 agency_id : 1 contactable_id : 1)

class ContactController extends Controller
{
    public function forceDelete(Request $request)
    {
        if ($request->ajax()) {
            \Log::info($request->contact_id);
            try {
                $deleted = $this->model_instance::withTrashed()->find($request->contact_id)->forceDelete();
              
            } catch (\Exception $ex) {
                \Log::info($ex->getMessage());
            }
            // if ($deleted) {
            //     $log_message = trans('contacts.delete_log') . '#' . $request->contact_id;
            //     return response()->json(['status' => 'success', 'message' => 'deleted_successfully']);
            // } else {
            //     return response()->json(['status' => 'fail', 'message' => 'fail_while_delete']);
            // }
        }
        // return redirect()->route($this->index_route);
    }
}

forceDelete() return true


so this method work like this or there problem in my code in some where(I mean not jsut the previos code ) ?!

use softdelete in some cases use delete (for soft delete) and other cases use forceDelete (for delete from the database)


for soft delete it worked very well for force delete it takes another scenario



via Chebli Mohamed

Carbon's formatLocalized not working on production server

The following function present in app/Helpers/helpers.php returns me the short month on my local machine. However, I deployed it to the server and it is always returning the month in English.

function dateFormatShortDateLang($date) {
    setlocale(LC_TIME, app()->getLocale());
    \Carbon\Carbon::setLocale(app()->getLocale());
    $shortMonth = ucfirst(str_replace('.', ',', \Carbon\Carbon::createFromFormat('d/m/Y', $date)->formatLocalized('%b %G')));

    return $shortMonth;
}

If I dd() the value of app()->getLocale() I get the correct current locale. The whole repo has the same code, same PHP version and I run the following commands:

php artisan cache:clear
php artisan config:clear
composer dump autoload

My config/app.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Application Name
    |--------------------------------------------------------------------------
    |
    | This value is the name of your application. This value is used when the
    | framework needs to place the application's name in a notification or
    | any other location as required by the application or its packages.
    |
    */

    'name' => env('APP_NAME', 'Laravel'),

    /*
    |--------------------------------------------------------------------------
    | Application Environment
    |--------------------------------------------------------------------------
    |
    | This value determines the "environment" your application is currently
    | running in. This may determine how you prefer to configure various
    | services your application utilizes. Set this in your ".env" file.
    |
    */

    'env' => env('APP_ENV', 'production'),

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => env('APP_DEBUG', false),

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => env('APP_URL', 'http://localhost'),

    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'UTC',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'es',

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'es',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    */

    'key' => env('APP_KEY'),

    'cipher' => 'AES-256-CBC',

    /*
    |--------------------------------------------------------------------------
    | Logging Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log settings for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Settings: "single", "daily", "syslog", "errorlog"
    |
    */

    'log' => env('APP_LOG', 'single'),

    'log_level' => env('APP_LOG_LEVEL', 'debug'),

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        // Illuminate\Translation\TranslationServiceProvider::class,
        Spatie\TranslationLoader\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,

        // Multilingual
        App\Providers\RouteServiceProvider::class,
        App\Providers\ViewComposerServiceProvider::class,

    ],

    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
        'Bus' => Illuminate\Support\Facades\Bus::class,
        'Cache' => Illuminate\Support\Facades\Cache::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
        'Event' => Illuminate\Support\Facades\Event::class,
        'File' => Illuminate\Support\Facades\File::class,
        'Gate' => Illuminate\Support\Facades\Gate::class,
        'Hash' => Illuminate\Support\Facades\Hash::class,
        'Lang' => Illuminate\Support\Facades\Lang::class,
        'Log' => Illuminate\Support\Facades\Log::class,
        'Mail' => Illuminate\Support\Facades\Mail::class,
        'Notification' => Illuminate\Support\Facades\Notification::class,
        'Password' => Illuminate\Support\Facades\Password::class,
        'Queue' => Illuminate\Support\Facades\Queue::class,
        'Redirect' => Illuminate\Support\Facades\Redirect::class,
        'Redis' => Illuminate\Support\Facades\Redis::class,
        'Request' => Illuminate\Support\Facades\Request::class,
        'Response' => Illuminate\Support\Facades\Response::class,
        'Route' => Illuminate\Support\Facades\Route::class,
        'Schema' => Illuminate\Support\Facades\Schema::class,
        'Session' => Illuminate\Support\Facades\Session::class,
        'Storage' => Illuminate\Support\Facades\Storage::class,
        'URL' => Illuminate\Support\Facades\URL::class,
        'Validator' => Illuminate\Support\Facades\Validator::class,
        'View' => Illuminate\Support\Facades\View::class,

    ],
];


via Chebli Mohamed

vendredi 3 février 2023

Laravel copy and move not working with large file(10GB) with s3

Small files (up to 1 GB) are successfully transferred but large files return false on the move and copy functions.

both functions should work correctly for large files as well.

My code

try {
       //dd($param);
       $s3 = Storage::disk('s3');
       $dd = $s3->move($param['source'], $param['target']);
       dd($dd);
    } catch (Exception $e) {
       return [
          "status" => 0,
             "msg" => $e->getMessage(),
         ];
   }


via Chebli Mohamed

mercredi 1 février 2023

laravel dynamic routing showing 404 not found

I have created a route to pass dynamic parameters to controller but when i serve url it shows me for not found here is my route and controller I create

Routes

Route::get('/admin/managers/{method}/{id}', 
    [
        SetupController::class, 'managers'
    ]
);

Controller

public function managers($method, $id) {
        if($method == 'create') {
            return view('admin.pages.create-manager'); 
        } elseif($method == 'create') {
            echo $id;
            return view('admin.pages.create-manager'); 
        } else {
            return view('admin.pages.managers'); 
        }  
    }

When i serve url localhost/public/managers it shows me 404 not found but when i serve localhost/public/managers/create/1 the page is loading then can anyone hep me out why exactly is it happening



via Chebli Mohamed

Random project chooser for laravel

today I have two similar Laravel projects, they are exactly the same except for the Laravel version, the first is running on 5.5, and the second is the updated version running on Laravel 9. The Laravel 9 one is not in production because we need a way to test it and check if everything is working after the update. My question is if there's a way to redirect to some clients only the newer version. The projects for the clients are exactly the same.

In conclusion I need a way to show to like 20% of the clients the newer version, and the older version for the other 80%, is possible to do this? Is there a better way to test the newer project for errors?

Thanks in advance.



via Chebli Mohamed