samedi 31 octobre 2020

Getting a 500 Internal Server Error Jquery

While everything is running in the software, I get this error when I make a selection from the dropdown list in only one part. Where am I making a mistake? or is it a server error? I have not received this error in any Laravel before. When trying to get something from a dropdown list, this error comes to the console and there is no reaction on the site.

https://prnt.sc/vaujzf

<script type="text/javascript">
$("ul#product").siblings('a').attr('aria-expanded','true');
$("ul#product").addClass("show");
$("ul#product #adjustment-create-menu").addClass("active");

var lims_product_array = [];
var product_code = [];
var product_name = [];
var product_qty = [];

$('.selectpicker').selectpicker({
style: 'btn-link',
});

$('#lims_productcodeSearch').on('input', function() {
var warehouse_id = $('#warehouse_id').val();
temp_data = $('#lims_productcodeSearch').val();

if (!warehouse_id) {
    $('#lims_productcodeSearch').val(temp_data.substring(0, temp_data.length - 1));
    alert('Please select Warehouse!');
}
});

$('select[name="warehouse_id"]').on('change', function() {
var id = $(this).val();
$.get('getproduct/' + id, function(data) {
    lims_product_array = [];
    product_code = data[0];
    product_name = data[1];
    product_qty = data[2];

    $.each(product_code, function(index) {
        lims_product_array.push(product_code[index] + ' (' + product_name[index] + ')');
    });
});
});

var lims_productcodeSearch = $('#lims_productcodeSearch');

lims_productcodeSearch.autocomplete({
source: function(request, response) {
    var matcher = new RegExp(".?" + $.ui.autocomplete.escapeRegex(request.term), "i");
    response($.grep(lims_product_array, function(item) {
        return matcher.test(item);
    }));
},
response: function(event, ui) {
    if (ui.content.length == 1) {
        var data = ui.content[0].value;
        $(this).autocomplete( "close" );
        productSearch(data);
    };
},
select: function(event, ui) {
    var data = ui.item.value;
    productSearch(data);
}
});

$("#myTable").on('input', '.qty', function() {
rowindex = $(this).closest('tr').index();
checkQuantity($(this).val(), true);
});

$("table.order-list tbody").on("click", ".ibtnDel", function(event) {
rowindex = $(this).closest('tr').index();
$(this).closest("tr").remove();
calculateTotal();
});

$(window).keydown(function(e) {
if (e.which == 13) {
    var $targ = $(e.target);
    if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
        var focusNext = false;
        $(this).find(":input:visible:not([disabled],[readonly]), a").each(function() {
            if (this === e.target) {
                focusNext = true;
            }
            else if (focusNext) {
                $(this).focus();
                return false;
            }
        });
        return false;
    }
}
});

$('#adjustment-form').on('submit', function(e) {
var rownumber = $('table.order-list tbody tr:last').index();
if (rownumber < 0) {
    alert("Please insert product to order table!")
    e.preventDefault();
}
});

function productSearch(data) {
$.ajax({
    type: 'GET',
    url: 'lims_product_search',
    data: {
        data: data
    },
    success: function(data) {
        var flag = 1;
        $(".product-code").each(function(i) {
            if ($(this).val() == data[1]) {
                rowindex = i;
                var qty = parseFloat($('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val()) + 1;
                $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(qty);
                checkQuantity(qty);
                flag = 0;
            }
        });
        $("input[name='product_code_name']").val('');
        if(flag) {
            var newRow = $("<tr>");
            var cols = '';
            cols += '<td>' + data[0] + '</td>';
            cols += '<td>' + data[1] + '</td>';
            cols += '<td><input type="number" class="form-control qty" name="qty[]" value="1" required step="any" /></td>';
            cols += '<td class="action"><select name="action[]" class="form-control act-val"><option value="-"></option><option value="+"></option></select></td>';
            cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger"></button></td>';
            cols += '<input type="hidden" class="product-code" name="product_code[]" value="' + data[1] + '"/>';
            cols += '<input type="hidden" class="product-id" name="product_id[]" value="' + data[2] + '"/>';

            newRow.append(cols);
            $("table.order-list tbody").append(newRow);
            rowindex = newRow.index();
            calculateTotal();
        }  
    }
});
}

function checkQuantity(qty) {
var row_product_code = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(2)').text();
var action = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.act-val').val();
var pos = product_code.indexOf(row_product_code);

if ( (qty > parseFloat(product_qty[pos])) && (action == '-') ) {
    alert('Quantity exceeds stock quantity!');
    var row_qty = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val();
    row_qty = row_qty.substring(0, row_qty.length - 1);
    $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(row_qty);
}
else {
    $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(qty);
}
calculateTotal();
}

function calculateTotal() {
var total_qty = 0;
$(".qty").each(function() {
    if ($(this).val() == '') {
        total_qty += 0;
    } else {
        total_qty += parseFloat($(this).val());
    }
});
$("#total-qty").text(total_qty);
$('input[name="total_qty"]').val(total_qty);
$('input[name="item"]').val($('table.order-list tbody tr:last').index() + 1);
}
</script>


via Chebli Mohamed

Laravel Error Whoops, looks like something went wrong. 2/2 ErrorException in path/storage/framework/views/44812f12bcefe0281da2f29a7f94d872 line 40

I got an error as follow and I don't understand it. Is that a session issue.

2/2 Whoops, looks like something went wrong.
ErrorException in /path-to-app/storage/framework/views/44812f12bcefe0281da2f29a7f94d872 line 40:
Trying to get property of non-object (View: /path-to-app/resources/views/backend/base/clients/companies/peoples/index_all.blade.php)

1/2
ErrorException in 44812f12bcefe0281da2f29a7f94d872 line 40:
Trying to get property of non-object


via Chebli Mohamed

How to store pdf file using filesytem and retreive it through sql database in laravel?

Hope you are fine. Please help me with this issue. I want to generate the pdf invoice automatically by pressing the button and save it filesystem and also save its path in the SQL database when I need to access these invoices it can be easily accessible from the SQL database. Thank you.



via Chebli Mohamed

vendredi 30 octobre 2020

Laravel how can I run two redirect with each other simultaneously?

I'm trying to execute two redirect at the same time, but I don't know how to display this correctly in Laravel. Laravel 5.7 is used.

Here is my code:

    public function store(Request $request)
    {
        
         $validatedData = $request->validate([
            'name' => 'min:2|max:50',
            'details' => 'nullable|max:255',
            'image' => 'nullable',
            'tournament_id' => 'nullable',
            
        ]);
        
          $team = Team::create($validatedData);

        return redirect()
            ->route('tournaments.show', $tournament)
            ->with('success', 'Team erstellt');
        
        return redirect()
        ->route('teams.show', $team)
        ->with('success', 'Team erstellt');
        
        $errors = $validator->errors();
        
        $tournament = Tournament::where('id', $team->tournament_id)->first();


return redirect()->back()->with('error' ,'Error Foo');
    }

Update: This was my old code which I changed I refactoring the old code. The code was before whitout a validation and worked.

public function store(Request $request)
    {
        if(Auth::check()){
            $team = Team::create([
                'name' => $request->input('name'),
                'details' => $request->input('details'),
                'image' => $request->input('image'),
                'tournament_id' => $request->input('tournament_id'), 
            ]);
 
                
            if($team){
                
                $tournament = Tournament::where('id', $team->tournament_id)->first();
                
                if($tournament->size > 1){
                    return redirect()->route('tournaments.show', ['tournament'=> $tournament->id])
                ->with('success' , 'Team erstellt');
                }
                
                return redirect()->route('teams.show', ['team'=> $team->id])
                ->with('success' , 'Team erstellt');
            }
 
        }
         
        return back()->withInput()->with('errors', 'Fehler beim erstellen des Teams');
    }


via Chebli Mohamed

image not linked from storage folder to public

i have saved image given path storage/app/public/image/image.jpg but not able to call them, also used given command.working on local server but not live.

php artisan storage:link


via Chebli Mohamed

How can we pass a variable from script inside php and set it to new a variable?(Updated)

How can we pass a variable from script inside php and set it to new a variable? I want to calculate the user location and the destination location by their coordinates but first I want to get the user coordinates which is already given in the script.

<?php
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  if (($lat1 == $lat2) && ($lon1 == $lon2)) {
    return 0;
  }
  else {
    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
      return ($miles * 1.609344);
    } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
      return $miles;
    }
  }
}

