dimanche 31 juillet 2022

Guzzle Laravel simple connection and errors checker

Im using Guzzle on a laravel Project, I want to have a working validation for Api connection and error checker, Also want to keep a sequence while checking, for example, first check the connection if its 200 if isnt then show the Connection error message. If is 200 then proceed to second check that checking if has errors from the remote server like "duplicate ID" then show the error message. If has no error then make the POST or GET request is it possible that? because now when i run this im getting error regarding variable $errormsg error:

 Trying to get property 'error' of non-object

And thats happened because if hasn't errors on server response the field strval(simplexml_load_string($response)->response->errors->error->message) doesnt exist on xml , so is it possible to check if that field is empty or not without getting error?

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

Updating an existing record via Laravel eloquent throws exception

I'm struggling to update record in my table using Laravel 5.5. I, basically, have a table that contains a column named status and I'm trying to update the status like this:

public function updateMatchStatus(Request $request) {
        try{
            $match = Match::find($request->id);
            $match->status = $request->status;
            $match->save();
            return response(["message" => "Match status updated"], 200);
        }
        catch(Exception $e){
            return response(["message" => "Error updating match status"], 500);
        }
    }

I have tested and checked the request and it contains the data, it succesfully finds the record to be updated but as soon as I try calling save() it throws exception. I have also tried:

Match::where('id',$request->id)->update(['status' => $request->status]);

Both throw same error:

{
    "message": "SQLSTATE[23514]: Check violation: 7 ERROR:  new row for relation \"matches\" violates check constraint \"matches_status_check\"\nDETAIL:  Failing row contains (7d6dfaa9-c6f6-4548-b9d3-4ddc11137103, E, 2022-07-17 00:00:00, 2022-07-23 00:00:00, 102, 108, PROCESSED, 2022-07-17 18:27:17, 2022-07-27 20:02:47, 5735, 75, 170722-230722, MLB, 16, null). (SQL: update \"matches\" set \"status\" = PROCESSED, \"updated_at\" = 2022-07-27 20:02:47 where \"id\" = 16)",
    "exception": "Illuminate\\Database\\QueryException",
    "file": "/directories/projec/vendor/laravel/framework/src/Illuminate/Database/Connection.php",
    "line": 664,
    "trace": [
        {
         ...
        }
    ]

I am using PostgreSQL. I am unable to understand what possibly is wrong here.



via Chebli Mohamed

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

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 a variable, 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

samedi 23 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

vendredi 22 juillet 2022

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

lundi 18 juillet 2022

laravel 5.7 job instance create but not execute

I have created jobs for video converting and updating in database in Laravel 5.7. All created jobs work correctly but any new job I am create in that only instance create but not execute. I have created one test email job with log entry.

My env file changes: .env

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120

In config folder: queue.php

'default' => env('QUEUE_CONNECTION', 'sync'),

'connections' => [

        'sync' => [
            'driver' => 'sync',
        ],

        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'retry_after' => 400000,
        ],

Job called by cron job custom command: TestEmail.php

MatchSendEmail::dispatch()->onQueue('queue_test');

My test mail job: MatchSendEmail.php

namespace App\Jobs;
use Mail;
use App\Mail\EmailTest;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class MatchSendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        app('log')->info('supervisor send mail for all construct->');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        app('log')->info('supervisor send mail for all handle');
        $email = new EmailTest();
        Mail::to(['******@gmail.com', 'ravi@****.com'])->send($email);
        app('log')->info('supervisor send mail for all handle1');
    }
}

I have used supervisor for background process and below is configuration file:

[program:queue_test]

process_name=%(program_name)s_%(process_num)02d

command=php /home/web1/******.com/htdocs/artisan queue:work --tries=10 --sleep=5

autostart=true

autorestart=true

user=web1

numprocs=20

redirect_stderr=true

stdout_logfile=/home/web1/******.com/htdocs/storage/logs/queue_test.log

Only job instance creates but not execute, please guide me how this issue resolve.



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

How to do a surgery on an Eloquent Query on-the-fly

is there any way to interrupt and change the components and scopes of an eloquent query?

in order to add multitenancy to an existing project, I've added a global scope to my models, filtering results by tenant_id. and it works fine.

the problem is I have found more than 500 hardcoded 'where conditions ' and 'create statements' all over the place. such as these:

$notification_type= NotificationTypes::where('id', '2')->get();

or

$tickets = Tickets::create( $title, $body, $sender, '1'); // 1 as statusID

etc.

It's a problem because I'm using the single DB approach for multitenancy and these IDs must be relative to the tenant. for Example in the first query above, I don't want the 'NotificationTypes' with Id of '2', But I want the 'second' NotificationType with that tenant_id (id of this column could be 4 or 7 or else).

I can figure out a way to properly calculate the exact amount of these Relative IDs. but is there any way to find the prior scope and conditions of an eloquent object and change them?

I'm looking for a way to add multitenancy to the project without changing much of the existing code. like a module or plugin.



via Chebli Mohamed

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",



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

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