dimanche 31 juillet 2022

Laravel SwitMessage add Reply-path header

We have a Laravel application which sends newsletters to customers. As per the client's request, we would like to add a header in the email indicating that it's a newsletter or mail to a list to avoid out of office email bounces. Upon research, I found that one way to do so is to add Precedence: bulk header. But answer also says that RFC 2076 discourages adding Precedence header. Some post recommend adding Return-Path: <> (a NULL Return-Path). However, I'm not able to add this header. I have tried following codes to add such a header but not working.

$headers->addTextHeader('Return-Path', ''); - Uses the mail id defined in config file 
$headers->addTextHeader('Return-Path', '<>') - This generates a malformed header as in the attached image
$headers->addTextHeader('Return-Path', ' '); - Adds a header like Return-Path   
< > but not sure if this is correct or it will create other issues


via Chebli Mohamed

Guzzle Laravel simple connection and errors checker

Im using Guzzle on a laravel Project, Im want to have a working connection validation and error checker if has errors, also want first check the connection if its 200 if isnt then show the error message, if is 200 then proceed to second check that checking if has Error from the remote server like "duplicate ID" if has no error then make the POST or GET request is it possible that? because now when run this get error on $errormsg

My function:

  public function showinvoice()
    {
        $client = new \GuzzleHttp\Client([
            'http_errors' => false,
            'headers' => [
                'aade-user-id' => 'blabla',
                'Ocp-Apim-Subscription-Key' => 'blablabla',
               
            ]
        ]);

        $request = $client->GET('https://mydatapi.aade.gr/myDATA/RequestMyExpenses/?dateFrom=11/11/2021&dateTo=11/12/2022');

        $response = $request->getBody()->getContents();

        $reasonPhrase = $request->getReasonPhrase();

        $statusCode = $request->getStatusCode();
        $errormsg = strval(simplexml_load_string($response)->response->errors->error->message);
        if ($statusCode <= 200) { 

            if (isset($errormsg)) {

                $this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => $errormsg]);
            }
            else{
               return $response;
            }
   
        } 
        else {
            $this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => $statusCode .' '. $reasonPhrase]);
        }
    }
    ```


via Chebli Mohamed

jeudi 28 juillet 2022

Laravel Grouping a list of todos into one folder

Please I am trying to group a list of todos by selecting them and grouping them into one link. so when I click on the link I will be able to see all the todos I selected and added to the group. how can I do that? I have been able to add these codes but I do not know how to move forward because I am quite new to laravel. here are my codes

 <tbody>
                @foreach($todos as $todo)
                    <tr>
                        <td><input type="checkbox" name="selected_todos[]" value=""></td>
                        @if($todo->completed)
                            <span><td style="text-decoration:line-through"></td></span>
                        @else
                            <td></td>  
                        @endif     
                        <td></td>
                        <td></td>
                        <td><a class="btn btn-primary" href="" role="button" ><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pen" viewBox="0 0 16 16">
                            <path d="m13.498.795.149-.149a1.207 1.207 0 1 1 1.707 1.708l-.149.148a1.5 1.5 0 0 1-.059 2.059L4.854 14.854a.5.5 0 0 1-.233.131l-4 1a.5.5 0 0 1-.606-.606l1-4a.5.5 0 0 1 .131-.232l9.642-9.642a.5.5 0 0 0-.642.056L6.854 4.854a.5.5 0 1 1-.708-.708L9.44.854A1.5 1.5 0 0 1 11.5.796a1.5 1.5 0 0 1 1.998-.001zm-.644.766a.5.5 0 0 0-.707 0L1.95 11.756l-.764 3.057 3.057-.764L14.44 3.854a.5.5 0 0 0 0-.708l-1.585-1.585z"/>
                            </svg></a></td>
                        <td><a class="btn btn-danger" href="" role="button" ><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16">
                            <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
                            <path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
                            </svg></a></td>
                        @if($todo->completed)
                            <td><a class="btn btn-info" href="" role="button" ><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bag-x" viewBox="0 0 16 16">
                                <path fill-rule="evenodd" d="M6.146 8.146a.5.5 0 0 1 .708 0L8 9.293l1.146-1.147a.5.5 0 1 1 .708.708L8.707 10l1.147 1.146a.5.5 0 0 1-.708.708L8 10.707l-1.146 1.147a.5.5 0 0 1-.708-.708L7.293 10 6.146 8.854a.5.5 0 0 1 0-.708z"/>
                                <path d="M8 1a2.5 2.5 0 0 1 2.5 2.5V4h-5v-.5A2.5 2.5 0 0 1 8 1zm3.5 3v-.5a3.5 3.5 0 1 0-7 0V4H1v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V4h-3.5zM2 5h12v9a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V5z"/>
                                </svg></a></td>
                        @else
                            <td><a class="btn btn-success" href="" role="button" ><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bag-check" viewBox="0 0 16 16">
                                <path fill-rule="evenodd" d="M10.854 8.146a.5.5 0 0 1 0 .708l-3 3a.5.5 0 0 1-.708 0l-1.5-1.5a.5.5 0 0 1 .708-.708L7.5 10.793l2.646-2.647a.5.5 0 0 1 .708 0z"/>
                                <path d="M8 1a2.5 2.5 0 0 1 2.5 2.5V4h-5v-.5A2.5 2.5 0 0 1 8 1zm3.5 3v-.5a3.5 3.5 0 1 0-7 0V4H1v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V4h-3.5zM2 5h12v9a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V5z"/>
                                </svg></a></td>
                        @endif 
                    </tr>
                @endforeach
            </tbody> 
  public function todos()
    {
        return $this->hasMany(TodoList::class);

    }
    public function GroupTodoList()
    {
        return $this->belongsTo(GroupTodoList::class);

    }

and I have not included a controller for the grouping because I do not know how to go about it.

Thank you



via Chebli Mohamed

mercredi 27 juillet 2022

Could not load mock: class already exists when run with RefreshDatabase Trait

public function testSomething()
{
    $this->login();

    m::mock('overload:MyClass', function ($mock) {
        $mock->shouldReceive('METHOD')
            ->andReturn(
                (object)[
                    'status'  => true,
                    'message' => 'Message',
                ]
            );
    });

    $this->post(route('ROUTE'))
        ->assertRedirect()
        ->assertSessionHas(
            'success',
            'Message'
        );
}

When I try to run this with:

use DatabaseTrasactions: It works

use RefreshDatabase: It does NOT work

Error: Mockery\Exception\RuntimeException : Could not load mock \MyClass, class already exists

Laravel: 5.5 PHPUnit: 6.5.14

Tried

  • @runTestsInSeparateProcesses (on entire class)
  • @runInSeparateProcess (on single test)


via Chebli Mohamed

Laravel 5.5.50 not resetting password

Good day programmers, I'm using laravel 5.5.50 and I don't intend to reinvent the wheel so I'm using the default password reset. Normally everything goes fine;

  1. I clicked on forgot password
  2. I put my email and send password reset link
  3. I go to my email and click the link
  4. The link takes me to reset page then I put my new password
  5. The password change is successful then it redirects me to my user dashboard

But when I logout and login again with the new password, it says incorrect. In fact the password was not changed at all. How do I rectify this please. I am new to laravel



via Chebli Mohamed

dimanche 24 juillet 2022

Auth::user() always return null

recently I have installed spatie/permissions in a fresh Laravel 9 installation. before I install this package whenever I called Auth::user() it returns back with the result with the currently authenticated user. but now after I installed spatie/permissions it always returns null in any controller, but it's working normally in views.

is there anyone have the same issue here. and how he managed to fix it.



via Chebli Mohamed

samedi 23 juillet 2022

Data Pass from controller to view

I want to display sum of column debit but when i pass data after sum value of column store in varibale, I pass the data from controller to view but laravel said its undefined can anyone help me with this ?

View.blade.php

                      <tr>
                        <th>Total Debit:</th>
                        <td>
                          @foreach ($totaldebit as $tdebit)
                          
                          @endforeach
                        </td>
                      </tr>

UserController.php

$tdebit = DB::table('debitemps')->sum('debit');
        return view('pages/payments/debit/debit',['workerlists'=>$data,'debitid'=>$id,'Empdebitdata'=>$dataEmp,'totaldebit'=>$tdebit]);


via Chebli Mohamed

vendredi 22 juillet 2022

laravel i want to show count and with there name

laravel I'm trying to get count row and its value.

model name Result

example THIS DATA STORED IN DATABASCE

NAME    SUBJECT        RESULT 
 A        HX            PASS  
 B        HX            FAIL
 C        DX            PASS
 D        DX            PASS
 E        MR            FAIL

I want to show value like blade this

in table

SUBJECT   PASS    FAIL
  HX       1       1
  DX       2       0
  MR       0       1 


via Chebli Mohamed

Select2 dropdown menu appears but the option does not

I need to display out a list of Models in a dropdown menu using jQuery Select2 function in which I have zero knowledge in. My problem is that the dropdown menu appeared in the page, however the option doesn't. Technically, it seems that it does appear but I just can't see it.

As you can see in the image below, the dropdown menu does appear in the page and I can expand the dropdown. However, the contents aren't visible.

Image

This is in my view for the dropdown menu part:

@section('js') <script src=""></script>

<script type="text/javascript">
    $('#model_id').select2({
        dropdownParent: $('#model_id')
        }
    ); </script>

<script>

$(document).ready(function(){

    var count = 1;
    dynamic_field(count);

    function dynamic_field(number){
    html = '<tr>';
        html += '<td>'+number+'<input type="hidden" name="row[]" value="'+number+'"></td>';    
        html += '<td><div class="form-group"> <select name="model_id[]" id="model_id" class="select2 form-control" required> <option value="" >Please select the model</option> @foreach ($model as $mod) <option value=""></option> @endforeach </select> @if($errors->has('model_id')) <div class="invalid-feedback">  </div> @endif <span class="help-block"></span> </td>';
        html += '<td><input id="quantity" type="number" min="1" name="quantity[]" class="form-control" required/></td>';
        html += '<td><input id="remark" type="text" name="remark[]" class="form-control" placeholder=""/></td>';
        if(number > 1)
        {
            html += '<td><button type="button" name="remove" id="" class="btn btn-danger remove">Remove</button></td></tr>';
            $('tbody').append(html);
        }
        else
        {
            html += '<td><button type="button" name="add" id="add" class="btn btn-success">Add</button></td></tr>';
            $('tbody').append(html);
        }
    }

    $(document).on('click', '#add', function(){
    count++;
    dynamic_field(count);
    });

    $(document).on('click', '.remove', function(){
    count--;
    $(this).closest("tr").remove();
    });

    $('form').submit(function(){
            $(this).find(':input[type=submit]').prop('disabled', true);
    }); }); </script>

@stop

I have found a solution saying that I need to increase the z-index but it's still not working. I hope you guys can help me with this.



via Chebli Mohamed

jeudi 21 juillet 2022

'View [] not found' only with Laravel Command

I have an application which has a command scheduled to run every minute to update catalogs status and it should send an email upon a new book being found, somehow when the mailer sends the email it triggers the 'View not found'.

The Laravel Command has a function that calls another function in a controller. However when a route is made pointing to the same controller it works fine i.e sends an email.

It is only when the controller func is called from the Command that it doesn't find the email template view file.

The view file is present as it runs correctly when the route is used.

Any idea what amendments I need in my command?



via Chebli Mohamed

Compare array and object in php without foreach [closed]

I want to compare arrays and objects in my PHP website. Currently, I am using foreach for comparison. But, it takes a long time for heavy data.

Is any other ways to compare array and object?



via Chebli Mohamed

I can't install spatie/laravel-sitemap on Laravel 5.6

I'm getting this error when installing:

Your requirements could not be resolved to an installable set of packages.

Problem 1 - spatie/laravel-sitemap[5.9.0, ..., 5.9.2] require illuminate/support ^8.0 -> found illuminate/support[v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require. - Root composer.json requires spatie/laravel-sitemap ^5.9 -> satisfiable by spatie/laravel-sitemap[5.9.0, 5.9.1, 5.9.2].

You can also try re-running composer require with an explicit version constraint, e.g. "composer require spatie/laravel-sitemap:*" to figure out if any version is installable, or "composer require spatie/laravel-sitemap:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.



via Chebli Mohamed

mercredi 20 juillet 2022

How to custimization laravel nova page manager package

I need help for laravel nova page manager package.I want apply duplicate functionality for Nova template index page.



via Chebli Mohamed

How to update IMAGE in laravel?

I have tried many ways to update image but its not working at all though I can update other data except image.

code for saving Image and other inputs

 public function store(Request $request)
{

    $fileName = null;
    if($request->file('image')){
        $fileName = strtotime(Carbon::now());
        $fileName = $fileName.".".$request->file('image')->extension();
        $uploadPath = (public_path($this->uploadPath."/".$fileName));
        move_uploaded_file($request->file('image'), $uploadPath);
    }
        $data = $request->all();
        $data['image'] = $fileName;
    if(Covidrecord::create($data))
    {
        return redirect()->route('store')->with(['msg'=>"User create successfully"]);
        return redirect()->route('store')->withError(['msg'=>"User cannot be registerd at the moment"]);

    }
}

Code for UPDATING

  public function update(Request $request,Covidrecord $covidrecord, $id)
    {
        $data = Covidrecord::find($id);

    $fileName = null;
    if($request->file('image')){
        $fileName = strtotime(Carbon::now());
        $fileName = $fileName.".".$request->file('image')->extension();
        $uploadPath = (public_path($this->uploadPath."/".$fileName));
        move_uploaded_file($request->file('image'), $uploadPath);
    }
        $data = $request->all();
        $data['image'] = $fileName;
        $covidrecord->update($request->all());

        return redirect()->route('allrecord')->with(['msg'=>"User create successfully"]);

}

Blade

 <div class="input-group">
  <input class="form-control" type="file" placeholder="Upload Image" name="image" >
   <img src=""
   </div>
   </div>


via Chebli Mohamed

Laravel 5.6 Error on clicking the Patient list when creating a new doctor account

question 1.I have a thesis project about a certain clinic, I have a default users in my database, The default doctor doesn't have any problems or errors, but when i create a new doctor account, and when i click the patient list I get this error

Undefined variable: patient (View:C:\Users\patri\OneDrive\Desktop\Megason_noOTP\resources\views\patient-management\list.blade.php)

Please help TIA!!

    enter code here


public function index(){
    $user = User::where('id', Auth::user()->id)->with('usertype','usertype.permissions')->get();
    $permissions = [];
    foreach($user[0]->usertype->permissions as $permission)
    {
        array_push($permissions, $permission->name);
    }

    $patients = $this->getPatients();

    $data = array(
        'permissions' => $permissions,
        'patients' => $patients
    );

    return view('patient-management.list')->with('data',$data);

}

public function getPatients(){
    if(Auth::user()->type == 2){
        return PatientDetail::where('doctor_id', Auth::user()->id)->with('doctor.doctorDetails','user')->get();
    }else if(Auth::user()->type == 3){
        return PatientDetail::where('user_id', Auth::user()->id)->with('doctor.doctorDetails','user')->get();
    }
    else{
        return PatientDetail::with('doctor.doctorDetails','user')->get();
    }
}


via Chebli Mohamed

vendredi 15 juillet 2022

laravel products with the highest sales will be displayed at the top

I am trying to sort products with the highest sales will be displayed at the top. Do I need to improve it? or is it correct enough to get sorted products with highest sales?

Here is my sort query

    $data = Product::query();
    if ($category_id) {
        $data->where('category_id', $category_id);
    }
    if ($theme_id) {
        $data->Where('theme_id', 'LIKE', '%' . $theme_id . '%');
    }
    if ($sub_category_id) {
        $data->where('sub_category_id', $sub_category_id);
    }

    $data = $data->leftJoin('order_items', function ($join) {
              $join->on('products.id', '=', 'order_items.product_id');
    })
    ->selectRaw('products.*, sum(order_items.id) as total')
    ->groupBy('products.id')
    ->orderByDesc('total');

    $products = excludeProductLessThanZero($data->paginate($this->paginationcount));

products table

enter image description here

**Orders table**

enter image description here

**order_items**

enter image description here

All three tables database structure is given above. Please guide and suggested. Thanks



via Chebli Mohamed

mardi 12 juillet 2022

multithreading Laravel [closed]

Hey Guys, I need help with an assignment.

It is necessary to implement a service that provides a REST API for hashing:

Create a task;

Getting the status of task completion;

Stop task execution;

Create a task group;

Obtaining the status of the execution of a group of tasks;

Stopping the execution of a group of tasks;

List of all tasks;

group tasks are executed in the priority queue

There is an idea to use Rabbitmq



via Chebli Mohamed

lundi 11 juillet 2022

Login with Linkedin shows error "The Application is disabled" Laravel

I'm integrating LinkedIn with socialite in laravel

I got this error when logging in with LinkedIn "The application is disabled". Can you help identify the issue if ever I missed something? Thanks alot

  "laravel/framework": "5.7.*",
  "laravel/socialite": "^4.4",

The application is disabled - LinkedIn The application is disabled - LinkedIn



via Chebli Mohamed

Splitting methods between controllers

I currently have a controller that is beginning to grow out of control. I'm now going to split it into separate controllers to make it easier to manage and maintain. This is legacy code and therefore, unfortunately, is running laravel 5.2. Upgrading laravel and php version is not an option at the current stage.

Is the following approach ok? Or is there a better way of doing this?

Current Approach

class StoreDistributionData extends Controller
{
    public function method1()
    {
        // code
    }

    public function method2()
    {
        $array = [];
        // lots of logic building above array

        $this->method3($array);
    }

    public function method3($array)
    {
        // code relating to above array
    }

    public function method4($array)
    {
        foreach($array as $k => $v) {
            // more logic
        }
        // more logic using various methods
    }

    // more methods and code
}

Revised Approach

class FormatDistributionData extends Controller
{
    public function method1()
    {
        // code
    }

    public function method2()
    {
        $array = [];
        // lots of logic building above array

        app(StoreDistributionData::class)->splitData($array);
    }
}

class StoreDistributionData extends Controller
{
    public function splitData($array)
    {
        // code relating to above array processed/stored using internal methods
    }

    // more methods
}


via Chebli Mohamed

vendredi 8 juillet 2022

Too few arguments to function App\Http\Controllers\ProduitController::show()

I wants to show users list into my dashboard pannel but it shows me this problem :

Too few arguments to function App\Http\Controllers\ProduitController::show(), 0 passed in C:\wamp64\www\Ecommerce\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 1 expected

Controller File :

public function show($id)
{   
    $produit = Produit::find($id);
    return view('produits', compact('produit'));
}

blade file :

@foreach($produits as $produit)
    <div class="product__item__pic set-bg" data-setbg="">
        <ul class="product__item__pic__hover">
            <li><a href="#"><i class="fa fa-heart"></i></a></li>
            <li><a href="#"><i class="fa fa-retweet"></i></a></li>
            <li><a href="#"><i class="fa fa-shopping-cart"></i></a></li>
        </ul>
    </div>
    <div class="product__item__text">
        <h6><a href="#"></a></h6>
        <h5> Mad</h5>
    </div>
@endforeach 

Route :

Route::get('/produits','ProduitController@show');


via Chebli Mohamed

Failed to install npm for laravel 5.6

npm ERR! gyp ERR! cwd C:\Users\abc\Desktop\Project\council\node_modules\node-sass npm ERR! gyp ERR! node -v v16.16.0 npm ERR! gyp ERR! node-gyp -v v3.8.0 npm ERR! gyp ERR! not ok npm ERR! Build failed with error code: 1

npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\abc\AppData\Local\npm-cache_logs\2022-07-08T11_43_43_669Z-debug-0.log



via Chebli Mohamed

jeudi 7 juillet 2022

Install mpdf v8.0.4 for php 7.4 Version

I am running on PHP v 7.4 after an upgrade from the 7.1 version I am having issues on install mpdf v8.0.4 since its compatible with php 7.4 version

The error facing after ruuning composer update

 mpdf/mpdf[v7.0.0-beta1, ..., v7.0.0-beta2] require php ^5.6 || ~7.0.0 || ~7.1.0 -> your php version (7.4.19) does not satisfy that requirement.

running these two commands turns unsuccessfully

composer require mpdf/mpdf v8.0.4
composer require mpdf/mpdf dev-php7-support 


via Chebli Mohamed

Error 520 Web server is returning an unknown error AWS (Laravel)

I have AWS EC2 Instance and installed Laravel in that but i getting this error when multiple time hits URL.

We have also solution for that when we remove cookie problem is resolved but are not go with this solution. Is there any solution for that



via Chebli Mohamed

mercredi 6 juillet 2022

javascript-jquery-fancytable next page dont show table

I'm strugling with fancyTable pagination. The table renders all rows in two pages but the first click in my page 2 or 3 the table gets hidden and when I click again in that page the table appears with the data. What's my problem? I'm using this fancyTable in my laravel project, and I render the results in a for each I0m not using a js function to render the fancyTable. Anyone with the same problem?

table style="margin-top: 20px;"  id="tabelaAssistencia">
    <thead>
        <tr>
            <th scope="column" style="text-align:center">Entidade</th>
            <th scope="column" style="text-align:center" data-sortas="numeric">Numero</th>
            
        </tr>
    </thead>
    <tbody>
        @if (count($results) > 0) @foreach ($results as $r)
        <tr>
            
                <td class="active-apply"></td>
            @endif
            <td class="active-apply"></td>
            
            @endforeach @endif  
    </tbody>
</table>


<script type="text/javascript">
   $(document).ready(function(){
    
        $("#tabelaAssistencia").fancyTable({
            sortColumn:1,// column number for initial sorting
            sortOrder:'asc',// 'desc', 'descending', 'asc', 'ascending', -1 (descending) and 1 (ascending)
            sortable:true,
            pagination:true,// default: false
            searchable:true,
        //  globalSearch:true,
        //  globalSearchExcludeColumns: [2,5],// exclude column 2 & 5,
            paginationClass:"btn btn-light",
            paginationClassActive:"btn-active",
            perPage: 15,
            inputStyle:"color:black!important;font-size:14px",
            inputPlaceholder:"Introduza o que pretende procurar..."
        });
    });
</script>


via Chebli Mohamed

laravel inside with leftjoin is not working

I have added left join inside with but it is not working at all. Please suggest or guide.

$q = $q->leftJoin('product_sort_order', function ($join) {
 $join->on('products.id', '=', 'product_sort_order.product_id');
 $join->on('products.sub_category_id', '=', 'product_sort_order.type_id');
})->orderBy('product_sort_order.sort_order', 'ASC');

Controller code (trying to get category products with relationship)

$category = Category::query();
        $category->where('status', '=', '1');
        $category->where('id', $sub_category_id);
        // $category->where('status', '!=', '2');
        $category = $category->with([
            'subproducts' => function ($q) use ($request, $sub_category_id) {
                $q->select('products.*');
                $q->where('products.status', '=', 1);
                $q->where('products.is_pendding', '=', 0);
                $q->where('products.sub_category_id', $sub_category_id);
                if ($request->get('theme')) {
                    $q->Where('products.theme_id', 'LIKE', '%' . $request->get('theme') . '%');
                }
                if ($request->get('categories')) {
                    $q->where('products.category_id', getCategoryIdFromSlug($request->get('categories')));
                }
                if ($request->get('sections')) {
                    $q->where('products.section_category_id', getSectionIdFromSlug($request->get('sections')));
                }
                if ((App::getLocale()) == 'en') {
                //    $q->orderBy('product_name_lang->en');
                } else {
                //    $q->orderBy('product_name_lang->fr');
                }
                if ($request->get_j0_product == true) {
                    $q->where('products.delivery', 'J0');
                }
                // $q->orderBy('sale_price', 'DESC');
                // $q->orderBy('created_at', 'DESC');

                // $q = $q->leftJoin('product_sort_order', function ($join) {
                //         $join->on('products.id', '=', 'product_sort_order.product_id');
                //         $join->on('products.sub_category_id', '=', 'product_sort_order.type_id');
                //      })->orderBy('product_sort_order.sort_order', 'ASC');


            }
        ])->first();

model relationship inside category

 public function subproducts(){
  return $this->hasMany(Product::class,'sub_category_id','id');
 }


via Chebli Mohamed

Cypress with laradock

I've setup a laravel project with laradock. Project can be accessed from url http://blog.localhost

I have written a sample test file to visit the application url but I get the following error.

enter image description here

How do I setup cypress to visit my project URL ?



via Chebli Mohamed

laravel query to sort product based on other database table

Sorting product We have two tables

  1. products(contain all products)
  2. product_sort_order (see below screenshot) (table contain sorted products with column sort_order)

I need to display sorted products with the help of sort_order in product_sort_order table.Simple is that. What modification should I do to get sorted results from product_srot_order tables. Please suggest some solutions.

enter image description here

Note: section = third level of category

    $q = Product::query();
    $q->where('sub_category_id', $sub_category_id);
    $q->where('status', '=', 1);
    $q->where('is_pendding', '=', 0);
    // $q->where('status', '=', 1);

    $q->where('sub_category_id', $sub_category_id);
    // offer check.
    if ($request->get('theme')) {
        $q->Where('theme_id', 'LIKE', '%' . $request->get('theme') . '%');
    }
    // category check.
    if ($request->get('categories')) {
        $q->where('category_id', getCategoryIdFromSlug($request->get('categories')));
    }

    if ($request->get('sections')) { // third level of category

        $q->where('section_category_id', getSectionIdFromSlug($request->get('sections')));
     
       

    }

    // product language
    if ((App::getLocale()) == 'en') {
        // $q->orderBy('product_name_lang->en');
    } else {
        // $q->orderBy('product_name_lang->fr');
    }

    if ($request->get_j0_product == true) {
        $q->where('delivery', 'J0');
    }
    

    $products = $q->paginate($this->paginationcount);

    $data['paginationproducts'] = (excludeProductLessThanZero($products));


via Chebli Mohamed

mardi 5 juillet 2022

After click on print function() in javascript if I cancle print window my dashboard sidebar dropdown not working

After click on print function() in javascript if I cancle print window my dashboard sidebar dropdown not working.enter image description here

This error is showing in console. enter image description here



via Chebli Mohamed

SQLSTATE[HY000] [2002] Connection timed out (SQL: select * from `sessions` where `id` = Me2dEG11Zq4pJBhzCoWlhZwZuWPebKdGPLyhuleg limit 1)

I have a problem, my web site was working without problems, but when I enter any product, the web site does not work and gives this error I made

php artisan cache:clear
php artisan key:generate
php artisan cache:clear
php artisan make:command FlushSessions
php artisan session:flush

And I Deleted the data into the sessions table inside the Database But the problem has not been resolved



via Chebli Mohamed

getting infinite loop - adding scope on user model with traits

after adding the following trait to the user model, I get a 500 error because of an infinite loop.

    trait Multitenantable
    {
        public static function bootMultitenantable()
        {
            static::addGlobalScope('tenant_id', function (Builder $builder) {
                $tenant_id = 1;
                if ( auth()->check() )
                {
                    $tenant_id = Auth::user()->tenant_id;
                }
    
                $builder->where('tenant_id', '=', $tenant_id);
            });
        }
    }

when I remove either the trait from the user model or the if containing the auth() part (lines 7,8,9,10) from this trait, the infinite loop resolves.

I'm not familiar with the magic behind laravel, could someone explain why this happens?

and how I could add global scope for multitenancy to the user model like the others?

I've followed this instruction to add multitenancy to my laraval project.



via Chebli Mohamed

lundi 4 juillet 2022

Laravel ReflectionException : Class CustomerAccountController does not exist

I have this project on Laravel 5.7 and Voyager on WAMP with 2 issues, the first one is when I run php artisan route:list and the result is:

 ReflectionException  : Class CustomerAccountController does not exist
 at C:\wamp64\www\cell_marketplace\vendor\laravel\framework\src\Illuminate\Container\Container.php:779

And actually the class exists and I'm using its functions on another processes and it's working, I've checked namespace, ran composer dump-autoload with no results.

The second one, I've created a BREAD on Voyager, and I got the model class and controller class, but when I go to the index of that resource again got this:

 ReflectionException: Class DropOffController does not exist in \vendor\laravel\framework\src\Illuminate\Container\Container.php:779

And the controller exists and has a function that it's actually working, so I think that's related with the first one but if anybody can help I'd really appreciate it



via Chebli Mohamed

whereJsonContains is not working with array of strings

I have a JSON stored on to my table column valid_dates:

{"weeks": [8], "endDate": "2022-06-02", "startDate": "2022-07-03"}

I am generating dates range by:

$from = Carbon::now()->addDays(-200);
        $from = Carbon::now()->addDays(-200);
        $to = Carbon::now();
        $past_dates = CarbonPeriod::create($from, $to)->toArray();
        $date_strings = [];
        foreach ($past_dates as $date) {
            $date_strings[] = $date->format('Y-m-d');
        }

Now when I have all the date in $date_strings array according to the format in database, when I try to query it via whereJsonContains():

->whereJsonContains('valid_dates->startDate',[$date_strings]) // this doesn't work

Nothing is returned however there are records with matching dates, but the opposite is the case when I try using a single date here as:

->whereJsonContains('valid_dates->startDate','2022-07-03') //this works

I wonder what could I be missing here, I have also checked Laravel docs and found the syntax similar to what I have.

Moreover is there any relaible way to compare data in whereJsonContains() using operators?



via Chebli Mohamed

dimanche 3 juillet 2022

can we use payment network tokenization in the backened code?

as a part of our project we would like to implement a few more functionalities like Apple Pay,Google Pay and PayPal using autherize.net for billing payment transactions. In our project we already implemented autherize.net for card payments. Payment methods are implemented in the backend code side (using Laravel 5.5) with autherize.net APIs.There is no front end code interactions for card payment. User details needed for billing payments like Card details, auth_customer_id etc are fetched (today's user payment transaction due ) by running a crone job everyday. In Autherize.net documentation it is written Apple Pay uses payment network tokenization. We would like to know, is it possible to use payment network tokenization in the backend development(using Laravel 5.5) to implement Apple Pay,Google Pay, PayPal for billing payment transactions.



via Chebli Mohamed

vendredi 1 juillet 2022

how to use custom rule in middleware of laravel 9.x?

NOTE: this is for an endpoint. not for a form request.

let's say I have middleware named Inputs which has this code in the handle()

public function handle(Request $request, Closure $next) {

  $data = $request->all();
   
  foreach ($data as $array) {
      //HOW TO USE THE CUSTOM RULE HERE?
  }
  return next($request);

}

here's the custom rule App\Rules

class MyRule {


  public function construct() {}

  public function passes($attribute, $value) {
       if ($value > 1) {
          return false;
       }
      return true;
  }

  public function message() {
      return "data invalid";
  }

}


via Chebli Mohamed