$mResult = distance($lat, $long, 29.46786, -98.53506, "M") . " Miles<br>";
$kmResult = distance($lat, $long, 29.46786, -98.53506, "K") . " Kilometers<br>";
$nmResult = distance($lat, $long, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

echo $kmResult;

?>
<script>

window.onload = function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(bindPosition);
  } else { 
    y.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function bindPosition(position) {
  $.ajax({
    url: "/getlocation",
    type: "GET",
    dataType: "json",
    data: { 
      lat: position.coords.latitude, 
      long: position.coords.longitude
    },
    success: function(response){
          if(data == "success")
        alert(response); 
    },
    error: function(response){
        alert('Error'+response);
        console.log('Error'+response);
    }
  })
}
</script>

the route

Route::get('getlocation', 'HomeController@getAllLocations');

ajax response enter image description here

enter image description here



via Chebli Mohamed

How to display Thai text with proper word wrap in PDF?

I'm using Laravel Framework to develop a pdf generated by using variables from Controller and display in THAI language. The problem is whenever THAI language is displayed and justified. It's not in the correct form. For example, the string "พัฒนาสำเร็จเทคโนโลยีผลักดันนานาชาติทรัพยากรส่งเสริมเอสเอ็มอีระดับสากลจัดการคุณธรรมโทรคมนาคมวิสาหกิจบริหารสตาร์ทอัพสร้างสรรค์จิตวิญญาณสนับสนุนลงทุนโลกาภิวัฒน์สตาร์ทอัพผลักดันยุคใหม่ลงทุนเอสเอ็มอีจริยธรรมนวัตกรรมผสมผสานเป้าหมายก้าวหน้าสำเร็จล้ำสมัยคุณธรรมพลเมืองเทคโนโลยีโลกาภิวัฒน์ความสัมพันธ์บูรณาการสร้างสรรค์บริหารพันธกิจสร้างสรรค์พลังงานเทคโนโลยีบริหารเอสเอ็มอีสตาร์ทอัพคุณธรรมสำเร็จจัดการจิตวิญญาณยุคใหม่มุ่งมั่นวิสาหกิจวาทกรรมสุขภาวะสนับสนุนต่างประเทศกระแสเป้าหมายอาเซียนกระแสวิสาหกิจสนธิกำลังสุขภาวะเป้าหมายบูรณาการเทคโนโลยีเทคโนโลยีผสมผสานพลังงานบริหารเป้าหมายผลักดันโครงสร้างระดับสากลพันธกิจวาทกรรมทรัพยากรพัฒนาระดับสากลทรัพยากรจิตวิญญาณกระแสจัดการส่งเสริมต่างประเทศสตาร์ทอัพคุณธรรมสุขภาวะเทคโนโลยีวาทกรรมโครงสร้างประชารัฐโลกาภิวัฒน์บริหารผสมผสานนานาชาติยุคใหม่ความสัมพันธ์อาเซียนโลกาภิวัฒน์บูรณาการสนธิกำลังจริยธรรมวาทกรรมจัดการผสมผสานล้ำสมัยมุ่งมั่นผลักดันพลเมืองนานาชาติพลังงานโครงสร้างบริหารจิตวิญญาณส่งเสริมเทคโนโลยีพันธกิจ" will be displayed in this form >>

Example of Incorrect Thai Text Display

The Javascript I used as below >>

function widthCharCount(txt){
if(!txt) return 0;
  var thaiFullWidthCharRegex = /[^\u0E31\u0E34-\u0E3E\u0E47-\u0E4E]/g;
  return txt.match(thaiFullWidthCharRegex).length;
}
function wrapThaiText(segThaiTxt,maxLength,linebreak){
  linebreak = linebreak || '\n';
  //thai word segmentation with '|'
  var words = segThaiTxt.split('|');
  var txt = '';
  //loop from start words
  for (var i = 0, line = '', linewlength = 0; i < words.length; i++){
    var wlen = widthCharCount(words[i]);
    if(linewlength + wlen <= maxLength){
      line = line + words[i];
      linewlength +=  wlen;
      
    } else { //word exceed line length
      //add line to txt
      txt = txt + (line+linebreak);
      //move the word to new line
      line = words[i];
      linewlength = wlen;
    }
  }
  if( linewlength > 0 ) {
    txt = txt + line;
  }
  return txt;
}
function wrapText() {
  var inlen = $("#in-len").val();
  //replace new line with ^ before send to word segment
  var thaiTxt = $("#in-txt").val().replace(/\n/g,'^');
  $.ajax( "https://s2.adsstat.com/swath",
         { crossDomain: true,
          data: thaiTxt,
          contentType: 'text/plain; charset=UTF-8',
          type: 'POST',
          success:function( data ) {//replace work segmentation new line with <wbr/>, <br/>
                    $( "#out-txt-swath" ).html( wrapThaiText(data.replace(/\^/g,'\n'),inlen,'<br />'));
                  }
         });
}
$("#in-txt").on( "change", wrapText );
$("#in-len").on( "change", wrapText );

When I hard code the THAI text directly in the div like this >>

<input id="in-len" type="text" value="50" style="display: none;"/>
<div id="in-txt">ใดใดในโลกล้วน อนิจจา สิ้นซึ่งสังขารลา เที่ยงแท้ คงแต่บาปบุญมาพาส่ง สู่ที่โปรดนา ใดใดในโลกล้วน อนิจจา สิ้นซึ่งสังขารลา เที่ยงแท้ คงแต่บาปบุญมาพาส่ง สู่ที่โปรดนา ใดใดในโลกล้วน อนิจจา สิ้นซึ่งสังขารลา เที่ยงแท้ คงแต่บาปบุญมาพาส่ง สู่ที่โปรดนา ใดใดในโลกล้วน อนิจจา สิ้นซึ่งสังขารลา เที่ยงแท้ คงแต่บาปบุญมาพาส่ง สู่ที่โปรดนา ใดใดในโลกล้วน อนิจจา สิ้นซึ่งสังขารลา เที่ยงแท้ คงแต่บาปบุญมาพาส่ง สู่ที่โปรดนา ใดใดในโลกล้วน อนิจจา สิ้นซึ่งสังขารลา เที่ยงแท้ คงแต่บาปบุญมาพาส่ง สู่ที่โปรดนาใดใดในโลกล้วน อนิจจา สิ้นซึ่งสังขารลา เที่ยงแท้ คงแต่บาปบุญมาพาส่ง สู่ที่โปรดนา ใดใดในโลกล้วน อนิจจา สิ้นซึ่งสังขารลา เที่ยงแท้ คงแต่บาปบุญมาพาส่ง สู่ที่โปรดนา</div>
<div id="out-txt-swath"></div>

When I'm using the code like above. The text is displayed and break lines correctly.

I don't know why hard code text and text from or php tag are differ from each other in some way. Any ideas for this? If you got an idea, please let me know. Thank you in advance.



via Chebli Mohamed

jeudi 29 octobre 2020

How to switch php versions on mac catalina

I'm trying to switch project between laravel 8 and laravel 5.2 but unfortunately laravel 5.2 only runs on php5.5.9 - php7.1 and I'm currently running PHP7.4, so I ended up following this thread How can I easily switch between PHP versions on Mac OSX?, but nothings works for me.

And then I'm trying this one: https://medium.com/@jalendport/how-to-switch-between-php-versions-on-your-mac-b561758ed8f5, But when I run php -v, I'm getting this error:

dyld: Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib

So I tried to find answers about this here: dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib, but nothing works. Do you have any other options so I can switch between my projects?



via Chebli Mohamed

How to change the column names used in Laravel Auditing Package?

I'm currently trying to use Laravel Auditing v4.1, yes, I know it's end of support and due to legacy issues I can't use the newer one.

The issue is, there are two apps, that will be referencing the same audit table. The old app, was using the older version of Laravel Auditing where the column names are different to the version 4.1. So what I was trying to do is map the saving of the audit record referencing to the old column names.

Anyway, what I tried so far:

  • Using a custom model. Changed the implementation value under config/audit.php to my own model App\Models\CustomAudit

    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use OwenIt\Auditing\Audit as AuditTrait;
    use OwenIt\Auditing\Contracts\Audit as AuditContract;
    
    class CustomAudit extends Model implements AuditContract
    {
        use AuditTrait;
    
        /**
         * {@inheritdoc}
         */
        protected $guarded = [];
    
        /**
         * {@inheritdoc}
         */
        protected $casts = [
            'old_value' => 'json',
            'new_value' => 'json',
        ];
    
    
        /**
         * The attributes that should be mutated to dates.
         *
         * @var array
         */
        protected $dates = [
            'created_at',
            'updated_at'
        ];
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'id',
            'user_id',
            'owner_type',
            'owner_id',        
            'old_value',
            'new_value',
            'type',
            'route',
            'ip',
        ];
    }
    
    
    

Notice that in this model, I'm using the old column names, but during submit, it says Unknown column old_values that is because it's trying to use the new column names.

  • Under the model class that I want to Audit, I called the function transformAudit and change the array keys on the fly before saving it to the database, which works. But is there a cleaner way to do it?

I tried looking for related issues online but what I only found was adding additional columns.



via Chebli Mohamed

laravel validation does not work with Auth

I am trying to add validation in the controller but it does not work with auth:check. This is the Laravel version 5.7.

This is the function store that has a problem with the validation.

 public function store(Request $request)
    {
        $request->validate([
                'first_name' => ['required'|'min:2'|'max:50']
                ]);
        
        if(Auth::check()){
            
            $player = Player::create([
                'first_name' => $request->input('fist_name'),
                'last_name' => $request->input('last_name'),
            ]);
 
 
            if($player){
                return redirect()->route('players.show', ['player'=> $player->id])
                ->with('success' , 'foo');
            }
 
        }
         
        return back()->withInput()->with('errors', 'Foo Error');
    }


via Chebli Mohamed

Laravel wrong limit inside function with

There are three models User Post and Image. The user has many posts, posts have many images. Also, there is a user_images function - it's hasManyThrough function. All relations work well. During the search, I wanna get users with images(max 3 for every user) and do something like that:

$users = User::where('is_active', true)
            ->with([
                'user_images' => function ($relation) {
                    $relation->limit(self::LIMIT_IMAGES);
                }
            ])->get();

Response:

[
  {
    "id": 265,
    "user_images": [
      {
        "id": 309,
        "path": "url"
      },
      {
        "id": 308,
        "path": "url"
      },
      {
        "id": 306,
        "path": "url"
      }
    ]
  },
  {
    "id": 305,
    "user_images": []
  }
]

As you can I have ONLY 3 images for all users, not for every. But if I use Lazy Eager Loading(function load) with the same limit, all works well. Can someone explain that behavior?



via Chebli Mohamed

mercredi 28 octobre 2020

Markers are missing when calling it dynamically

Most of the Markers are missing when calling it dynamically. Here is my code. I am beginner in Laravel. The Sports variable contains various sports name, marker image for each sport name, popup image for each sport name etc. The Mapevents contains different/ repeated sport names with different latitude and longitude. While try to mark in Map using Markers most of the Map events are not displaying.

<script type="text/javascript">
  (function(A) {
  if (!Array.prototype.forEach)
    A.forEach = A.forEach || function(action, that) {
      for (var i = 0, l = this.length; i < l; i++)
        if (i in this)
          action.call(that, this[i], i, this);
      };
    })(Array.prototype);
    var
    mapObject,
    markers = [],
    markersData = {
      @foreach($mapevents as $event)
      @foreach($sports as $sport)
      @if($event->category_id==$sport->id)
      '': [
      {
        name: 'Events',
        location_latitude: "", 
        location_longitude: "",
        map_image_url: 'sport2gether/storage/<?php echo $sport->popup_image?>',
        name_point: '""',
        description_point: 'Event Details<br>Starting Date: ""<br>Ending Date: ""<br>Starting time: ""<br>Ending time: ""',
        url_point: 'eventsdetails'
      },
      ],
      @endif
      @endforeach
      @endforeach
      @foreach($maphotspots as $hotspot)
      @foreach($sports as $sport)
      @if($hotspot->category_id==$sport->id)
      '': [
      {
        name: 'Hotspots',
        location_latitude: "", 
        location_longitude: "",
        map_image_url: 'sport2gether/storage/<?php echo $sport->popup_image?>',
        name_point: '""',
        description_point: 'Hotspot Details<br>Starting Date: ""<br>Ending Date: ""<br>Starting time: ""<br>Ending time: ""',
        url_point: 'hotspotsdetails'
      },
      ],
      @endif
      @endforeach
      @endforeach
    };
    function initialize () {
      var mapOptions = {
        zoom: 16,
        center: new google.maps.LatLng("", ""),
        mapTypeId: google.maps.MapTypeId.HYBRID,
        mapTypeControl: false,
        mapTypeControlOptions: {
          style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
          position: google.maps.ControlPosition.LEFT_CENTER
        },
        panControl: false,
        panControlOptions: {
          position: google.maps.ControlPosition.TOP_RIGHT
        },
        zoomControl: true,
        zoomControlOptions: {
          style: google.maps.ZoomControlStyle.LARGE,
          position: google.maps.ControlPosition.TOP_RIGHT
        },
        scaleControl: false,
        scaleControlOptions: {
          position: google.maps.ControlPosition.TOP_LEFT
        },
        streetViewControl: false,
        streetViewControlOptions: {
          position: google.maps.ControlPosition.LEFT_TOP
        },
        styles: [{"featureType":"poi","stylers":[{"visibility":"off"}]},{"stylers":[{"saturation":-70},{"lightness":37},{"gamma":1.15}]},{"elementType":"labels","stylers":[{"gamma":0.26},{"visibility":"off"}]},{"featureType":"road","stylers":[{"lightness":0},{"saturation":0},{"hue":"#ffffff"},{"gamma":0}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"lightness":50},{"saturation":0},{"hue":"#ffffff"}]},{"featureType":"administrative.province","stylers":[{"visibility":"on"},{"lightness":-50}]},{"featureType":"administrative.province","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"administrative.province","elementType":"labels.text","stylers":[{"lightness":20}]}]
      };
      var
      marker;
      mapObject = new google.maps.Map(document.getElementById('map'), mapOptions);
      for (var key in markersData)
        markersData[key].forEach(function (item) {
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(item.location_latitude, item.location_longitude),
            map: mapObject,
            icon: 'sport2gether/storage/' + key, 
          });
          if ('undefined' === typeof markers[key])
            markers[key] = [];
          markers[key].push(marker);
          google.maps.event.addListener(marker, 'click', (function () {
      closeInfoBox();
      getInfoBox(item).open(mapObject, this);
      mapObject.setCenter(new google.maps.LatLng(item.location_latitude, item.location_longitude));
     }));    
        });
    };
    function hideAllMarkers () {
      for (var key in markers)
        markers[key].forEach(function (marker) {
          marker.setMap(null);
        });
    };
    function toggleMarkers (category) {
      hideAllMarkers();
      closeInfoBox();
      if ('undefined' === typeof markers[category])
        return false;
      markers[category].forEach(function (marker) {
        marker.setMap(mapObject);
        marker.setAnimation(google.maps.Animation.DROP);

      });
    };
    function closeInfoBox() {
      $('div.infoBox').remove();
    };
    function getInfoBox(item) {
      return new InfoBox({
        content:
        '<div class="marker_info none" id="marker_info">' +
        '<div class="info" id="info">'+
        '<img src="' + item.map_image_url + '" class="logotype" alt=""/>' +
        '<h2>'+ item.name_point +'<span></span></h2>' +
        '<span>'+ item.description_point +'</span>' +
        '<a href="'+ item.url_point + '" class="green_btn">Join</a>' +
        '<span class="arrow"></span>' +
        '</div>' +
        '</div>',
        disableAutoPan: true,
        maxWidth: 0,
        pixelOffset: new google.maps.Size(40, -210),
        closeBoxMargin: '50px 200px',
        closeBoxURL: '',
        isHidden: false,
        pane: 'floatPane',
        enableEventPropagation: true
      });
    };
</script>


via Chebli Mohamed

Calling Artisan Commands from other Artisan Commands using different .env

I want to use .env.testing and I read here:

You may also create a .env.testing file. This file will override the .env file when running PHPUnit tests or executing Artisan commands with the --env=testing option.

I have an artisan command that should create my testing database. The command is triggered using php artisan testdb:fresh and calling another command in his handle method:

public function handle()
{
    if ($this->isProduction()) {
        $this->errorMessageTestingDatabase();
        return;
    }

    $this->call('migrate:fresh', ['--env' => 'testing',  '--seed' => true]);
}

However, it seems that the --env=testing flag is ignored. I get a failure to connect to db exception.

However, if I run the command by

php artisan testdb:fresh --env=testing 

It works. It it not possible to pass an env flag when calling an Artisan command withing an Artisan command?



via Chebli Mohamed

Is this Mysql Bug? About SELECT ... FOR UPDATE lock_mode X insert intention

have a table struct is id, aid, ...... the aid is an index(a type of int)

trx1 and 2: begin;
trx1: select max(id) from a where aid = 10 for update;
trx2: select max(id) from a where aid = 10 for update; ## have blocked waiting trx 1
trx1: insert into a (........;  then trx 2 will throw a deadlock even not commit yet

this error can't throw out in PHP, no error in PHP and MySQL. just-auto rollback then continues to execute other code.

change MySQL query order below:

trx1 and 2: begin;
trx1: select max(id) ... for update;
trx1: insert ...;
trx2: select max(id) ... for update;
trx1: commit; the trx2 result is currectly

enter image description here

my MySql version is 5.7 I was saw(the same kind of type question):Solution for Insert Intention Locks in MySQL
and this:https://bugs.mysql.com/bug.php?id=25847

for test code below:

//prepared:
CREATE TABLE `test_lock` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `aid` int(11) NOT NULL,
  `otherinfo` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `aid` (`aid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
insert into `test_lock` (`aid`) values(10);
##trx1 and trx2
begin;
##trx1
select max(id) from `test_lock` where (`aid` = 10) limit 1 for update;
##trx2(have blocked)
select max(id) from `test_lock` where (`aid` = 10) limit 1 for update;
##trx1
insert into `test_lock` (`aid`) values(10);
##then trx2 will gave a deadlock error and look that error
show engine innodb status\G;

use PHP to test(i use Laravel5.6 Commands):

//file1:
$aid = 10;
DB::beginTransaction();
$result = DB::table('test_lock')->where('aid', $aid)->orderByDesc('id')->lockForUpdate()->first();
var_dump($result);
echo "after get:" . date('Y-m-d H:m:s.u'). "\r\n";
sleep(10); // wrong
DB::table('test_lock')->insert(
    ['aid' => $aid]
);
echo "after insert:" . date('Y-m-d H:m:s.u'). "\r\n";
//sleep(10);  // correctly and  file2 is correct result
DB::commit();

//file2
$aid = 10;
DB::beginTransaction();
$pdo = DB::connection()->getPdo();
$result = DB::table('test_lock')->where('aid', $aid)->orderByDesc('id')->lockForUpdate()->first();
var_dump($result); //NULL
echo "after get:" . date('Y-m-d H:m:s.u'). "\r\n";
var_dump($pdo->errorCode()); // 00000
$ret = DB::table('test_lock')->insert(
    ['aid' => $aid]
);
echo "after insert:" . date('Y-m-d H:m:s.u'). "\r\n";
DB::commit();

In PHP File2 result is NULL. Have not any error throw. no mysql error log left. you can use show engine innodb status\G; to found the deadlock happened.

have some way can give me help, please?



via Chebli Mohamed

Get the first free column in a Google Sheet via PHP API

I'm using the Google Sheets API to write some data into the sheets, but so far either I clear it all and write everything again or I write in new rows (which Sheets API does by default).

I am now writing a single column per run, but I need to get the first available column in the sheet, so I can pass it as the range of writing.

This is my code so far:

        $sheet = new \Google_Service_Sheets($this->client);
        $range = "'" . $sheetName . "'!" . $rangeArg . (strlen($rangeArg) == 2 ? '' : count($data) + 1000);

        $response = $sheet->spreadsheets_values->get($this->sheetId, $range);

        if (!$clear && $response && $response->values) {
            $c = count($response->values);
            $newRange = (intval(substr($rangeArg, 1, 1)) + $c);
            $newRange = substr($rangeArg, 0, 1) . $newRange . substr($rangeArg, 2);
            $range = "'" . $sheetName . "'!" . $newRange . (count($data) + 1000);
        }

        $options = ['valueInputOption' => 'RAW'];

        if ($clear) {
            $sheet->spreadsheets_values->clear($this->sheetId, $range, new \Google_Service_Sheets_ClearValuesRequest);
        }

       $body = new \Google_Service_Sheets_ValueRange(['values' => $data, 'majorDimension' => $columns ? 'COLUMNS' : 'ROWS']);
       $ok = $sheet->spreadsheets_values->append($this->sheetId, $range, $body, $options);
    }

I saw someone on the internet mentioning getLastColumn() as a function, but it's not available in my version of sheets API apparently or it's just not in this package.

google/apiclient                   v2.5.0
google/apiclient-services          v0.138
google/auth                        v1.9.0


via Chebli Mohamed

mardi 27 octobre 2020

Facing facades issue in laravel


Fatal error: Uncaught RuntimeException: A facade root has not been set. in /app/dragonglass/crm/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:218 Stack trace: #0 /app/dragonglass/crm/app/helpers.php(617): Illuminate\Support\Facades\Facade::__callStatic('Header', Array) #1 /app/dragonglass/crm/app/helpers.php(556): getLoggerBasicData('Call to undefin...', '') #2 /app/dragonglass/crm/app/Exceptions/Handler.php(40): logError('Call to undefin...', '', Array) #3 /app/dragonglass/crm/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(314): App\Exceptions\Handler->report(Object(Symfony\Component\Debug\Exception\FatalThrowableError)) #4 /app/dragonglass/crm/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(122): Illuminate\Foundation\Http\Kernel->reportException(Object(Symfony\Component\Debug\Exception\FatalThrowableError)) #5 /app/dragonglass/crm/public/index.php(53): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #6 {main} thrown in /app/dragonglass/crm/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 218

Facing the above issue in Laravel 5.6 any solution please?



via Chebli Mohamed

Timestamp comparison on where clause randomly working?

I have an old database where the column FastStart_start and FastStart_End are varchars.

Using the Laravel query builder, the following query

$referrals = \DB::table('users')->join('order_details', 'order_details.user_id', 'users.id')
            ->join('users as sponsor', 'sponsor.id', '=', 'users.sponsor_id')
            //->where('order_details.created_at', '>=', 'sponsor.FastStart_Start')
            ->where('order_details.created_at', '<=', 'sponsor.FastStart_End')
            ->select('users.username', 'users.email',  'order_details.created_at', 'users.sponsor_id',
                 'sponsor.FastStart_Start', 'sponsor.FastStart_End')
            ->get();

gives this outcome:

 #items: array:3 [
    0 => {#2792
      +"username": "annalise92"
      +"email": "luisa.grimes@example.net"
      +"created_at": "2020-06-15 21:32:23"
      +"sponsor_id": 2085929
      +"FastStart_Start": "2020-06-01 00:00:00"
      +"FastStart_End": "2020-06-30 00:00:00"
    }
    1 => {#2832
      +"username": "nbarton"
      +"email": "gibson.ibrahim@example.com"
      +"created_at": "2020-06-15 21:32:23"
      +"sponsor_id": 2085929
      +"FastStart_Start": "2020-06-01 00:00:00"
      +"FastStart_End": "2020-06-30 00:00:00"
    }
    2 => {#2836
      +"username": "maxine56"
      +"email": "cwuckert@example.net"
      +"created_at": "2020-06-15 21:32:23"
      +"sponsor_id": 2085929
      +"FastStart_Start": "2020-06-01 00:00:00"
      +"FastStart_End": "2020-06-30 00:00:00"
    }
  ]

From the outcome its clear that FastStart_Start is less then order_details.created_at.

However, if I uncomment the line

//->where('order_details.created_at', '>=', 'sponsor.FastStart_Start')

from the query builder, the result set will be empty.

How is this possible? Does it have to do with the fact that FastStart_Start is a varchar column? If so, why does it not affect the comparison with FastStart_End?

Using toSql command I see that query builder is creating this query:

select users.username
     , users.email
     , order_details.created_at
     , users.sponsor_id
     , sponsor.FastStart_Start
     , sponsor.FastStart_End 
  from users 
  join order_details 
    on order_details.user_id = users.id 
  join users sponsor 
    on sponsor.id = users.sponsor_id 
 where order_details.created_at >= ? 
   and order_details.created_at <= ?

Any idea why the resulting set is empty if I uncomment the where line?

EDIT: The tosql result for the other query is:

select users.username
     , users.email
     , order_details.created_at
     , users.sponsor_id
     , sponsor.FastStart_Start
     , sponsor.FastStart_End 
  from users 
  join order_details 
    on order_details.user_id = users.id 
  join users sponsor 
    on sponsor.id = users.sponsor_id 
 where order_details.created_at <= ?


via Chebli Mohamed

How to access assets from resources sub folder in Laravel?

This is the javascript source in blade file.

<script src=""></script>

OR

<script src=""></script>

Both asset and URL::to doesn't work. The actual file path is: resources -> views -> template -> js

error shows 404 not found on local xampp server. its working fine in production. project is copy of production code.

I would appreciate for your kind support. thanks



via Chebli Mohamed

laravel post for image and textfield

The post created is to save the image and description to the DB but only the description gets saved.The request is being done via formData()..So currently trying via postman

$post = new Post;
$post->user_id = Auth::user()->id;
$post->desc = $request->desc;

//check if post has photo
If($request->hasFile('image')){
  $imageName = time().'.'.$request->image->extension();  
  $request->image->move('storage/posts', $imageName);
  $post->photo = $imageName ;
}

//mistake
$post->save();
$post->user;
return response()->json([
  'success' => true,
  'message' => 'posted',
  'post' => $post
]);


via Chebli Mohamed

After Module creation Laravel project give error

I have project botsolutionNew and I want to make module inside my project, but problem here is that after creating module the whole project is not running. It work fine when i disable module. I got the following errors after running my project

Action Modules\Quickbooks\Http\Controllers\HomeController@index not defined.

(View: F:\wamps\www\botsolutionNew\resources\views\layouts\partials\home_header.blade.php)



via Chebli Mohamed

How to limit the telescope entries in laravel?

We are using telescope to monitor our laravel application. but telescope is using big amount of database. Yes we can delete records . But is there any way that we only allow telescope to insert record related to queues and schedule commands not all data like requests , database queries and many other things.



via Chebli Mohamed

Sending temporary attachment to email not working in Laravel 5.8

I'm trying to send attachment from form input via Notification email but I keep getting "Serialization of 'Illuminate\Http\UploadedFile' is not allowed" error.

This is my controller function:

/**
 * @param InterviewRequest $request
 * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
 */
public function interviewPost(InterviewRequest $request)
{
    $contactForm = $request->all();
    $contactForm['country_code'] = config('country.code');
    $contactForm['country_name'] = config('country.name');
    $contactForm = ArrayHelper::toObject($contactForm);

    if ($request->hasFile('filename')) {
        $contactForm->filename = $request->file('filename');
    }

    // Send Contact Email
        if (config('settings.app.email')) {
            Notification::route('mail', config('settings.app.email'))->notify(new InterviewSent($contactForm)); 
   }
}

This is my Notification function:

/**
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    $mailMessage = (new MailMessage)
        ->replyTo($this->msg->email, $this->msg->name)
        ->subject(trans('mail.contact_form_title', ['country' => $this->msg->country_name, 'appName' => config('app.name')]))
        ->line(t('Country') . ': <a href="' . lurl('/?d=' . $this->msg->country_code) . '">' . $this->msg->country_name . '</a>')
        ->line(t('Name') . ': ' . $this->msg->name);

    if (isset($this->msg->email) && $this->msg->email!='') {
        $mailMessage->line(t('Email Address') . ': ' . $this->msg->email);
    }

    if (isset($this->msg->phone) && $this->msg->phone!='') {
        $mailMessage->line(t('Phone Number') . ': ' . $this->msg->phone);
    }

    if (isset($this->msg->filename)  && (!empty($filename))) {
        return $mailMessage->attachData(
            $this->msg->filename->path(),
            $this->msg->filename->getClientOriginalName(),
            [
            'mime' => $this->msg->filename->getMimeType(),
        ]);
    }

    return $mailMessage;
}

I also tried to use the attach() method but it's still the same result.



via Chebli Mohamed

Form validation on Laravel 5

I seem to have a problem with this function which is used in a contact form. This form was made by a developper I get this message displaying in a random way : "An Error Occured.." when I click Submit button in my form. Most of time I get this error message but on local I yesterday got it not displayed and bassed to the next step and validated the form. Problem is I was not able to reproduce it.

I found the controler use a PostIndex function as follow

    public function postIndex($origin = '')
{
    $input = Input::only('title','name','country_id','company','company_website','phone_number','email','message');
    $input['origin'] = $origin;
    $input['ip'] = getIP();
    // Create a new validator instance from our validation rules
    $validator = Validator::make($input, ContactUs::$rules );

    // If validation fails, we'll exit the operation now.
    if ($validator->fails())
        return Redirect::route('contact-us')->withErrors($validator);
    try {
        $contact = ContactUs::create($input);
    } catch (Exception $e) {
        return Redirect::back()->withInput()->with('error', 'An Error Occured..');  
    }
    return Redirect::route('contact-us.show',$contact->token)->with('success', 'We have received your message.');

}

I suppose there is an issue with the validator relatd to rules which are defined as follow

public static $rules = array(
        'title'             => 'required',
        'name'              => 'required',
        'email'             => 'required|email',
        'country_id'        => 'required|exists:countries,id',
        'company'           => 'required',
        'company_website'   => 'required',
        'phone_number'      => 'required',
        'message'           => 'required',
    );

This is the form field:

<div class="form-group ">
                    <label class="col-lg-3 " for="title">Title: <sup>*</sup></label>
                    <div class="col-lg-8">
                        

                        
                    </div>
                </div>
                <div class="form-group ">
                    <label class="col-lg-3" for="name">Name: <sup>*</sup></label>
                    <div class="col-lg-8">
                        <input type="text" class="form-control required "
                               name="name" id="name" value="" required>
                        
                    </div>
                </div>
                <div class="form-group ">
                    <label class="col-lg-3" for="email">Email: <sup>*</sup></label>
                    <div class="col-lg-8">
                        <input type="email" class="form-control required "
                               name="email" id="email" value="" required>
                        
                    </div>
                </div>
                <div class="form-group ">
                    <label class="col-lg-3" for="country_id">Country: <sup>*</sup></label>
                    <div class="col-lg-8">
                        
                        
                    </div>
                </div>
                <div class="form-group ">
                    <label class="col-lg-3" for="company">Company Name: <sup>*</sup></label>
                    <div class="col-lg-8">
                        <input type="text" class="form-control required " required name="company" id="company" value="">
                        
                    </div>
                </div>
                <div class="form-group ">
                    <label class="col-lg-3" for="company_website">Company Website: <sup>*</sup></label>
                    <div class="col-lg-8">
                        <input type="url" class="form-control required " required name="company_website" id="company_website" value="">
                        
                    </div>
                </div>
                <div class="form-group ">
                    <label class="col-lg-3" for="phone_number">Phone Number: <sup>*</sup></label>
                    <div class="col-lg-8">
                        <input type="text" class="form-control hidden " name="phone_number" id="phone_number" placeholder="in internal format e.g : +185523232422" value="">
                        <input type="tel" id="phone" class="form-control">
                        <div id="valid-msg" class="hide text-aqc-green val_msg">✓ Valid</div>
                        <div id="error-msg" class="hide text-aqc-red val_msg">Invalid number</div>
                        
                    </div>
                </div>
                <div class="form-group ">
                    <label class="col-lg-3" for="message">Your Message: <sup>*</sup></label>
                    <div class="col-lg-8">
                        <textarea name="message" id="message" class="form-control" style="min-height:150px;max-height:200px;" placeholder="Place Your Message Here" required></textarea>
                    </div>
                </div>


via Chebli Mohamed

What is best practice to save history in laravel?

We have big laravel application . In many controller method we are calling golbal helper function which is saving history. Here is our method.

            $user_id =  $userId;
            $user_model = $userModel;
            $model = Consignment::class;
            $object_id = $consignment->id;
            $status = getConsignmentStatus($consignment->status);
            $comment = "Consignment has been created";
            $visibility = "Internal Only";
            //Hitory Helper function
            history($user_id, $object_id, $model, $status, $comment, $visibility, $user_model);

History function

function history($user_id, $object_id, $model, $status, $comment, $visibility = '', $user_model = null)
{
  $history = new History;
  $history->user_id = $user_id;
  $history->object_id = $object_id;
  $history->model = $model;
  $history->status = $status;
  $history->comment = $comment;
  $history->visibility = $visibility;
  if (!empty($user_model))
    $history->user_model = $user_model;

  $history->save();
  return "history inserted";
}

But I personally think that there could be a better approach, I heared that this type of things should be done by events but why and how I dont know.



via Chebli Mohamed

lundi 26 octobre 2020

General Error with laravel General error: 1366 Incorrect integer value: for column image_id

i'm not sure what is wrong
"message": "SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'C:\Users\roman\AppData\Local\Temp\php85A7.tmp' for column 'image_id' at row 1 (SQL: insert into foods (name, description, price, offer_price, quantity, image_id, updated_at, created_at) values (Hussain Wael, kasdhv;loasid, 100, 1, 12, C:\Users\roman\AppData\Local\Temp\php85A7.tmp, 2020-10-26 22:25:30, 2020-10-26 22:25:30))",

store function

    public function store(FoodRequest $request)
    {
        $data = Food::create($request->all());


        if ($file = $request->file('image_id')) {
            $path = $file->store('image');

            $data['image_id'] = Image::create([
                'name' => $file->getClientOriginalName(),
                'size' => $file->getSize(),
                'path' => $path
            ])->id;
        }
        return $this->response_api(true, __('front.success'), StatusCodes::OK);
    }

my migration

 Schema::create('foods', function (Blueprint $table) {
        $table->bigIncrements('id');

        $table->string('name');
        $table->unsignedBigInteger('image_id');
        $table->integer('quantity')->default(1);
        $table->float('price' , 10 , 2)->default(1);
        $table->string('addons')->default(0);
        $table->longText('description');
        $table->float('offer_price',10,2)->default(0);
        $table->unsignedInteger('category_id')->nullable();
        $table->unsignedBigInteger('menu_id')->nullable();
        $table->timestamps();
    });

My request :

public function rules()
{
    return [
        'name'=>['string','required'],
        'image_id'   => 'required_unless:_method,PUT|nullable|image',
        'quantity'=>['required','numeric'],
        'category_id' =>[ 'nullable','exists:categories,id',],
        'menu_id' =>[ 'nullable','exists:menus,id',],
        'price'=>'required','numeric','min:1',
        'offer_price'=>['nullable','numeric'],
        'description' =>[ 'nullable',],
        'addons' =>[ 'nullable'],

    ];
}

Model :

class Food extends Model

{

 protected $fillable = [
        'parent_id',
        'menu_id',
        'name',
        'image_id',
        'quantity',
        'price',
        'addons',
        'description',
        'offer_price'];

Relations with images table:

 public function image()
    {
        return $this->belongsTo(Image::class)->withDefault();
    }


Schema::create('images', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('size');
        $table->string('path');
        $table->timestamps();
    });


via Chebli Mohamed

How to install package in old laravel project

I have a project built in laravel 5.8 and I want to add socialite package in this project but whenever I try to install the socialite package it gave me this error all the time. enter image description here Here is my composer.json

{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": [
    "framework",
    "laravel"
],
"license": "MIT",
"require": {
    "php": "^7.1.3",
    "anandsiddharth/laravel-paytm-wallet": "^1.0",
    "anhskohbo/no-captcha": "^3.1",
    "barryvdh/laravel-dompdf": "^0.8.6",
    "caouecs/laravel-lang": "~4.0",
    "cartalyst/stripe-laravel": "10.*",
    "doctrine/dbal": "^2.10",
    "fideloper/proxy": "^4.0",
    "guzzlehttp/guzzle": "~6.0",
    "instamojo/instamojo-php": "^0.4.0",
    "laravel/framework": "5.8.*",
    "laravel/socialite": "^5.0",
    "laravel/tinker": "^1.0",
    "masterro/laravel-xss-filter": "^1.0",
    "mollie/laravel-mollie": "2.0",
    "paypal/rest-api-sdk-php": "^1.14",
    "phpmailer/phpmailer": "^6.1",
    "rachidlaasri/laravel-installer": "^4.1",
    "razorpay/razorpay": "2.*",
    "renatomarinho/laravel-page-speed": "^1.8",
    "softon/indipay": "^1.2",
    "spatie/laravel-cookie-consent": "^2.10",
    "spatie/laravel-sitemap": "^5.7",
    "willvincent/feeds": "^2.1"
},
"require-dev": {
    "beyondcode/laravel-dump-server": "^1.0",
    "filp/whoops": "^2.0",
    "fzaninotto/faker": "^1.4",
    "mockery/mockery": "^1.0",
    "nunomaduro/collision": "^3.0",
    "phpunit/phpunit": "^7.5"
},
"config": {
    "optimize-autoloader": true,
    "preferred-install": "dist",
    "sort-packages": true
},
"extra": {
    "laravel": {
        "dont-discover": []
    }
},
"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "files": ["app/Http/Helpers/Helper.php"]
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts": {
    "post-autoload-dump": [
        "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
        "@php artisan package:discover --ansi"
    ],
    "post-root-package-install": [
        "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "@php artisan key:generate --ansi"
    ]
}

Note: I am using PHP Version 7.4 with laragon
Please help me to solve this problem.
Thanks in Advance



via Chebli Mohamed

Authentication In Laravel With Multi Auth

i am just learning the laravel version 5.4. i just made a simple blog post application using laravel with an website and admin panel

So in navbar which is common for front side code looks like below

@if (Auth::guest())
    <li><a href="">Login</a></li>
    <li><a href="">Register</a></li>
@else
    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
             <span class="caret"></span>
        </a>
    </li>

And In controller

class PostController extends Controller
{
    public function __construct()
    {
        //$this->middleware('auth:user'); << i also tried thi
        $this->middleware('auth:user')->except('index','show');
    }

So the problem is i wants to allow all users to read blog post without login but if i add this middleware than user cant access this page without the login.

than i also tried to put except() keyword. after adding this it works but problem is in navbar it is still showing Login/Register instead showing logout button and profile name.



via Chebli Mohamed

dimanche 25 octobre 2020

I want to Create One to Many Relationship | with If Condition | (Category has many Subcategories)

I want to create a Category, if they have a parent categoryId then update the parent id, and categoryName on the subcategory Table. if they have not parent id then, it saves on the parent Category table with category name. Can you Correct my Relationship Code? I think it is wrong. and Very Thank you to Help me

in category Model (parent)

class Category extends Model
{
    public function subcategories(){
        return $this->hasMany(Subcategory::class);
    }
}

In the Subcategory Model,

class Subcategory extends Model

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

In controller,

public function store(Request $request){
    //dd($request->categoryid);
    if($request->categoryid){ 
       $subcategory = new Subcategory();
       $subcategory->name = $request->subcatname;
       $subcategory->save(); 

     $category = $request->categoryid;
       //dd($category);
       $subcategory->category()->attach($category); 

    } 
       $category = new Category();
       $category->name = $request->catname;
       $category->save();
    }


via Chebli Mohamed

How to make URL from Laravel routes

I've got Laravel backend and I'm trying to make iOS to it, but there is no documentation. It is my first time with Laravel, so confused with the routes and middlewares. How do I compose URL from code below

Route::middleware('auth:api')->get('/user', function (Request $request) {
   return $request->user();
});

// Passport authentication
Route::group([
   'prefix' => 'auth'
], function () {
   Route::post('login', 'AuthController@login');
   Route::post('signup', 'AuthController@signup');

   Route::group([
     'middleware' => 'auth:api'
   ], function() {
       Route::get('logout', 'AuthController@logout');
       Route::get('user', 'AuthController@user');
       Route::resource('materials', 'MaterialsController');
       Route::resource('packages', 'PackagesController'); ```


via Chebli Mohamed

Migration Error: Syntax error or access violation: 1071 Specified key was too long in Laravel

I'm working with Laravel 5.6 and Mysql Version 5.7.3. Everything is working fine in Laravel Vagrant box. But when I deployed my project in VPS hosting with CentOS and run the command "php artisan migrate:refresh" it's raised error like "SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: a lter table products add unique products_bar_code_unique(bar_code))". How could I solve this issue? Thanks in advance.



via Chebli Mohamed

Server Error (500) when starting my dockerized laravel app

I have created a laravel app and then created a Dockerfile:

FROM php:7.4-cli

RUN apt-get update -y && apt-get install -y libmcrypt-dev

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN docker-php-ext-install pdo 
#mbstring

WORKDIR /app
COPY . /app

RUN composer install

EXPOSE 8000
CMD php artisan serve --host=0.0.0.0 --port=8000

Then I ran sudo docker build -t myApp . and sudo docker run -it -p 8000:8000 news-organizer. Everything worked fine.

When I copy this folder (with Dockerfile) to another location and run composer update --ignore-platform-reqs, sudo docker build --no-cache -t theApp . and sudo docker run -it -p 8888:8888 theApp the Web App starts. When I enter 127.0.0.1:8888 I get the 500 Error.

I already set all rights to sudo chmod 755 -R <myLaravelFolder>. I also tried setting different port numbers. The Dockerfile of the new folder is:

FROM php:7.4-cli

RUN apt-get update -y && apt-get install -y libmcrypt-dev

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN docker-php-ext-install pdo 
#mbstring

WORKDIR /app
COPY . /app

RUN composer install

EXPOSE 8888
CMD php artisan serve --host=0.0.0.0 --port=8888

I just can't find a way to fix the 500 Error. What can I do?

My basic idea is: Creating a Laravel Web-App. Then creating a Dockerfile and upload it somewhere. Then others can download the Web App, install Docker, and run sudo docker build -t <myImage> . and sudo docker run -it -p 8000:8000 <myImage>. With that they can use my Laravel App on their computers as docker container.

I run xubuntu 20.04 as OS.



via Chebli Mohamed

samedi 24 octobre 2020

How to use gentelella alela select2 option in laravel

I found they have select2 file in their vendor folder, so i linked them (those links works when i open these two files in web browser). in header

 <link href="" rel="stylesheet">

in Footer

<script src=""></script>

in body

 <div class="item form-group">
                        <select class="form-control select2-multi" name="tags[]">
                            @foreach($tags as $tag)
                            <option value="">  </option>
                            @endforeach
                        </select>
                    </div>

in body

<script type="text/javascript">
$(.select2-multi').select2();
</script>

but, still it not working.. this code found in here https://www.youtube.com/watch?v=BNUYaLWdR04&list=PLwAKR305CRO-Q90J---jXVzbOd4CDRbVx&index=43



via Chebli Mohamed

Laravel version upgrade with routes.php

Laravel had a routes.php file in older version. Which got changed into routes/web.php I am trying to upgrade the laravel from older to latest version. But my routes.php still exists and routes folder is not still created.

Is this fine, because the code works fine till now.



via Chebli Mohamed

Display image in Vue from storage folder with laravel

I'm saving my images in following location

Storage/app/public/userImages

It is getting saved but when i retrieve it in my vue component it throws error 404 not found.

<img :src="`/storage/${post.img_path}`"/>

and the url which is created is

http://localhost:8000/storage/userImages/872937058.png

Please give any suggestions.



via Chebli Mohamed

how to deal with long task on laravel to avoid 504 error?

I'm trying to do a long task (upload file or foreach 100k rows query) but every time I get the 504 error.

I have set nginx.conf and the set_time_limit(0) but nothing seems to work.

What is the proper way to deal with long tasks, I mean, is there a way to send responses while doing the job? so the server and client keep communicating? so both parties know that the job isn't done yet?

For example, I know the query have 100k rows, so I know is a long job. Or uploading a large file, I send chunks of it, knowing theres a lot of chunks, but keep getting the 504 error.

Should I send responses for each loop? How can I do that? returning responses ends the job, so I don't know how to keep the task alive



via Chebli Mohamed

Hyn tenancy showing Query Exception 'the table 'db' is full when creating new tenant

I have been working on laravel angular project since last 6 months and now implementing hyn\multi-tenancy showing the error query exception:

  Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1114 The table 'db' is full (SQL: GRANT ALL ON `XYfeQKZivx`.* TO `XYfeQKZivx`@'127.0.0.1')

And I don't have such table in my database. Tried almost everything from the Internet still unable to find the solution for the problem. Please any one help. Thank You.



via Chebli Mohamed

vendredi 23 octobre 2020

Joining two models in Laravel Eloquent

I have a model stored in a variable like:

$user = User::where('name', 'like', $test)
             ->orderBy('name');

I would like to build another query where I can join $user. Can't find the right syntax to do it.

What am trying to achieve:

$numbers= Number::>join($user, $users.id, '=', 'number.user_id')
                        ->where('name', 'like', "%" . $validated['text'] . "%")])
                        ->get();


via Chebli Mohamed

Sent Thank-you email to visitors after form submit via Laravel 5

enter image description here

I'm trying to send out an email in Laravel 5

$mail = Mail::send('layouts.share.emails.confirm', array(
    'message' => $contact->message,
) , function ($message)
{
    $message->from(env('MAIL_FROM') , 'www.jdoe.com');
    if(env('APP_ENV') == 'local'){
        $message->to($email , 'Cyb3r 8200')->subject(' Thank-you from '.env('APP_URL'));
    } else {
        $message->to($email , 'Cyb3r 8200')->subject(' Thank-you from www.jdoe.com ');
    }

});

I kept getting

message: "Undefined variable: email"

Any hints for me ?



via Chebli Mohamed

How do I make header and sidebar stay in my project?

i want to call component of header footer and sidebar in one daseboard page.

<x-app-layout>   




@include('/assets. Header')
@include('/assets. Sidebar')
@include('/assets. Footer')
</x-app-layout>


via Chebli Mohamed

How to remove paginate in Laravel?

I need to remove the pagination and leave everything on one page, but this way I'm doing it only generates BUG. I wonder why the snippet of the commented code doesn't work to remove the pagination.

     whereHas('sizes', function($query)  use($minParam, $maxParam) {
         if($minParam && $maxParam) {
             $query->whereBetween('max_capacity', [$minParam, $maxParam]);
         } elseif($minParam) {
             $query->where('max_capacity', '>=', $minParam);
         } else {
             $query->where('max_capacity', '<=', $maxParam);
         }
     })->
    
    if ($minParam || $maxParam) {
      $products = Product::whereHas('sizes', function ($query) use ($minParam, $maxParam) {
        if ($minParam && $maxParam) {
          $query->whereBetween('max_capacity', [$minParam, $maxParam]);
        } elseif ($minParam) {
          $query->where('max_capacity', '>=', $minParam);
        } else {
          $query->where('max_capacity', '<=', $maxParam);
        }
      })
        ->whereHas('solutions', function ($query) use ($solution_id) {
          $query->whereIn('solution_id', $solution_id);
        })
        ->where('active', 1)
        ->orderBy('position', 'ASC')
        ->paginate(16);
    } else {
      $products = Product::whereHas('solutions', function ($query) use ($solution_id) {
        $query->whereIn('solution_id', $solution_id);
      })
        ->where('active', 1)
        ->orderBy('position', 'ASC')
        ->paginate(16);

 /*$products = Product::whereHas('solutions', function ($query) use ($solution_id) {
    $query->whereIn('solution_id', $solution_id);
  })
    ->where('active', 1)
    ->orderBy('position', 'ASC');*/
    
      return view('solutions.show')->with(compact('solutions', 'solution', 'products', 'ranges'));
    
    }


via Chebli Mohamed

laravel's environment file .env always clean itself during development

I face an issue when in development, my laravel's environment file : .env, usually clean itself whenever I update the client-side code (*.vue files).

I'm using VueJS as client and running the run-time build/watch whenever we have some change, we can refresh the browser to see the change but usually, I don't know why it always clear the laravel .env file to a blank file. It's so annoy.

Who might face the same issue? Any solution or way to find-out the root cause?

Noted: In production, it's OK. (Laravel 5.8 / VueJS 2.x)



via Chebli Mohamed

Upload Multiple images in Laravel using Vue.js

I'm trying to upload image using vue.js in Laravel for that i'm using this link

https://jsfiddle.net/b412ruzo/

to upload image using vue.js and when i submit the form i'm getting following image in files array

enter image description here

now issue is that i cannot get this file array in laravel controller

when i print

$request->file('files') 

in my controller i am getting null. and when i print $request->input('files') this is the result, an empty array

enter image description here

Any help regarding this issue is highly appreciated.

Code Snippet :

data() {
     return {
    rawData: [],
    formData: new Form({
        files:[],
})
..

  const header = {
             Authorization: "Bearer " + this.token,
            };
  this.formData
        .post(APP_URL + `/api/post`, { headers: header })
        .then((response) => {

   }


via Chebli Mohamed

How to combine or merge two nested arrays according to their index

Here is the formatted code:

<?php
$final_data1 = [
    '6882' => [
            'observation' => '51',
            'dom' => '4462',
            'amenity_value' => '5900',
            'amenity_id' => '6882',
            'amenity_name' => '10 ft. Ceiling',
            'unit_id' => [
                    '0' => '45349',
                    '1' => '45350',
                ]
        ],
    '6842' => [
            'observation' => '0',
            'dom' => '0',
            'amenity_value' => '0',
            'amenity_id' => '6842',
            'amenity_name' => '11 Ft. Ceiling',
            'unit_id' => [
                    '0' => '45317',
                    '1' => '45531'
                ]
        ]

];
$final_data2 =  [
    '6882' => [
            'observation' => '5',
            'dom' => '415',
            'amenity_value' => '150',
            'amenity_id' => '6882',
            'amenity_name' => '10 ft. Ceiling',
            'unit_id' => [
                    '0' => '45502',
                    '1' => '45505',
                    '2' => '45786'
                ]
        ]
];
$final_data  = [
    '6882' => [
            'observation' => '56', //51+5 = 56
            'dom' => '4877', //4462+415 = 4877
            'amenity_value' => '6050', //5900+150
            'amenity_id' => '6882',//no addition here id fixed
            'amenity_name' => '10 ft. Ceiling', //name fixed too
            'unit_id' => [
                    '0' => '45349',
                    '1' => '45350',
                    '2' => '45502',
                    '3' => '45505',
                    '4' => '45786' //here concatenated the two array $final_data1['6882']['unit_id'] and $final_data2['6882']['unit_id']
                ]
        ],
    '6842' => [
            'observation' => '0',
            'dom' => '0',
            'amenity_value' => '0',
            'amenity_id' => '6842',
            'amenity_name' => '11 Ft. Ceiling',
            'unit_id' => [
                    '0' => '45317',
                    '1' => '45531'
                ]
        ]

];
print_r($final_data);

Here, you can see I have two array $final_data1 and $final_data2 where first one has two index and second one as one index. Now, I want combine this two arrays to one $final_data. While combining we need to consider only those value with same index.

In this case, we will add $final_data1['6882'] and $final_data2['6882'] but index 6842 is present only in $final_data1 so this will be same in $final_data.

And, while producing final results we need to sum observation, dom, amenity_value, while amenity_id, amenity_name should be used as fixed value and unit_id should be merged or concatenated. To make this more clear I have commented it on $final_data which is the expected output.

In case you need phpsandbox online url



via Chebli Mohamed

jeudi 22 octobre 2020

how to download csv file then redirect the page using laravel

I want to download the CSV file after that want to redirect the page on laravel controller.but does not work on the below code

$downloadthefile=Response::make($return_data);
Response.redirect('/app-sent-report');


via Chebli Mohamed

Could .env and .env.example files differ in Laravel?

I have some custom configuration variables that only my company uses for the app. We have a dependency and we have to have those env variables to work that class but other people doesn't need those variables since they are not using the class we are using. So I have 5 more key=>value pair in my production .env which are not in .env.example, is this logical? Are there any other place that I should hold custom key variables other than .env



via Chebli Mohamed

Laravel get file name from folder with File method

Cant figure out how to get file name from folder in ````filePath```

use Illuminate\Support\Facades\File;

    $filePath = storage_path('app/apiFiles/'.auth()->user()->id_message.'/');

    $fileName = File::files($filePath);

    dd($fileName);

dd($fileName) return array but i need only filename is possible to separated from array?

what i need from array is only this filename: "Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"

 array:1 [▼
    0 => Symfony\Component\Finder\SplFileInfo {#293 ▼
    -relativePath: ""
    -relativePathname: "Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
    path: "/var/www/html/domain/storage/app/apiFiles/910960"
    filename: "Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
    basename: "Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
    pathname: "/var/www/html/domain/storage/app/apiFiles/910960/Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
    extension: "zip"
    realPath: "/var/www/html/domain/storage/app/apiFiles/910960/Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
   aTime: 2020-10-22 06:46:37
   mTime: 2020-10-22 06:46:37
   cTime: 2020-10-22 06:46:37
   inode: 1308192
   size: 3180822
   perms: 0100644
   owner: 33
   group: 33
   type: "file"
   writable: true
   readable: true
   executable: false
   file: true
   dir: false
   link: false
 }

]



via Chebli Mohamed

mercredi 21 octobre 2020

using s3 storage Class 'SimpleXMLElement' not found

I am using digital ocean server and my site is in laravel and php 7.2 site is working fine but now I want to use amazone S3 storage space while I am entering s3 credentials in env file and run this site then it is showing this error

 ErrorException in PayloadParserTrait.php line 44: 
 Class 'SimpleXMLElement' not found (View: /var/www/xxxxxxxx/xxxxxxxxx/resources/views/home/index.blade.php)

please help me out about this problem.

but when I use these credentials in local host it is showing this error

ErrorException in WrappedHttpHandler.php line 195: 
Error executing "ListObjects" on "https://astrochest.s3.amazonaws.com/?prefix=cache%2Fcad2dc21%2Faveec8569429dbfa0cc9b.jpeg%2F&max-keys=1&encoding-type=url"; AWS HTTP error: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) (View: E:\wamp64\www\newastrochest\astrochest\resources\views\home\index.blade.php) 


via Chebli Mohamed

Laravel - File Upload button not working in live server

In the laravel project the file upload button was working fine during local development using WAMP Server. But when I uploaded the project to my shared hosting server, the file upload button does not work anymore. The button is disabled.

In my localhost the upload button works, but in my live server the file upload button does not work(disabled)

Pls help I don't know what to do.



via Chebli Mohamed

Space before %pdf in snappy pdf generation

I am using Snappy pdf and all things are working fine but I tried to upload on some websites then it says "PDF header is not at the start of file". I analyzed this error and found that this is because when i generate the pdf file then the pdf is taking space before the %pdf syntax. I opened the generated pdf in the notepad++.

My config file is like this

 return array(
'pdf' => array(
    'enabled' => true,
    'binary'  => base_path('vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64'),
    'timeout' => false,
    'options' => array(),
    'env'     => array(),
    'margin-top' => 0,
    'margin-right' => 0,
    'margin-bottom' => 0,
    'margin-left' => 0,
),

Could you please help me to find a solution on how to remove this space when the pdf generate



via Chebli Mohamed

Saving selected option after validation in Laravel

I need help with saving a selected option after validation fails.

Here is main.blade.php

<form method="POST" action="">
  <select id="searchEngine" name="searchEngine">
    <option value="google">Google</option>
    <option value="bing">Bing</option>
    <option value="duckduck">DuckDuckGo</option>
  </select>

  @if ($errors->has('searchEngine'))
    <div style="background-color: #faa;">
        @foreach ($errors->all() as $error) 
         
        @endforeach
    </div>
  @endif
</form>

Controller looks like:

request()->validate(
            ['searchEngine' => "required|in:google,duckduck"],
            ['searchEngine.in' => $searchEngine.' not working, try another']
        );

I tried this, but it always returns only the last option:

<option value="google" {!! $errors->has('searchEngine') ? 'selected' : '' !!}>Google</option>
<option value="bing" {!! $errors->has('searchEngine') ? 'selected' : '' !!}>Bing</option>
<option value="duckduck" {!! $errors->has('searchEngine') ? 'selected' : '' !!}>DuckDuckGo</option>


via Chebli Mohamed

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) with Laravel session

Suddenly I got 500 error in my laravel application and I did composer install and composer update. 500 Error was gone and I got Laravel error called as follows.

Illuminate \ Database \ QueryException (1045) SQLSTATE[HY000] [1045] Access denied for user 'bec'@'localhost' (using password: YES) (SQL: select * from sessionswhereid = nEF6h6M0tWczE2pMn2pdwAZ2pHwPwlQN7KgTLQH2 limit 1)

I tried below things. php artisan optimize:clear

this is my .env

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=becmis
DB_USERNAME=root
DB_PASSWORD=secret

I never faced this error with

(SQL: select * from `sessions` where `id` = nEF6h6M0tWczE2pMn2pdwAZ2pHwPwlQN7KgTLQH2 limit 1)

Please help me to get rid of this



via Chebli Mohamed

mardi 20 octobre 2020

How do you read the type file of input using sweetalerts in laravel 5?

I am using laravel 5.2 and sweetalert. I have a button for upload a file, and when I click the button, there is a sweetalert popup shown to upload the file. But when I submit it, it won't uploaded but no error message.. I tried to print the file but it shows nothing. I use this code too to insert the text type and it worked but not with the file type. Do you know how to read a filetype in sweetalert?
This is the button code:

<button id="uploadfile" data-id="" class="btn btn-success"><i class="fa fa-upload"></i></button>

This below is my sweetalert code

  $('button#uploadfile').on('click', function(ID){
      var ID = $(this).attr('data-id');
      swal({
      content: {
        element: "input",
        attributes: {
          placeholder: "Upload the file",
          type: "file",
          confirmButtonText: 'Upload',
        },
      },
    })
    .then((myfile) => {
        if (myfile.value === false) return false;
        if (myfile.value === "") {
          swal.showInputError("You need to upload the file");
          return false
        }
        if (myfile) {
        $.ajax({
            url: "FileUpload?ID="+ID+ "&file="+myfile,
            type: "GET",
            success: function (data) {
                if (data == 'ok') {
                    swal("Uploaded", "Your file has been uploaded successfully!", {
                      icon: "success",
                    }).then(function () {location.reload();});
                }
            }      
        });
      }
    } 
});

And this one is my controller:

public function FileUpload(Request $request)
    {
        $id = $request['ID'];
        $document = Files::where('id', $id)->first();
        $destination = 'files';
        if(!Storage::exists($destination)){
            Storage::makeDirectory($destination);
        } 

        if($request->hasFile('myfile')) {
            $file = $request->file('myfile');
            $extension = $file->getClientOriginalExtension();
            $file_name =  $document->id .'_'. date('YmdHis', strtotime(date('Y-m-d H:i:s'))) . '.' . $extension;
            $file->move($destination, $file_name );
            $document->file = $file_name;
        }
        $document->save();  
        $data = 'ok';
        return $data;
    }


via Chebli Mohamed

Eloquent Relationship Count Constraint

I am trying to write an eloquent query that would work as follows:

Tables:
Order
Support Ticket (one to many with the order)

Query: Filter the support tickets and only show the order if the support ticket is less than 45 days old.

I feel like this would be an adaptation of the whereHas() method in Laravel but I am not sure how to implement a filter or a date search on a relationship like this.

Thanks!



via Chebli Mohamed

Method update does not exist in Laravel

It is very simple code to update an existing entry. save() is working perfectly. But update is not working. Here is my code:

Route::post('toggleFavourite',function(){
    try{
        $data = Request::all();
        extract($data);
        $favourite = \ItScholarBd\Api\Models\Favourite::where(['user_id'=> $user_id,'shop_id'=> $shop_id])->get();
        if(empty($favourite)){
            $favourite = new \ItScholarBd\Api\Models\Favourite;
            $favourite->user_id = $user_id;
            $favourite->shop_id = $shop_id;
            $favourite->status  = $status;
            $favourite->save();
        }else{
            $favourite->status  = $status;
            $favourite->update();
        }
        return response()->json(['status' =>1, 'data' => $favourite], 200); 
    }
    catch (Exception $ex) {
        return response()->json(['status'=>0, 'status_text' => $ex->getMessage()], 500);

    }
});

I am getting the following response:

{"status":0,"status_text":"Method update does not exist."}


via Chebli Mohamed

in laravel collection remove key if value is null

i new in laravel, trying to filter null value array and remove from array. like this i have this array from response

array:8 [▼
  "videoa" => Collection {#801 ▼
    #items: []
  }
  "music" => Collection {#872 ▼
    #items: array:69 [▶]
  }
  "meditation" => Collection {#869 ▼
    #items: array:1 [▶]
  }
]

see , in this array videos has null , but i want following array

array:8 [▼
 
  "music" => Collection {#872 ▼
    #items: array:69 [▶]
  }
  "meditation" => Collection {#869 ▼
    #items: array:1 [▶]
  }
  
]

when the key value is null then remove it from array. i tried array_filter($array); but not get any results. plase help me



via Chebli Mohamed

How to upload file using sweetalerts in laravel 5?

I am using laravel 5.2 and sweetalert. I have a button for upload a file, and when I click the button, there is a sweetalert popup shown to upload the file. But when I submit it, it won't uploaded but no error message.. I tried to print the file but it shows nothing. Do you know how to read a filetype in sweetalert?
This is the button code:

<button id="uploadfile" data-id="" class="btn btn-success"><i class="fa fa-upload"></i></button>

This below is my sweetalert code

  $('button#uploadfile').on('click', function(ID){
      var ID = $(this).attr('data-id');
      swal({
      content: {
        element: "input",
        attributes: {
          placeholder: "Upload the file",
          type: "file",
          confirmButtonText: 'Upload',
        },
      },
    })
    .then((myfile) => {
        if (myfile.value === false) return false;
        if (myfile.value === "") {
          swal.showInputError("You need to upload the file");
          return false
        }
        if (myfile) {
        $.ajax({
            url: "FileUpload?ID="+ID+ "&file="+myfile,
            type: "GET",
            success: function (data) {
                if (data == 'ok') {
                    swal("Uploaded", "Your file has been uploaded successfully!", {
                      icon: "success",
                    }).then(function () {location.reload();});
                }
            }      
        });
      }
    } 
});

And this one is my controller:

public function FileUpload(Request $request)
    {
        $id = $request['ID'];
        $document = Files::where('id', $id)->first();
        $destination = 'files';
        if(!Storage::exists($destination)){
            Storage::makeDirectory($destination);
        } 

        if($request->hasFile('myfile')) {
            $file = $request->file('myfile');
            $extension = $file->getClientOriginalExtension();
            $file_name =  $document->id .'_'. date('YmdHis', strtotime(date('Y-m-d H:i:s'))) . '.' . $extension;
            $file->move($destination, $file_name );
            $document->file = $file_name;
        }
        $document->save();  
        $data = 'ok';
        return $data;
    }


via Chebli Mohamed

How to delete data in DB Laravel 7

Can someone tell me what my mistake is when deleting data from the database Previously, when I used a similar method, everything worked correctly. But now for some reason when I click to delete the last record, the first one is deleted I have used several different methods but the result is the same There is my code in controller

public function destroy(Coin $coin)
    {
        Coin::where('id', '=', $coin->id)->first()->delete();
        Coin::find($coin->id)->delete();
        $coin->delete($coin->id);
        $coin->delete();
        Coin::destroy($coin->id);
        return back();
    }

There is my route

Route::post('/coins/delete/{coin}', 'CoinController@destroy')->name('coins.delete');


via Chebli Mohamed

lundi 19 octobre 2020

get the address bar url instead of request url

I have the page test_page with the url http://domain.sd/test_page which is in the address bar. I have used the controller with url filter_details in the same page in ajax response. I want to get the address in the address bar. Now I can get only the ajax request url

 $url=\Request::getRequestUri();
   echo $url; // output: filter_details

How to get the address in the address bar



via Chebli Mohamed

run laravel project uploaded from Git in localhost using Win10,Wamp

I have uploaded an laravel projet but Don't know how to exécute it in my localhost, Windows 10, an wamp server



via Chebli Mohamed

How can I use one .env file for multiple Document roots in Laravel

We use Laravel and have multiple subdomains/domains set up in our servers for different clients. Most of the .env parameters - API urls, DB configurations etc are the same for all clients. Some parameters such as hashing keys may be different. Is it possible to store common parameters in one 'global' .env file,'source' them from it and then add the client-specific parameters in a 'local' .env file? As of now, we have to edit the .env file for each client when we add a new parameter.



via Chebli Mohamed

Laravel $request->all() not retuning anything

Laravel form request not working this $request->all(); return empty array.

I am using Laravel FormRequest and its not working when I am updating the record with put method and sending multipart data in ajax request



via Chebli Mohamed

Upload multiple images using laravel and Vue.js

I'm using vue.js and laravel to upload multiple images using vue.js

JS fiddle:

https://jsfiddle.net/jfwv04mu/

Vue.js

new Vue({
  el: "#app",
  data() {
    return {
      option: {
        maxFileCount: 3
      },
      files:[],
      rawData: [],
    }
  },
  methods: {
    loaddropfile: function(e) {
        e.preventDefault()
      e.stopPropagation()
        alert('ok')
        console.log(e)
    },
    openinput: function() {
        document.getElementById("vue-file-upload-input").click();
    },
    addImage: function(e) {
        const tmpFiles = e.target.files
      if (tmpFiles.length === 0) {
        return false;
      }
      const file = tmpFiles[0]
      this.files.push(file)
      const self = this
        const reader = new FileReader()
      reader.onload = function(e) {
        self.rawData.push(e.target.result)
      }
      reader.readAsDataURL(file)
    },
    removeFile: function(index) {
        this.files.splice(index, 1)
      this.rawData.splice(index, 1)
      document.getElementById("vue-file-upload-input").value = null
    },
    upload: function() {
        alert('Check console to see uploads')
        console.log(this.files)
    }
  },
  mounted(){
  dropContainer.ondragover = dropContainer.ondragenter = function(evt) {
  evt.preventDefault();
};

dropContainer.ondrop = function(evt) {
  // pretty simple -- but not for IE :(
  fileInput.files = evt.dataTransfer.files;
  evt.preventDefault();
};
  }
})

now getting it in controller like this:

foreach($request->input('files') as $file)
      {   dd($file);
         
      }

Now when i print the count of files it shows files count correctly but cannot get images it contains blank array. Please give suggestions to solve this issue.



via Chebli Mohamed

Where is security bug? [closed]

I'm using laravel 5.1. This is the code of custom function so users can transfer coins.

<?php
public function postCoinTransfer( Request $request )
{
    $user = Auth::user();
    $validator = Validator::make( $request->all(), [
        'recipient' => 'required|min:1|max:20',
        'amount' => 'required|numeric|integer'
    ]);

    if ( $validator->fails() )
    {
        return redirect( 'account/settings#transfer' )
            ->withErrors( $validator )
            ->withInput();
    }

    $username = $request->recipient;
    $amount = $request->amount;

    if ($user->name == $username)
    {
        flash()->error( 'You can\'t transfer coins to yourself.' );
        return redirect()->back();

    }

    if (($amount <= 0) || ($amount > 9999))
    {
        flash()->error( 'Amount should be from 1 to 9999 Coins.' );
        return redirect()->back();
    }
    if ($amount > $user->money)
    {
        flash()->error( 'Sorry, not enough coins to make this transaction.' );
        return redirect()->back();
    }

    $recipient = User::where('name', $username) -> first();
    if (!$recipient)
    {
        flash()->error( 'Can\'t find this user.' );
        return redirect()->back();

    }
    Coin::create([
        'sender_id' => $user->ID,
        'recipient_id' => $recipient->ID,
        'amount' => $amount
    ]);

    $user = Auth::user();
    $user->money = $user->money - $amount;
    $user->save();

    $recipient->money = $recipient->money + $amount;
    $recipient->save();

    flash()->success( 'Coins sent successfully.' );
    return redirect( 'account/settings#transfer' );
}

Recently I saw this one in my database. Logs

User with ID 1456 has transferred the coins to himself. And this actions created unlimited and free coins for him. How to fix this bug please?



via Chebli Mohamed

Class does not exist exception if I don't provide full path to my class in Laravel validation extension

I am using Laravel 5.8 and attempting to set up a custom validation extension.

  • I have created a class GroupValidator containing a validate function.
  • I have created a ValidationServiceProvider with the following code:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
use App\Classes\GroupValidator;

class ValidationExtensionServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('valid_parent_id', 'GroupValidator@validate');
    }
}

When my validation triggers I get a Class GroupValidator does not exist exception. However if I specify the full path to my class in the extend function call like so:

Validator::extend('valid_parent_id', 'App\Classes\GroupValidator@validate');

then everything works fine.

Is there some way I can set this up so that I don't have to include the full path to my class?



via Chebli Mohamed

Views and Http folder is getting deleted repetedly

Views folder under resources and Http folder under app in my laravel project is getting deleted repeatedly when someone visits www.website.com/laravel_7.0. The laravel version of the project is 5.8.*. How may I stop this? I would appreciate any help.



via Chebli Mohamed

skip key and its value if key is empty in laravel

I am trying to skip key and it's value if empty.
Following example key f is empty and I want to remove that.


$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5,"f"=>"","i"=>0);

Expected array in laravel

array
      'a' => int 1
      'b' => int 2
      'c' => int 3
      'd' => int 4
      'e' => int 5
      'i' => int 0

I have tried many way like taking if conditions, and array_filter but still not worked



via Chebli Mohamed

Is there any way to determine that where I used exit() or die()? I forgot that where I use dump and die in Laravel

Is there any way to determine that where I use dd() in laravel? Or any way to determine that where i used exit() or die()?
Because there is a lots of files in laravel, I used dd() for testing purpose and I want to remove it so that it runs without dying.



via Chebli Mohamed