lundi 31 mai 2021

Undefined Variable, Passing data to view

I am trying to pass a value from the controller to my view, it keeps showing that the variable is not defined. how do i solve it ?

public function showItemPage(Order $order)
    {
        $products = Product::all();

        $items=$order->packages[0];

  
        $bidSessions = BidSession::find($items->bid_session_id)->get();
       

        return view('app.order.item', array('order' => $order,'products' => $products) , compact("bidSessions"));
    }

When log:info($bidSessions), it shows that I have the data.

{
   "id":1528,
   "page_id":1,
   "name":"Test Steven",
   "user_id":1,
   "channel":"facebook_live",
   "video_id":"486698512444605",
   "video_url":"https:\/\/www.facebook.com\/ricksmanfishmarket\/videos\/486698512444605\/",
   "data":{
      "standalone":"no"
   },
   "start_date":1621332720,
   "end_date":null,
   "ended_at":1621333018,
   "created_at":"1621332887",
   "updated_at":"1621333018",
   "deleted_at":null
}

but when I want to display it

<p>  </p>

This errors shows up

enter image description here



via Chebli Mohamed

Accessing SQS job data (receipt handle) from a Laravel queued console command

I'm adding functionality to a pre-existing app, using Laravel 5.8.38 and the SQS queue driver.

I'm looking for a way to log the receipt handle of queue messages as they're processed, so that we can manually delete messages from the queue for jobs that have gone horribly wrong (without the receipt ID, we'd have to wait for the visibility timeout to be reached).

I'm not super familiar with Laravel and am trying to figure things out as I go. We have two types of queued jobs:

  • a custom class implementing Illuminate\Contracts\Queue\ShouldQueue, that also uses the Illuminate\Queue\InteractsWithQueue, Illuminate\Foundation\Bus\Dispatchable and Illuminate\Bus\Queueable traits (our class gets queued directly)
  • a custom command, extending Illuminate\Console\Command, that runs via Illuminate\Foundation\Console\QueuedCommand

For the custom class, browsing through the source for InteractsWithQueue and Illuminate/Queue/Jobs/SqsJob I discovered I could access the receipt handle directly:

$sqsJob = $this->job->getSqsJob();
\Log::info("Processing SQS job {$sqsJob["MessageId"]} with handle {$sqsJob["ReceiptHandle"]}");

This works great! However, I can't figure out how to do a similar thing from the console command.

Laravel's QueuedCommand implements ShouldQueue as well as Illuminate\Bus\Queueable, so my current guess is that I'll need to extend this, use InteractsWithQueue, and retrieve and log the receipt handle from there. However if I do that, I can't figure out how I would modify Artisan::queue('app:command', $commandOptions); to queue my custom QueuedCommand class instead.

Am I almost there? If so, how can I queue my custom QueuedCommand class instead of the Laravel one? Or, is there a better way to do this?



via Chebli Mohamed

dimanche 30 mai 2021

Laravel subquery in from clause

I need to use subquery in from clause but i can not find such thing in Laravel docs

Laravel version 5.4

$sub = Chat::join("chats as _chats", function ($query) {
    $query->on('chats.room_id', "=", "_chats.room_id")
          ->on('chats.user_type', "<>", "_chats.user_type")
          ->on('chats.created_at', "=", DB::raw("(SELECT MIN(created_at) FROM chats WHERE created_at > '_chats.created_at')"));
    })
    ->selectRaw('TIMESTAMPDIFF(MINUTE, _chats.created_at, chats.created_at) as res')
    ->where('chats.user_type', 'pharmacy_consultant')
    ->where('chats.user_id', 26)
    ->toSql();

       
dd(
    DB::connection('mysql2')
        ->table(DB::raw("({$sub}) as sub"))
        ->select('res')
        ->get()
);
(2/2) QueryException SQLSTATE[HY000]: General error: 2031 
(SQL: select `res` from (select TIMESTAMPDIFF(MINUTE, _chats.created_at, chats.created_at) as res
from `chats` inner join `chats` as `_chats` on `chats`.`room_id` = `_chats`.`room_id` and `chats`.`user_type` <> `_chats`.`user_type` and `chats`.`created_at` = 
(SELECT MIN(created_at) FROM chats WHERE created_at > _chats.created_at) where `chats`.`user_type` = ? and `chats`.`user_id` = ?) as sub)


via Chebli Mohamed

vendredi 28 mai 2021

laravel 8 is not loading css and js/bootstrap

i dont know why, this isnt my first project in laravel but my css isnt working and i cant find any problem in my code, maybe i`m tired or something but this kept me stuck for about 10hours.

it seems that my css isnt working, why? i dont know, i have all my folders in the public folder and my website it`s not looking at all like the template.

here are my css`s

<link href="'" rel="stylesheet" type="text/css" />
    <link href="" rel="stylesheet" type="text/css" />
    <link href="" rel="stylesheet" />
    <link href="" rel="stylesheet" />
    <link href="" rel="stylesheet" type="text/css" />
    <link href="" rel="stylesheet" type="text/css">
    <link href="" rel="stylesheet" type="text/css">
    <link href="" rel="stylesheet" type="text/css">

i dont see any error in the terminal neither when i use ctrl+u, all the css links are oppening



via Chebli Mohamed

Laravel 5.1 route not expecting array

I have the following routes:

use NexCast\Domain\NiveisServico\NiveisServicoController;

Route::group(['prefix' => 'niveis-servico', 'name' => 'niveis-servico.'], function () {
    Route::get('/', [NiveisServicoController::class, 'getData'])->name('get');
    Route::post('/', [NiveisServicoController::class, 'saveData'])->name('save');
    Route::delete('/', [NiveisServicoController::class, 'deleteData'])->name('delete');
});

However I am receiving the following error:

Type error: ReflectionFunction::__construct() expects parameter 1 to be string, array given

What am I doing wrong?



via Chebli Mohamed

jeudi 27 mai 2021

Combine laravel queries

Is it possible to combine those queries in one? What I need is to get 4 rows spaced by 6 hours from now.

$data1 = TransacoesRecentes::orderBy('created_at', 'desc')
        ->whereRaw('created_at <= NOW() - INTERVAL 24 HOUR')
        ->first();

$data2 = TransacoesRecentes::orderBy('created_at', 'desc')
        ->whereRaw('created_at <= NOW() - INTERVAL 18 HOUR')
        ->first();

$data3 = TransacoesRecentes::orderBy('created_at', 'desc')
        ->whereRaw('created_at <= NOW() - INTERVAL 12 HOUR')
        ->first();

$data4 = TransacoesRecentes::orderBy('created_at', 'desc')
        ->whereRaw('created_at <= NOW() - INTERVAL 6 HOUR')
        ->first();

Thanks.



via Chebli Mohamed

Laravel query builder relationships

how can I make join to tables if they have one to many relationships using QueryBuilder I want to do it like Eloquent for example

$result = $this->model::with('members')->select($columns)
            ->latest()
            ->paginate($perPage);

return this result

 "id" => 3701
 "user_id" => 3842
 "cycle_name" => null
 "members_number" => 5
 "code" => "UZFf"
 "start_date" => "2021-05-01"
 "end_date" => "2021-09-01"
 "total_amount" => "5000"
 "amount_per_month" => "1000"
 "public" => 1
 "status" => null
 "created_at" => "2021-05-27 02:14:44"
 "updated_at" => "2021-05-27 02:14:44"
 "is_active" => "yes"
 "is_visible" => "yes"
 "cycle_type_id" => 1
 "collecting_member" => null
 "members" => array:2 [▼
      0 => array:25 [▶]
      1 => array:25 [▶]

how can I perform this operation using query builder I mean to get property in the parent object represent the many relationship



via Chebli Mohamed

redirected you too many times error in Laravel

I have uploaded my Laravel project on Infinityfree free hosting. My url is like this: http://abc.freecluster.eu/ But it shows ERR_TOO_MANY_REDIRECTS



via Chebli Mohamed

Error 404 when using axios.post in .vue file to store product on Laravel Framework

I'm using ProductUploader.vue on Laravel Framework to create the form that allow user to see photos of product and be able to select multiple photos at a time. The problem occurred when I'm using 'axios.post' in ProductUploader.vue. It return Error 404 Not Found when return to http://localhost/products instead of http://localhost/travel-with-us/public/products.

Here is my Code in ProductUploader.vue

<div class="row justify-content-center">
    <div class="col-md-12">
        <div class="card-header font1 font-size2">Add Product</div>

        <div class="card-body font3">
            <form class="vue-form" @submit.prevent="submit">
                <fieldset>
                    <div class="form-group row rounded">
                        <label class="col-md-4 col-form-label text-md-right" for="product_name">Product Name<span style="color: red;">*</span></label>
                        <input class="col-md-6 form-control" type="text" name="product_name" id="product_name" required v-model="product_name">
                    </div>

                    <div class="form-group row rounded">
                        <label class="col-md-4 col-form-label text-md-right" for="product_details">Product Details</label>
                        <input class="col-md-6 form-control" type="text" name="product_details" id="product_details" v-model="product_details">
                    </div>

                    <div class="form-group row rounded">
                        <label class="col-md-4 col-form-label text-md-right" for="product_price_per_unit">Price Per Unit<span style="color: red;">*</span></label>
                        <input class="col-md-6 form-control" type="number" name="product_price_per_unit" id="product_price_per_unit" required v-model="product_price_per_unit">
                    </div>

                    <div class="form-group row rounded">
                        <label class="col-md-4 col-form-label text-md-right" for="product_discount_percentage">Discount Percentage</label>
                        <input class="col-md-6 form-control" type="number" name="product_discount_percentage" id="product_discount_percentage" v-model="product_discount_percentage">
                    </div>

                    <div class="form-group row">
                        <label class="col-md-4 col-form-label text-md-right" for="product_photos">Image(s) (If Any)</label>
                        <input class="col-md-6 form-control" ref="photoUploadInput" type="file" multiple @change="handleFileSelect" accept="image/*" style="display: none;">
                        <div class="col-md-6">
                            <div class="flex justify-between items-center mb-6">
                                <div class="leading-tight">
                                    <div v-if="product_photos.length > 0">
                                        <p>Image Selected :  Image(s)</p>
                                    </div>
                                </div>
                                <button @click="clickInput" type="button" class="px-6 py-2 font-semibold rounded">Please Select Image(s)</button>
                            </div>
                            <div class="row justify-content-center" v-if="product_photos.length">
                                <div class="col-md-6 p-3" v-for="(photo, index) in product_photos" :key="`thumb-${index}`">
                                    <div class="row">
                                        <img class="object-cover" style="width: 50%;" :src="photo.preview" alt="Selected Image">
                                        <button @click="removePhoto(index)" type="button" class="rounded" style="width: fit-content; height: fit-content; margin-top: auto; margin-bottom: auto;">
                                            <i class="fas fa-minus" style="color: red;"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group row rounded">
                        <label class="col-md-4 col-form-label text-md-right" for="tag_id">Tag<span style="color: red;">*</span></label>
                        <select class="col-md-6 form-control" name="tag_id" id="tag_id" required v-model="tag_id">
                            <option :selected="true" disabled value="0">Please Select Tag</option>
                            <option v-for="tag in tag_list" :value="tag.id"></option>
                        </select>
                    </div>

                    <div class="form-group row rounded">
                        <label class="col-md-4 col-form-label text-md-right" for="organization_id">Brand<span style="color: red;">*</span></label>
                        <select class="col-md-6 form-control" name="organization_id" id="organization_id" required v-model="organization_id">
                            <option :selected="true" disabled value="0">Please Select Brand</option>
                            <option v-for="organization in organization_list" :value="organization.id"></option>
                        </select>
                    </div>

                    <div class="form-group row rounded">
                        <label class="col-md-4 col-form-label text-md-right" for="main_type_id">Product Main Type<span style="color: red;">*</span></label>
                        <select class="col-md-6 form-control" name="main_type_id" id="main_type_id" required v-model="main_type_id">
                            <option :selected="true" disabled value="0">Please Select Product Main Type</option>
                            <option v-for="main_type in product_main_type_list" :value="main_type.id"></option>
                        </select>
                    </div>

                    <div class="form-group row rounded">
                        <label class="col-md-4 col-form-label text-md-right" for="sub_type_id">Product Sub Type<span style="color: red;">*</span></label>
                        <select class="col-md-6 form-control" name="sub_type_id" id="sub_type_id" required v-model="sub_type_id">
                            <option :selected="true" disabled value="0">Please Select Product Sub Type</option>
                            <option v-for="sub_type in product_sub_type_list" :value="sub_type.id"></option>
                        </select>
                    </div>

                    <div class="form-group row mb-0 justify-content-center">
                        <button @click="upload" type="button" :disabled="!product_name.length || tag_id == 0 || organization_id == 0 || main_type_id == 0 || sub_type_id == 0" :class="!product_name.length || tag_id == 0 || organization_id == 0 || main_type_id == 0 || sub_type_id == 0 ? 'cursor-not-allowed bg-gray-600 hover:bg-gray-600' : 'bg-indigo-500 hover:bg-indigo-600'" class="px-6 py-2 font-semibold rounded">Add Product</button>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
</div>

<script>
import axios from 'axios';
export default {
    props: ['tag_list', 'product_main_type_list', 'product_sub_type_list', 'organization_list'],
    data() {
        return {
            product_name: "",
            product_details: "",
            product_price_per_unit: "",
            product_discount_percentage: "",
            product_photos: [],
            tag_id: 0,
            organization_id: 0,
            main_type_id: 0,
            sub_type_id: 0,
        }
    },
    methods: {
        handleFileSelect(e) {
            Array.from(e.target.files).forEach(file => {
                const reader = new FileReader()
                reader.onload = () => {
                    this.product_photos.push({
                        preview: reader.result,
                        file
                    })
                }
                reader.readAsDataURL(file)
            })
        },
        clickInput() {
            this.$refs.photoUploadInput.click()
        },
        upload() {
            const dt = new DataTransfer()
            this.product_photos.forEach(photo => dt.items.add(photo.file))
            const fd = new FormData()

            fd.append('product_name', document.getElementById('product_name').value);
            fd.append('product_details', document.getElementById('product_details').value);
            fd.append('product_price_per_unit', document.getElementById('product_price_per_unit').value);
            fd.append('tag_id', document.getElementById('tag_id').value);
            fd.append('organization_id', document.getElementById('organization_id').value);
            fd.append('main_type_id', document.getElementById('main_type_id').value);
            fd.append('sub_type_id', document.getElementById('sub_type_id').value);

            this.product_photos.forEach((photo, index) => fd.append(`photo-${index}`, photo.file))

            console.log(document.getElementById('product_name').value);
            console.log(document.getElementById('product_details').value);
            console.log(document.getElementById('product_price_per_unit').value);
            console.log(document.getElementById('tag_id').value);
            console.log(document.getElementById('organization_id').value);
            console.log(document.getElementById('main_type_id').value);
            console.log(document.getElementById('sub_type_id').value);

            console.log(fd);
            axios.post('/products', fd, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
                // .then(response => console.log(response))
                .then(response => { 
                    // console.log(response); 
                    if(response.status === 200) {
                        window.location = '/products';
                    }
                })
                .catch(err => console.log(err))
        },
        removePhoto(index) {
            this.product_photos.splice(index, 1);
        }
    }
}
</script>

Here is my route in web.php

Route::resource('products','ProductController');

Any ideas why my code return Error 404? How can I fix this? If you have any ideas or want more information, please leave yours in the comment below. Thank you.



via Chebli Mohamed

i want create facebook chat messenger in my localhost website

My website is not live yet. I am using localhost for testing.

I want to integrate Facebook messenger chat but Facebook says only valid domain allowed.

Is there any way to do this?



via Chebli Mohamed

How to set default valute for input type file

<input type="file" name="file_path" class="form-file-input" value="">

larvel default value How to set default valute for input type file



via Chebli Mohamed

mercredi 26 mai 2021

How to use array_push in map method in Laravel?

$ids = [1];
$collection = collect([2]);
$collection->map(function ($item) use ($ids) {
   array_push($ids, $item);
});
dd($ids);

This code returns

array:1 [ 0 => 1 ]

I thought this would return [1, 2] because of array_push;

How can I get [1, 2] or array:2 [ 0 => 1 1 => 2 ] ?



via Chebli Mohamed

Unexpected byte range values defining scope of signed data. Details: The signature byte range is invalid

Used TCPDF for adding a digital signature to the document, Copied solution from here , The error I am keep getting is Unexpected byte range values defining scope of signed data. Details: The signature byte range is invalid Error in adobe Code:

        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle('TCPDF Example 052');
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

        $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 052', PDF_HEADER_STRING);
        $pdf->setHeaderFont([PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN]);
        $pdf->setFooterFont([PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA]);
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        $certificate = 'file://'.public_path().'/tcpdf.crt';
        $info = [
            'Name' => 'TCPDF',
            'Location' => 'Office',
            'Reason' => 'Testing TCPDF',
            'ContactInfo' => 'http://www.tcpdf.org',
        ];
        $pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);
        $pdf->SetFont('helvetica', '', 12);
        $pdf->AddPage();
        $text = 'This is a digitally signed document';
        $pdf->writeHTML($text, true, 0, true, 0);
        $pdf->setSignatureAppearance(180, 60, 15, 15);
        $pdf->addEmptySignatureAppearance(180, 80, 15, 15);
        $pdf->Output('example_052.pdf', 'I');


via Chebli Mohamed

How to retrieve existing stripe customer to charge him again in the future?

I used stripe paymentIntent to create and charge customers, and then used webhooks to activate a membership on my website staging server ... everything worked perfectly, I received events that the payment intent is succeeded and the payment method is attached to a customer, but I don't know how to retrieve the customer to charge him next month automatically from the saved card. This is the paymentIntent where the user pays for the first time and the card gets charged and attached.

public function checkitout (Request $request, $subscription_id)
    {
        \Stripe\Stripe::setApiKey('sk_test_51HcC9a-XXXXXX');
        header('Content-Type: application/json');

        try {
            $subscription = Subscription::findByUid($subscription_id);
            // retrieve JSON from POST body
            $json_str = file_get_contents('php://input');
            $json_obj = json_decode($json_str);
            $customer = \Stripe\Customer::create();
            $paymentIntent = \Stripe\PaymentIntent::create([
                'amount' => $subscription->plan->stripePrice(),
                'currency' => 'usd',
                'customer' => $customer->id,
                'setup_future_usage' => 'off_session',
                'description' => "$subscription_id",
            ]);

            $output = [
                'clientSecret' => $paymentIntent->client_secret,
            ];

            echo json_encode($output);
        } catch (Error $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }

can someone please give me some information on how to do it? Thank you



via Chebli Mohamed

Custom api authentication in laravel

I am trying to make authentication based on api in laravel . Here is my process flow. First of all I get data from api . If it is valid then I keep true value in session . Through a middleware i check every route if it is authenticated or not. Am I in right track ?

Session::put('authenticated', true);
session::get('authenticated');

Should I add anything to make more efficient ? Here problem is I can not handle /login route. After successful login it can be visit login page. Also I can't get session value in LoginController function __construct() . Thanks in advance. I am using laravel 5.5



via Chebli Mohamed

Laravel - append join query after executing a query

Is that possible in laravel to append another query to a query already exceuted?! I have a query with joins but the last join I want to excute is a on to many join so for perventing the duplicates I want to append this join to the query in array for examle.

$this->model::leftjoin('Route', 'Route.RouteID', 'Trip.RouteID') ->leftjoin('ReferenceTrip', 'ReferenceTrip.ReferenceTripID', 'Trip.ReferenceTripID') ->leftjoin('route', 'route.uuid','ReferenceTripGroup.route_id') ->leftjoin('tolls', 'tolls.route_id', 'route.uuid')->get();

the last line ->leftjoin('tolls', 'tolls.route_id', 'route.uuid'); is many so it will cause duplicates, is there any solution.

also if there is any solution I will consider to use first() insted of get()



via Chebli Mohamed

mardi 25 mai 2021

"php artisan serve" forces HTTPS, where to disable locally?

I am running Laravel 5.6 and when I run "php artisan serve" I am being redirected to httpS://127.0.0.1:xxxx where xxxx rotates a bunch of port numbers.

Also, I am getting this error message in the console: "127.0.0.1:63227 Invalid request (Unsupported SSL request)" ands as you can see it has a seemingly random port number.

Needless to say I cannot run locally. I would like to know what is causing this so at least I may be able to disable it locally. Any help will be greatly appreciated.

[Tue May 25 16:00:23 2021] 127.0.0.1:63230 Invalid request (Unsupported SSL request)
[Tue May 25 16:00:23 2021] 127.0.0.1:63230 Closing
[Tue May 25 16:00:23 2021] 127.0.0.1:63231 Accepted
[Tue May 25 16:00:23 2021] 127.0.0.1:63232 Accepted
[Tue May 25 16:00:23 2021] 127.0.0.1:63231 Invalid request (Unsupported SSL request)
[Tue May 25 16:00:23 2021] 127.0.0.1:63231 Closing
[Tue May 25 16:00:23 2021] 127.0.0.1:63232 Invalid request (Unsupported SSL request)

There is NOTHING in the log.



via Chebli Mohamed

Laravel project showing 500 error on free 000webhost

This page isn’t working abc.000webhostapp.com is currently unable to handle this request. HTTP ERROR 500

Laravel project uploaded followed by all instructions, still it is giving 500 error.



via Chebli Mohamed

Laravel project architecture for same model pointing at different tables

I created an application 3 years ago where it is possible to see the distribution of species and habitat in my country based on an official documentation. So I have the model "Species" and in the code of the model I have

protected $table = 'species';

and this happens for other 6 or 7 models (and the corresponding controllers).

Now, new official documentations came out and new data are available.

I can't overwrite those tables because the owner wants the possibility to check both the old data and the new ones.

So my question is: is there a way to structure the architecture of the models so that i can make the model pointing at a different table based on a "button" I click on the site or on a specific value I can set? Maybe something like this?

if ($some_value)
    protected $table = 'species';
else
    protected $table = 'species_new_data';


via Chebli Mohamed

lundi 24 mai 2021

Laravel Side Bar Menus are Hidden when notification is sent or when modal pop-up

I have this problem with my website project when notification is sent or when a modal pop-up my sidebar menus are gone, and also the logo. Here is the screenshot to be more understandable.enter image description here...I used pusher to send a real-time notification but when it sends the notification the above will occur and need to refresh the page so that the menus and logo can be seen again. Here I used laravel controller to trigger the pusher event here is my code on it.

`class PublicController extends Controller
{
    public function notify(){

        $token = Session::get('utoken');
        User::where('token', $token)->update(['notify' => 1]);
        \Helper::calculateResult($token);
        User::where('token', $token)->update(['status' => 'finish']);
        $notify = DB::table('users')->where('notify', 1)->select('name','id')->get();
        $notify=$notify->toArray();
        event(new ExamSubmitted($notify));
        return view('finish');
    }
    
}`

and in my blade i have this script in the head tag

    <script>

    Pusher.logToConsole = true;
    
    var pusher = new Pusher('pusher_key', {
      cluster: 'ap1'
    });

    var channel = pusher.subscribe('exam-channel');
    channel.bind('exam-event', function(data) {
        $("span").remove();
        $(".notif").empty();
      if(data['notify'].length>0){
        
        $("#notify").append("<span class='badge custom-badge'>"+data['notify'].length+"</span>");
        data['notify'].forEach(function(value){
          $(".notif").append(
            "<li> <a id='app_modal' data-id ="+value['id']+" href='javascript:void(0)'>"
                  +"<div class='row'>"
                   +" <div class='col-sm-2'><img src=\"\"class='img-size-50 img-circle'></div>"
                   +"<div class='col-sm-8' style='line-height: .5;'>"
                      +"<p style='font-size: 1.6rem'>"+value['name']+"</p>"
                      +"<p style='font-size: 1.2rem'>Just Completed the exam.</p>"
                      +"<p class='text-sm text-muted'><i class='fa fa-clock mr-1'></i> 4 Hours Ago</p>"
                    +"</div>"+
                    "<div class='col-sm-2 text-success'><i class='fa fa-star fa-lg'></i></div>"
                +"</div></div></a>"+
            "</li><div class='dropdown-divider'>"
            );
        });
        
      }
    });
  </script>

Did I do something wrong?



via Chebli Mohamed

Laravel group by id, sum qty and group date to month and year request only and get count

I want to make data based on 2 groups. namely the month group in that year and the group id then calculated based on the existing product id of the product in

I tried this code

$tahunx = '2021';        
          $barangmasuk=BarangMasuk::groupBy('id_barang','months')->select([
                'barang_masuk.id_barang',
                DB::raw("DATE_FORMAT(tgl_masuk,'%M %Y') as months", '=',$tahunx),
                DB::raw('sum(jml_bm) as jumlah')
            ])->get();
    
            dd($barangmasuk);

I want to create data that looks like this

enter image description here

there is table 1 and table 2 that I use

Please help



via Chebli Mohamed

Consultation with GROUP BY MYSQL IN ORM ELOQUENTE

I have this query but I don't know how to add it in eloquent SELECT * FROM contactcompany WHERE recipientid = 27 GROUP BY userid

regards



via Chebli Mohamed

in laravel yes followed by consecutive 3 or more no

in laravel yes followed by consecutive 3 or more no.

is the below correct. or is it necessary to use switch? @if ($($testresult->status== 'y') Yes @elseif ($($testresult->status == 'n') Not yet @else Rejected endif



via Chebli Mohamed

Expected response code 250 but got code "550" - Laravel

reset password working well on localhost but since I uploaded the website to a live host. It is not working anymore and I guess the problem is that the "public" folder has been chagned to "public_html". "public_html" is the root for the website and I can't rename it to "public" on the live host.

Error when insert email to reset its password:

Environment & details:

GET Data empty

POST Data

_token
"H2O8QDTCu1f3T1FMFVPurbsv8P1pMAKikxIG1EjC"

email

"forexample@hotmail.com"

Here is the root

/public_html (here is the website - index.php)

/public_html/sup (css etc)

index.php

require __DIR__.'/../public_html/sup/vendor/autoload.php';

$app = require_once __DIR__.'/../public_html/sup/bootstrap/app.php';

mail.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    'driver' => env('MAIL_DRIVER', 'smtp'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', '****@gmail.com'),
        'name' => env('MAIL_FROM_NAME', config('app.name')),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

.env

APP_NAME=****
APP_ENV=local
APP_KEY=base64:****
APP_DEBUG=true
APP_URL=******
APP_URL_IN_VIEW=*****

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=*****
DB_USERNAME=*****
DB_PASSWORD=****
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=1440
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=*****@gmail.com
MAIL_PASSWORD=app pass
MAIL_ENCRYPTION=tls

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

How can I fix this issue?



via Chebli Mohamed

how to redirect logged in user to specific view on some conditions?

i already read this answer laravel 5 redirect user after login based on user's role

but it is not helpful for me consider role 3 user is loged in already and he is woking in application

i want that on his every acation this function should run and check his status

if his admin change his status to 1 then on his(role 3 user) every action on click to any button he must be(role 3 user) redirected to given url

    public function check(){
     
     if(Auth::user()->role == 3)
        
        {
        $seller =  Seller::where('id' , Auth::id())->pluck('status')->first(); 
        if ($seller == 1){
        return redirect()->route('unconfirmed.orders')->with('error', 'please verify order first');
        } 
    }
}

i want to know in which file i have work in



via Chebli Mohamed

dimanche 23 mai 2021

how to create thing for each 10 created?

I need to create every 10 records of the new <ul> to store the rest. The idea is that every 10 <li> he creates another <ul> block that will contain 10 more and so on.

What is returned from the bank in blade: enter image description here

As I'm trying to do with result now: enter image description here

Can someone help me?



via Chebli Mohamed

How to Replace FCM with VAPID, I have push panel i want to replace my old fcm function to vapid

my developer built this panel, it is built in laravel framework. it uses firebase cloud messagingg (fcm) to send notification. now i after some research i know that push can be send without fcm with the help of VAPID. so dear freinds, please tell is there any way to shift from fcm to vapid?



via Chebli Mohamed

Laravel Eloquent use nested relationship to construct eloquent collection

I would like to pull the record subscription detail record and the plans and cheats that the particular user subscribes. Aside from that, I also included all my relationship that is available in my model(s).

 User Model
 Columns: id, username, email
 public function plans(){
        return $this->belongsToMany(Plan::class,"subscriptions","user_id","plan_id");
 }

Subscription Model
Columns: id, plan_id, user_id, expiry,dll_type


Plan Model
Columns: id, cheat_id, currency_code, country,amount
public function cheatinfo($val){
      return $this->hasOne(Cheat::class,'cheat_id','id');
}
 

Cheats Model
Columns: id, internal_subscription_name, cheat_name, isActive
public function plans(){
       return $this->hasMany(Plan::class)->select(['id','cheat_id','country','currency_code','amount']);
}

This is my attempt and this is my current function caller, by the way, I am new for Laravel Eloquent at the moment.

User::whereId(2)->with(["plans"])->first();

Current output:

{
    "resp": {
        "id": 2,
        "name": "qx.wong",
        "email": "user@gmail.com",
        "email_verified_at": null,
        "created_at": "2021-05-23T07:05:13.000000Z",
        "updated_at": "2021-05-23T07:05:13.000000Z",
        "plans": [
            {
                "id": 5,
                "country": "MY",
                "amount": 40,
                "currency_code": "MYR",
                "cheat_id": 3,
                "created_at": "2021-05-23T04:43:04.000000Z",
                "updated_at": "2021-05-23T04:43:04.000000Z",
                "pivot": {
                    "user_id": 2,
                    "plan_id": 5
                }
            }
        ]
    }
}

Expected output:

{
    "resp": {
        "id": 2,
        "name": "qx.wong",
        "email": "user@gmail.com",
        "email_verified_at": null,
        "created_at": "2021-05-23T07:05:13.000000Z",
        "updated_at": "2021-05-23T07:05:13.000000Z",
        "subscription": {
            "expiry":"2020-05-04",
            "dll_type":"2021",
            "plans":[{
                "id": 5,
                "country": "US",
                "amount": 10,
                "currency_code": "USD",
                "cheat_id": 3,
                "created_at": "2021-05-23T04:43:04.000000Z",
                "updated_at": "2021-05-23T04:43:04.000000Z",
                "pivot": {
                    "user_id": 2,
                    "plan_id": 5
                },
               "cheats":{
                    "id":3,
                    "internal_subscription_name":"pubg-ultimate-02",
                    "cheats_name":"PUBG Ultimate 2",
                    "isActive":1
               }
            }]
        }
    }
}


via Chebli Mohamed

samedi 22 mai 2021

Undefined variable in app.blade.php laravel5.4

i want to list the name of courses from my database in my navbar menu (app view) :

    @foreach ($cours as $cour)
                <li><a class="dropdown-item"></a></li>
                @endforeach

and i created my layoutcontroller to display the view :

    class layoutController extends Controller
{
    public function showView()
    {
        $cours = DB::table('cours')->select('id','nom')->get();
        return view('app',['cours' => $cours]);
    }
    
   
}

then i made a route for it :

    Route::get('#','layoutController@showView');

the problem is when i navigate to login view for exemple it shows an error that the variable cours is undefined in my app layout view :

Undefined variable: cours (View: C:\wamp64\www\opencourses\resources\views\layouts\app.blade.php) (View: C:\wamp64\www\opencourses\resources\views\layouts\app.blade.php)

here is my login view :




@extends('layouts.app')
@section('content')


<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 offset-md-2 px-3 py-3 pt-md-4 pb-md-4">
            <div class="card">
                <div class="card-header">Connexion</div>
             
                <div class="card-body">
                    <form class="form-horizontal" method="POST">
                    
                    
                        
                        <div class="row mb-3">
                            <label for="email" class="col-sm-3 offset-sm-1 col-form-label">Adresse Email</label>
                            <div class="col-sm-7">
                              <input type="text" class="form-control" id="email" name="email">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <label for="password" class="col-sm-3 offset-sm-1 col-form-label">Mot de passe</label>
                            <div class="col-sm-7">
                              <input type="password" class="form-control" id="password" name="password">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="offset-sm-4 col-sm-7">
                              <button type="submit" class="btn btn-primary">Envoyer</button>
                            </div>
                        </div>
                    

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>


@endsection


and here is my app view :

<!doctype html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    
    <title>Mon blog</title>
    <link rel="icon" href="https://www.jsdelivr.com/img/icon_256x256.png">

    

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css">
    
    <!-- other CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/css/flag-icon.min.css" rel="stylesheet"/>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- Bootstrap javascript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  
  <body>
    <nav class="navbar navbar-expand-md navbar-light p-3 px-md-4 mb-3 bg-body border-bottom shadow-sm">
      <div class="container-fluid">
        <a class="navbar-brand" href="welcome.html">
            <img src="https://www.jsdelivr.com/img/icon_256x256.png" width="30" height="30" class="d-inline-block align-top" alt=""> Mon blog
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav ms-auto mb-2 mb-lg-0 d-flex">
            <li class="nav-item px-2">
              <a class="nav-link active" aria-current="page" href="<?php echo url('')?>">Accueil</a>
            </li>
            <li class="nav-item dropdown px-2">
              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                Articles
              </a>
              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                @foreach ($cours as $cour)
                <li><a class="dropdown-item"></a></li>
                @endforeach
              </ul>
            </li>
            <!-- si utilisateur non authentifié -->
            @guest
            <li class="nav-item px-2">
                <a class="btn btn-outline-primary me-2" href="<?php echo url('login')?>">Connexion</a>
            </li>
            <li class="nav-item px-2">
                <a class="btn btn-primary" href="<?php echo url('register')?>">S'inscrire</a>
            </li>
            @else
            <!-- si utilisateur authentifié -->
            <li class="nav-item px-2">
                <a class="nav-link" href="home">Mon compte</a>
            </li>
            <li class="nav-item px-2">
                <a class="nav-link" href=""  onclick="event.preventDefault();
                document.getElementById('logout-form').submit();">Déconnexion</a>
            </li>
            @endguest
          </ul>
          <form id="logout-form" action="" method="POST" style="display: none;">
            
        </form>
        </div>
      </div>
    </nav>

    @yield('content')

    <footer class="container pt-4 my-md-5 pt-md-5 border-top">
        <div class="row">
          <div class="col-12 col-md">
            <img class="mb-2" src="https://www.jsdelivr.com/img/icon_256x256.png" alt="" width="24" height="24">
            <small class="d-block mb-3 text-muted">&copy; 2017–2021</small>
          </div>
          <div class="col-6 col-md">
            <h5>Features</h5>
            <ul class="list-unstyled text-small">
              <li><a class="link-secondary" href="#">Team feature</a></li>
              <li><a class="link-secondary" href="#">Stuff for developers</a></li>
              <li><a class="link-secondary" href="#">Another one</a></li>
              <li><a class="link-secondary" href="#">Last time</a></li>
            </ul>
          </div>
          <div class="col-6 col-md">
            <h5>Resources</h5>
            <ul class="list-unstyled text-small">
              <li><a class="link-secondary" href="#">Resource name</a></li>
              <li><a class="link-secondary" href="#">Another resource</a></li>
            </ul>
          </div>
          <div class="col-6 col-md">
            <h5>About</h5>
            <ul class="list-unstyled text-small">
              <li><a class="link-secondary" href="#">Privacy</a></li>
              <li><a class="link-secondary" href="#">Terms</a></li>
            </ul>
          </div>
        </div>
    </footer>


    
  </body>
</html>


via Chebli Mohamed

The best component or plugin to achieve this table with crud in laravel 8

The best component or plugin to achieve this table with crud in laravel 8.x

screenshot



via Chebli Mohamed

Does artisan cache:clear also remove lighthouse cache?

I am getting this error in production:

exception: "Nuwave\Lighthouse\Exceptions\DefinitionException" file: "/var/www/app/vendor/nuwave/lighthouse/src/Schema/TypeRegistry.php" line: 95 message: "Lighthouse failed while trying to load a type: CreateTicketInput↵↵Make sure the type is present in your schema definition.↵" trace: [,…]

and someone advices to clear lighthouse cache here

But I already used to clear laravel cache with artisan cache:clear So my question is: Does artisan cache:clear also remove lighthouse cache?



via Chebli Mohamed

vendredi 21 mai 2021

how create 1 beteween 10 ? [closed]

I tried to do it like this but it didn't work

<li class="first-level-item">
<a class="first-level-item-text u-blk "
    href=""
    title=""
    data-category-name="">
    
</a>

@for ($i = 0;$i < $category->recursiveChildrens->count(); $category->recursiveChildrens->count()++)
    @if ($category->recursiveChildrens->count()[$i])

        <ul class="menu-second-level">
            @each('partials.header.menu.sub-category', $category->recursiveChildrens, 'subCategory')
        </ul>
        
    @endif
@endfor

enter image description here



via Chebli Mohamed

Error executing "SendRawEmail" on "https://ift.tt/3hIzZ7S"; AWS HTTP laravel 5.2

I am using Amazon ses but i am getting error Please help me on this in laravel 5.2.My email and domain is verified on aws ses.I am attaching error screenshot please anyone help me on this.enter image description here



via Chebli Mohamed

Renaming Json in laravel

I have some doubt regarding the json format in laravel... i have enclosed my return json and expected json below, Can anyone help me with these.

{
    "message": [
        {
            "0": {
                "32": "TK238"
            },
            "selectedColumn": "tank",
            "selectedField": "1",
            "mode": "Dynamic",
            "keylabel": "32"
        },
        {
            "0": {
                "33": "HOF-MIXED-C4S"
            },
            "selectedColumn": "material",
            "selectedField": "2",
            "mode": "Dynamic",
            "keylabel": "33"
        }
    ]
}

And my expected json is to be

{
  "message": [
      {
          
          "value": "TK238",
          "selectedColumn": "tank",
          "selectedField": "1",
          "mode": "Dynamic",
          "keylabel": "32"
      },


      {
         
          "value": "HOF-MIXED-C4S",
          "selectedColumn": "material",
          "selectedField": "2",
          "mode": "Dynamic",
          "keylabel": "33"
      }
  ]
}

i want the return json to be return in the above format and my laravel controller :

$result = DB::connection('mysql1')->table($tableName)->select("$selectedcolumn AS Value")->where('id', '=', $selectedField + 1)->get();
                $result['selectedColumn'] = $data[$i]['selectedColumn'];
                $result['selectedField'] = $data[$i]['selectedField'];
                $result['mode'] = $data[$i]['mode'];
                $result['keylabel'] = $data[$i]['keylabel'];
 array_push($resultArray, $result);
            }
        }

        return response()->json([
            'message' => $resultArray
        ]);

Can anyone help with out with these thanks in advance.



via Chebli Mohamed

Trying to access array offset on value of type null (View: C:\xampp\htdocs\pro3\ecommerce\resources\views\backend\category\sub_subcategory_view.blade [duplicate]

the sub_subcategory_view page doesn't open i works in aonther page i just copied the same code in that page and pasted in this page to customize it

enter image description here

this in the buttom in sidebar page when i click on it it should take me to sub_subcategory view it's work but with error

  <li class=""><a href=""><i class="ti-more"></i>All Sub->SubCategory</a></li>

this is the route

Route::prefix('category')->group(function(){
 

    // admin Sub subcategory all route
    Route::get('/sub/sub/view',[SubCategoryController::class,'SubSubCategoryView'])->name('all.subsubcategory');
    });

this sub_subcategory_view.blade.php page

@extends('admin.admin_master')
@section('admin')
 
      <div class="container-full">
        <!-- Content Header (Page header) -->
        
 
        <!-- Main content -->
        <section class="content">
          <div class="row">
              
        
        
 
            <div class="col-8">
 
             <div class="box">
                <div class="box-header with-border">
                  <h3 class="box-title">Sub->SubCategory List</h3>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <div class="table-responsive">
                      <table id="example1" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Category </th>
                                <th>SubCategory Name</th>
                                <th>Sub-Category Name English</th>
                                
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                          @foreach($subsubcategory as $item)
     <tr>
        <td>   </td>
        <td></td>
         <td></td>
        <td width="30%">
 <a href="" class="btn btn-info" title="Edit Data"><i class="fa fa-pencil"></i> </a>
 
 <a href="" class="btn btn-danger" title="Delete Data" id="delete">
    <i class="fa fa-trash"></i></a>
        </td>                        
     </tr>
      @endforeach
                        </tbody>
                        
                      </table>
                    </div>
                </div>
                <!-- /.box-body -->
              </div>
              <!-- /.box -->         
              <!-- /.box -->          
            </div>
 
<div class="col-4">
 
             <div class="box">
                <div class="box-header with-border">
                  <h3 class="box-title">Add SubCategory</h3>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <div class="table-responsive">
                       <form method="post" action="" >
        @csrf
                       
 
     <div class="form-group">
        <h5>Basic Select <span class="text-danger">*</span></h5>
        <div class="controls">
            <select name="category_id"  class="form-control" >
                <option value="" disabled="" selected="">Select Category</option>
                @foreach($categories as $category)
                <option value=""></option>
                @endforeach
                
            </select>
        <div class="help-block"></div></div>
         @error('category_id') 
     <span class="text-danger"></span>
     @enderror  
    </div>
 
 
    <div class="form-group">
        <h5>SubCategory  English <span class="text-danger">*</span></h5>
        <div class="controls">
     <input type="text" name="subsubcategory_name_en" class="form-control" >
     @error('subsubcategory_name_en') 
     <span class="text-danger"></span>
     @enderror 
      </div>
    </div>
    <div class="form-group">
        <h5>SubCategory  Arabic <span class="text-danger">*</span></h5>
        <div class="controls">
     <input type="text" name="subsubcategory_name_ar" class="form-control" >
     @error('subsubcategory_name_ar') 
     <span class="text-danger"></span>
     @enderror 
      </div>
    </div>
         <div class="text-xs-right">
    <input type="submit" class="btn btn-rounded btn-primary mb-5" value="Add New">                   
                        </div>
                    </form>
                    </div>
                </div>
                <!-- /.box-body -->
              </div>
              <!-- /.box -->
              <!-- /.box -->          
            </div>
 
 <!-- Add sub sub Category Page --> 
            <!-- /.col -->
          </div>
          <!-- /.row -->
        </section>
        <!-- /.content -->
      </div>
      @endsection

this is the subcateegory controller

public function SubSubCategoryView(){
 
     $categories = Category::orderBy('category_name_en','ASC')->get();
        $subsubcategory = SubCategory::latest()->get();
        return view('backend.category.sub_subcategory_view',compact('subsubcategory','categories'));
     }

this is the table

enter image description here

thanks in advance



via Chebli Mohamed

jeudi 20 mai 2021

Sum and group by month using Laravel Eloquent

I am using Laravel 5.6 and postgres 11.

I log changes in quantity of different equipment types which look something like this:

{location_id: 1, equipment_type_id: 1, qty: 5, total: 5, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 1, qty: 5, total: 10, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 2, qty: 5, total: 5, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 1, qty: 5, total: 15, date: 'YYYY-MM-DD'} etc

I am wanting to be able to get the sum of the total per type grouped by month BUT I only want to get the most recent total for a type and location within the same month. For example if location 1 has 3 entries for type 1, I want to sum the last entry for the month.

Returned data to look something like this:

{type: 1, data: [{month: Jan, total: 15}]},
{type: 2, data: [{month: Jan, total: 10},{month: Feb, total: 15}]}

I had a quick go but this type of query is well over my head:

$singles = EquipmentLog::where('equipment_type_id', '=', 3)
            ->select(
                DB::raw('sum(total) as total'), 
                DB::raw("DATE_TRUNC('month',logged_at) as month")
            )
            ->groupBy('month')
            ->get();

        $totals = [
            ['name' => 'Hives - Single', 'data' => $singles],
        ];


via Chebli Mohamed

Want to run laravel project using port 666 and not using 80 port, with https:// , how to do it? [closed]

For example, there is a site https://abc.xyz.com/login This is a laravel project I want run this site by https://abc.xyz.com:666/login What should I do it for this kind of scenario ?



via Chebli Mohamed

Laravel simple request is toooooo slow

I have a problem: When trying to get a single user from the database using laravel controller response is just too slow. Response time is over 1000ms, see Postman screenshot below.

Below is my code:

Controller:

public function getUserData(Request $request)
{
    return User::where('id',3)->select('name')->first();
}

web.php

Route::prefix('data-controller')
->name('data.controller')
->middleware([])
->group(static function(){

    Route::get('/get-user-data', 'DataController@getUserData')->name('getUserData');
});

.env

APP_NAME=AppName
APP_ENV=production
APP_KEY=base64:MEw1jEc7qyYhz4vIgxpZIqkjkfdkjfpasdfbURtoQ67HS6KsSBajwMC0=
APP_DEBUG=false
APP_URL=127.0.0.1
LOG_CHANNEL=single

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydb
DB_USERNAME=root
DB_PASSWORD=******

#SESSION_SECURE_COOKIE=true

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

ACCESS_ALLOW_IP=
ACCESS_ALLOW_IP_ON=false

Postman screenshot

I appreciate all of you ideas and help, I'm slowly but surely loosing my mind with this problem.

Thank you in advance! If you need any more information I'll gladly provide it in this post's edit.



via Chebli Mohamed

mercredi 19 mai 2021

How to apply regex properly in Jenssegers raw() function

I tried to implement a diacritic insensitive full word search in one of my application. I wrote this query and is working fine in the MongoDB terminal (I used Robo3T).

[ Here I passed the Unicode conversion of the word 'Irène' ]

db.getCollection('rvh_articles').aggregate([
  {
    "$match":{
       "art_xml_data.article.article_title":{
          "$regex":/( |^)[i\x{00ec}\x{00ed}\x{00ee}\x{00ef}]r[e\x{00e8}\x{00e9}\x{00ea}\x{00eb}\x{00e6}][n\x{00f1}][e\x{00e8}\x{00e9}\x{00ea}\x{00eb}\x{00e6}]( |$)/,
          "$options":"I"
       }
    }
  }
])

When I tried to implement this query in jenssegers raw() function, I wrote a PHP function to build a regular expression corresponding to the search string. Which will convert each letter in the string to the corresponding Unicode and returns the regular expression.

public function makeComp($input) 
{
    $accents = array(
        /*
            I include json_encode here because:
            json_encode used in the jenssegers building query function converts diacritic charectes to 
            hexadecimal(\u). But '\u' is not supported with regex mongodb. It shows this error:
            "Regular expression is invalid: PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u"

            So I first used json_encode for each string conversion and then replaced '{\u' with '{\x'. Problem solved.
        */
        "a" => json_encode('[a{à}{á}{â}{ã}{ä}{å}{æ}]'),
        "c" => json_encode('[c{ç}]'),
        "e" => json_encode('[e{è}{é}{ê}{ë}{æ}]'),
        "i" => json_encode('[i{ì}{í}{î}{ï}]'),
        "n" => json_encode('[n{ñ}]'),
        "o" => json_encode('[o{ò}{ó}{ô}{õ}{ö}{ø}]'),
        "s" => json_encode('[s{ß}]'),
        "u" => json_encode('[u{ù}{ú}{û}{ü}]'),
        "y" => json_encode('[y{ÿ}]'),
    );
    $out = strtr($input, $accents); // replacing all possible accented characters in the input string with $accents array key value
    $out = str_replace('{\u', '\x{', $out); // replace all {\u to \x{ because PCRE does not support the \uXXXX syntax. Use \x{XXXX}.
    $out = str_replace('"', "", $out); // replace all double quotes
    return '/( |^)' . $out . '( |$)/';
}

Here is the function that I applied the MongoDB query in jenssegers raw() function.

public function getall_articles(Request $request)
{
    extract($request->all());

    if (!empty($search_key)) {
        DB::connection()->enableQueryLog();

        $search_key = $this->makeComp($search_key);

        $data = Article::raw()->aggregate([
            array(
                '$match' => array(
                    "art_xml_data.article.article_title" => array(
                        '$regex' => $search_key,
                        '$options' => 'i'
                    )
                )
            )
        ])->toArray();

        dd(DB::getQueryLog());
    }
}

This is the query log printed:

array:1 [
    0 => array:3 [
        "query" => rvh_articles.aggregate([{
            "$match":{
                "art_xml_data.article.article_title":{
                    "$regex":"\/( |^)[i\\x{00ec}\\x{00ed}\\x{00ee}\\x{00ef}]r[e\\x{00e8}\\x{00e9}\\x{00ea}\\x{00eb}\\x{00e6}][n\\x{00f1}][e\\x{00e8}\\x{00e9}\\x{00ea}\\x{00eb}\\x{00e6}]( |$)\/",
                    "$options":"i"
                }
            }
        }])
        "bindings" => []
        "time" => 620.14
    ]
]

The regular expression that I applied is not placed as it is. So the mongo returns zero results. Can anyone help me to solve this issue? I need an alternative solution to apply diacritic insensitive and case insensitive search using jenssegers raw() function.



via Chebli Mohamed

How to redirect old urls to new urls in laravel 5.4?

I am changing the structure of product urls. Previously I was saving slug with spaces in db therefore they were showing like www.mydomain.com/Some%20Product

now after changing the structure it is showing as www.mydomain.com/some-product as intended

As my old urls are indexed in google so I want to redirect them to the new ones, currently my old urls showing 404page.

kindly help me. thank you.



via Chebli Mohamed

I can't work out why this Laravel API keeps returning a 404

I have this controller:

    <?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Assetgroup;
use App\Models\Asset;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class AssetgroupController extends Controller
{
    
    
    public function __construct()
    {
        $this->middleware(['jsonvalidation:CreateAssetGroupResource'])->only('store');
        $this->middleware(['jsonvalidation:CreateAssetGroupResource'])->only('update');
    }
   
    public function update(Request $request, Assetgroup $assetgroup, Asset $asset = null)
    {
        **********


    }

This route in api.php

Route::apiResource('/assetgroups', 'API\AssetgroupController');

And it's being called fromt his axios request

Axios.put(`${API_URL}assetgroups/${division.id}`, {
            added
        }).then(r => {
            // DETECT ERROR

            toast('Users assigned!', {
                type: toast.TYPE.SUCCESS,
                autoClose: 2500
            });

            this.setState({
                added: [],
                selectedUsers: r.data.selected_users,
                saving: false,
                users: r.data.users
            });
        });

I am new to laravel, and I cannot work out why this isn't working. The browser returns a

Request URL: http://127.0.0.1:8000/api/assetgroups/22
Request Method: PUT
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin

Any help would be appreciated. Thankyou.



via Chebli Mohamed

What causes map to not display after adding authentication to Laravel 5.5 [closed]

The project was working fine before I added authentication. After first login the map displayed correctly, and then when I reloaded the page, the map div was all grey. I then went and cleared browsing data and the map show once and disappeared after reload. If I do not clear browsing data the maps do not show at all. Below is the code for one of my pages:

<div id="map"></div>

<div id="addModal" class="modal fade" aria-hidden="true" aria-label="addModalLabel">
    <div class="modalAdd">
        <div class="modal-card">
            <div class="modal-card-head">
                <div class="modal-card-title">
                    <h3>Add Marker</h3>
                </div>
            </div>
            <div class="modal-card-body">
                <form action="" method="POST">
                    
                    <div class="form-group">
                        <label for="latitude">Latitude:</label>
                        <input type="text" class="form-control" id="latitude" name="latitude" value="">
                     </div>
                     <div class="form-group">
                         <label for="longitude">Longitude:</label>
                         <input type="text" class="form-control" id="longitude" name="longitude" value="">
                     </div>
                            
                     <div class="form-group">
                         <button type="submit" class="btn btn-primary">Add</button> &nbsp;
                         <button type="cancel" class="btn btn-danger">Cancel</button>
                      </div>
                  </form>
              </div>
          </div>
      </div>
  </div>

<script>
    function initMap(){
        var myLatlng = {lat:-17.999514, lng:31.061744};
        
        var options = {
            zoom: 8,
            center: myLatlng
        }

        var map = new google.maps.Map(document.getElementById('map'), options);

        var location = '';
        var lat = '';
        var lng = '';
        map.addListener("click", (mapsMouseEvent) => {
            $('#addModal').modal('show');
            location = JSON.stringify(mapsMouseEvent.latLng.toJSON());
            lat = JSON.stringify(mapsMouseEvent.latLng.lat());
            lng = JSON.stringify(mapsMouseEvent.latLng.lng());
            var latInput = document.getElementById('latitude');
            var lngInput = document.getElementById('longitude'); 
            locationInput.value = location;
            latInput.value = lat;
            lngInput.value =lng;
        });
    }
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap&libraries=places&v=weekly" async></script>


via Chebli Mohamed

Problem import excel file and save into a table with foreign keys

Code :

class BarangImport implements ToModel, WithHeadingRow, WithValidation { use Importable;

/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
    $row['kategori'] = Kategori::where('nama_kategori', 'like', '%'.$row['kategori'].'%'); //tabel kategori 

    return new Barang([            

        'kode_barang' => $row['kode'],
        'nama_barang' => $row['nama'],
        'stok' => $row['stok'],
        'satuan' => $row['satuan'],
        'stok_minimal' => $row['stok_minimal'],
        'id_kategori' => $row['kategori'],
        'keterangan' => $row['keterangan'],
        'status' => $row['status'],
    ]);
}

public function rules(): array{
    return [
        'kode' => 'required|unique:barang,kode_barang',
        'nama'=>'required|unique:barang,nama_barang',
        'stok' =>'required|numeric',
        'stok_minimal' =>'required|numeric',
        'status' => 'required|in:aktif,tidak aktif',
        'kategori' => 'required',
        
    ];
}

public function customValidationMessages()
{
    return [
        'kode.unique' => 'Kode barang sudah digunakan',
        'nama.unique'=> 'Nama barang sudah digunakan',
        'kode.required' => 'Kolom kode masih kosong',
        'nama.required' => 'Kolom nama barang masih kosong',
        'stok.required' => 'Kolom stok masih kosong',
        'stok.numeric' => 'Kolom stok harus berupa angka',
        'stok_minimal.required' => 'Kolom stok minimal masih kosong',
        'stok_minimal.numeric' => 'Kolom stok minimal harus berupa angka',
        'status.required' => 'Kolom status masih kosong',
        'status.in' => 'Isian status tidak valid',
        'kategori'=> 'Kolom kategori masih kosong',
        
    ];
}

}

This is the file that will be imported

enter image description here

I want to import file with foreign key category_name of category table, but I am confused. Because there are many statements. You can see the query above.

How and what is wrong, please help?enter code here



via Chebli Mohamed

Why the triggered pusher data is not updated in the view (blade) file in the browser?

I have the blade file with 3 div's

welcome.blade.php

 <div id="id1">0</div>
 <div id="id2">0</div>
 <div id="id3">0</div>
 <script>
    //pusher
    var pusher = new Pusher('xxxxxxxxxxxx', {
        cluster: 'eu',
        encrypted: true
      });
   // Subscribe to the channel we specified in our Laravel Event
      var channel = pusher.subscribe('my-channel');
   // Binding a function to a Event
     channel.bind('App\\Events\\UpdatedTime', function(data){
      target = data.id;
      console.log(data);
      value = data.value;
      var div1 = document.getElementById(target);
      div1.innerHTML =value;
     });
</script>

The 0 in the div should be replaced by the value which is triggered by the event in the pusher.

I could get the event triggered in the pusher like the below in the debug console, when I pass the Id in the URL.(http://project.test/id1) enter image description here

In my controller:

 public function getTime($divId)
    {

     // pusher
        $options = array(
            'cluster' => 'ap3',
            'useTLS' => true
        );

        $pusher = new Pusher(
            env('PUSHER_APP_KEY'),
            env('PUSHER_APP_SECRET'),
            env('PUSHER_APP_ID'),
            $options
        );
        //var_dump($pusher);
        $pusher->trigger('my-channel', 'UpdatedTime', ['id' => $divId, 'value' => 1511);
        return view('welcome');


    }

Events File

  public $id, $value;
    public function __construct($id, $value)
    {
       $this->id = $id;
       $this->value = $value;
    }
    public function broadcastOn()
    {
        return new Channel('my-channel');
    }

Routes/web.php

Route::get('/getTime/{id}', 'App\Http\Controllers\TimeController@getTime');

After passing the URL in the browser, http://project.test/id2

I could only see

0
0  
0

in the browser, Actually it should be in the browser.

0
1511
0

How can I get the triggered event value in the browser? Could someone please help?

Thanks



via Chebli Mohamed

What will be condition in laravel for

How to display the condition wherein

-if for given column A the column B is "yes" followed by "two no's" then display text



via Chebli Mohamed

How to get Get Attributes and NameID from encrypted SAML Response

I am working on onelogin saml, i am getting encrypted response from onelogin, i am able to decrypt if from https://www.samltool.com/attributes.php this link, i am getting proper data in array, but how to do that programmatically ? can anyone please help me how to do that ?



via Chebli Mohamed

mardi 18 mai 2021

How can i decrypt saml response in one login from private key?

I am working saml integration, which works fine for me, i did secure saml response, for that i am using public and private key, i am getting encrypted saml response, i want to decrypt it by private key, for demo purpose i am using onelogin developer account, they given attribute extractor from this link

https://developers.onelogin.com/saml/online-tools/attribute-extractor

which works fine for me, i want to do this programmatically, but still not able to find function for it, can anyone have idea how to decrypt it programmatically ?



via Chebli Mohamed

How to setup FROM MAIL IMAGE in Laravel

I usually send emails using 3rd Party Services such as: SendGrid Service, AWS SES Service,..

I code in Laravel and there are options to set:

MAIL_FROM_ADDRESS=no-reply@acme.com
MAIL_FROM_NAME="Acme Company"

but what about Mail From Image? I mean the contact photo. Check image below Contact Email Photo

I tried to find the answer.. but the google search results do not seem to get me any answers, they keywords seems to show different results.. I don't even know what type.

Do we set this in Php Code? in SendGrid or where exactly?

Thanks



via Chebli Mohamed

DB::statement with named binding returning "SQLSTATE[HY093]: Invalid parameter number"

I have the following code:

DB::statement(
    "DO $$
    BEGIN
        DELETE FROM sku_inativacao WHERE active = true;
        
        INSERT INTO sku_inativacao (id_sku, id_motivo, created_at, updated_at) (
            SELECT 
                id_sku, 
                CASE
                    WHEN data_u_venda is null AND estoque_atual = 0 THEN 1
                    WHEN data_u_venda < current_timestamp - interval '2 years' THEN 2
                END id_motivo,
                current_timestamp AS created_at,
                current_timestamp AS updated_at
            FROM 
                sku
            WHERE
                data_criacao::timestamp < current_timestamp - interval ':diasCriacao days'
                and fase_vida < 3
            AND
                (data_u_venda is null AND 
                estoque_atual = 0)
            OR
                (data_u_venda < current_timestamp - interval '2 years')
        ) ON CONFLICT (id_sku) DO nothing;
    END $$;",
    ['diasCriacao' => $this->diasCriacao ?? 90]
);

And as far as I can see in the documentation this is correct, however with named biding it returns SQLSTATE[HY093]: Invalid parameter number: :diasCriacao and using normal bindings it returns SQLSTATE[08P01]: <<Unknown error>>: 7 ERROR:bind message supplies 1 parameters, but prepared statement "pdo_stmt_00000004" requires 0

What can I do to fix this?

I am using Laravel 5.1, sadly.



via Chebli Mohamed

Unable to export data in laravel due to 'Proxy Error'

I have developed laravel application with MySQL database. I try to download more than 5k data. But I am getting the below error from the browser.

Proxy Error The proxy server received an invalid response from an upstream server. The proxy server could not handle the request Reason: Error reading from remote server

The same query I am using for displaying data(datatable). But the datatable data is loading within 3 minutes I have increase PHP memory size to 2048Mb. I am using docker environment. There is more than 300K data in a particular database.

Can anyone help me to fix this issue?



via Chebli Mohamed

lundi 17 mai 2021

Add v-select in Tabulator

I am using tabulator in my project along with vue3. I have successfully added tabulator and now I want to add v-select in tabulator. So how is it possible and what are the ways to achieve it?



via Chebli Mohamed

Return array of grouped results

Note: I'm using Laravel 5.3.

I have a table, comments, that looks like this:

+====+=========+
| id | message |
+====+=========+
|  1 |      Hi |
|  2 |   World |
+====+=========+

I have a second table, comment_stats, which keeps track of the total number of votes on each comment, that looks like this:

+====+============+=======+
| id | comment_id | votes |
+====+============+=======+
|  1 |          1 |    10 |
|  2 |          2 |     0 |
+====+============+=======+

And lastly, I have a third table, comment_votes, which keeps track of each individual user's vote for each comment, that looks like this:

+====+============+=========+=========+
| id | comment_id | user_id |    type |
+====+============+=========+=========+
|  1 |          1 |      10 |       0 |
|  2 |          1 |       9 |       0 |
|  3 |          1 |       8 |       1 |
|  4 |          1 |       7 |       2 |
|  5 |          1 |       6 |       1 |
|  6 |          1 |       5 |       5 |
|  7 |          1 |       4 |       3 |
|  8 |          1 |       3 |       3 |
|  9 |          1 |       2 |       1 |
| 10 |          1 |       1 |       0 |
+====+============+=========+=========+

As you can see, each comment can be voted on by other users (comment_votes) and the total votes are kept track of in comment_stats. Each vote has a type. There are a total of 6 possible types (0-5).

My current Comment.php class looks like:

class Comment extends Model
{
    protected $with = [
        'votes', 'stats'
    ];

    public function votes()
    {
        return $this->hasMany('App\Vote');
    }

    public function stats()
    {
        return $this->hasOne('App\Stat');
    }
}

My Stat.php class looks like:

class Stat extends Model
{
    protected $with = [
        'topTypes'
    ];

    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }

    public function topTypes()
    {
        // Need to return an array of the top 3 types here
    }
}

And my Vote.php class looks like:

class Vote extends Model
{
    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }
}

I'd like to retrieve the top 3 vote types for each comment. So for comment_id = 1, the output would be [0, 1, 3] (as an array), in that order. 0 appears 3 times, 1 appears 3 times, and 3 appears twice. If there is a tie, it should get the lower integer type.

I'm trying to get the JSON to end up looking something like this, so that the top_types is part of stats:

{
    "id": 1,
    "message": "Hi",
    "stats": {
        "id": 1,
        "comment_id": 1,
        "votes": 10,
        "top_types": [0, 1, 3]
    }
}

How could I achieve this? All of these relationships are driving me insane.



via Chebli Mohamed

Upload multiple images in Vue.js and Laravel

I'm trying to upload multiple files at once in vue.js and laravel, Code that i'm using is :

Vue.js code:

 <input type="file" v-validate="'required'" multiple @change="uploadDegree" name="uploadDegree" placeholder="Upload Degree"/>

  uploadDegree(e)
            {
                for (let file of e.target.files) {
                    try {
                        let reader = new FileReader();
                         reader.onloadend = file => {
                         this.user.degree_attachment= reader.result;
                        };
                        reader.readAsDataURL(file);                      
                    } catch {}
                }
              }

Laravel Code:

 $files = $request->input('degree_attachment');
           foreach($files as $file) {
               $degreename = time() . '.' . explode('/', explode(':', substr($file, 0, strpos($file, ';')))[1])[1];
                $pathDegreeExist = public_path("img/degree_img/"); 
                if(!File::exists($pathDegreeExist)) File::makeDirectory($pathDegreeExist, 777);
                $img = \Image::make($file);
                $img->save(public_path('img/degree_img/').$degreename); 
                $newUser->degree_attachment = $degreename;
            }

I'm getting this error :

Invalid argument supplied for foreach()

where i'm trying to get image,



via Chebli Mohamed

Checkbox does not work when clicking on it

I change this code: Demo1[ https://ift.tt/3fmzNs3 ]

<li class="nav-item">
   <span class="nav-switch" href="#">
     <span class="language" id="eg">EG</span>
       <label class="switch">
           <input type="checkbox">
           <span class="slider round"></span>
      </label>
    <span  class="language" id="ar">AR</span>
  </span>
</li>

To this code: Demo2[ https://ift.tt/3yetcsl ]

<li class="nav-item">
   <span class="nav-switch" href="#">
     <span class="language" id="eg">EG</span>
       <a class="switch">
           <input type="checkbox">
           <span class="slider round"></span>
       </a>
    <span  class="language" id="ar">AR</span>
  </span>
</li>

To be able to take action when changing from one language to another using the checkbox but after making that change, the color of the checkbox does not change as in Demo1, I need to take action because I use PHP/Laravel



via Chebli Mohamed

dimanche 16 mai 2021

Query returns when selecting *, but not when selecting specific column

In one of my model classes, I have the following relationship/query:

public function topTypes()
{
    return $this->votes()
        ->selectRaw('*, COUNT(comment_votes.type_id) as types_count')
        ->groupBy('comment_votes.type_id')
        ->orderBy('types_count', 'desc');
}

public function votes()
{
    return $this->hasMany('App\CommentVote', 'comment_id', 'comment_id');
}

When this gets executed, it returns successfully:

            "top_types" : [
              {
                "comment_id" : 461,
                "id" : 536,
                "type_id" : 0,
                "types_count" : 1,
                "user_id" : 58
              }
            ],

But really what I want it to return is just:

            "top_types" : [0],

Where 0 is the type_id.

When I try changing the selectRaw portion of the query to:

public function topTypes()
{
    return $this->votes()
        ->selectRaw('comment_votes.type_id, COUNT(comment_votes.type_id) as types_count')
        ->groupBy('comment_votes.type_id')
        ->orderBy('types_count', 'desc');
}

It just outputs an empty array:

            "top_types" : [

            ],

What am I doing wrong here?



via Chebli Mohamed

Laravel server side form validation, Validate field length(Size) with more than one option

I'm using ajax to make a server side form validation in laravel. All my validations are working fine except for one which i can figure out how to do it. Actually i have a field in my form for the ID number, which can take either 7 caracters for passport number, 9 caracters for ID card number or 20 caracters for temporary ID card number. How can i set a validation for size or lenght with 3 differents options?

function validation(e, f) {
  var x = document.getElementsByClassName("alert-danger");
  var y = "false";
  var i;
  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });

  $.ajax({
    url: "/membre/modalValidation",
    method: "post",
    data: (e == 1) ? new FormData(document.getElementById("modal-danger4")) :
      new FormData(document.getElementById("modal-danger8")),
    processData: false,
    dataType: 'json',
    async: false,
    contentType: false,
    beforeSend: function() {
      $(document).find('.alert-danger').text('');
    },
    success: function(data) {
      if (data.status == 0) {
        $.each(data.error, function(prefix, val) {
          $('.m' + f + ' .' + prefix + '_error').text(val[0]);
        });
      } else {

      }
      for (i = 0; i < 30; i++) {
        if (x[i].innerHTML) {
          y = "true";
        }
      }
    }
  });
  return y;
}
public function modalValidation(Request $request)
    {
        $newDate = Carbon::now()->subYears(10);
        $validator = Validator::make($request->all(), [
            'firstname' => ['required'],
            'email' => ['required', 'unique:users', 'digits:9'],
            'phone' => ['nullable', 'unique:users', 'email:rfc,dns'],
            'email1' => ['required', 'unique:client__ents,email', 'digits:9'],
            'phone1' => ['nullable', 'unique:client__ents,phone', 'email:rfc,dns'],
            'name' => ['required'],
            'job' => ['required'],
            'CNI_number' => ['required', 'unique:users', 'digits_between:7,20'],
            'CNI_date' => ['required', 'date_format:d/m/Y', 'after:'.$newDate],
            'CNI_place' => ['required'],
            'raison_sociale' => ['required'],
            'forme_juridique' => ['required'],
            'siteWeb' => ['nullable', 'url'],
            'activité' => ['required'],
            'num_contribuable' => ['required', 'unique:client__ents,Numero_contribuable', 'between:13,14'],
            'NC_date' => ['required', 'date_format:d/m/Y', 'after:'.$newDate],
            'siège' => ['required'],
            'email2' => ['required', 'unique:responsable_ents,email', 'digits:9'],
            'phone2' => ['nullable', 'unique:responsable_ents,phone', 'email:rfc,dns'],
            'CNI_number1' => ['required', 'unique:responsable_ents,CNI_number', 'digits_between:7,20'],
            'password' => ['required', 'min:8'],
            'confirm_password' => ['same:password'],
            'checkbox' => ['accepted'],
        ],
        ['confirm_password.same' => 'Ne correspond pas',
        'accepted'=>'Veuillez cocher la case avant de continuer',
        'required'=>'Ce champ est obligatoire',
        'phone.unique'=>'Un utilisateur avec ce mail existe déjà',
        'email.unique'=>'Un utilisateur avec ce numéro existe déjà',
        'phone1.unique'=>'Un utilisateur avec ce mail existe déjà',
        'email1.unique'=>'Un utilisateur avec ce numéro existe déjà',
        'phone2.unique'=>'Un responsable avec ce mail existe déjà',
        'email2.unique'=>'Un responsable avec ce numéro existe déjà',
        'CNI_number.unique'=>'Un utilisateur avec ce numéro de CNI existe déjà',
        'CNI_number1.unique'=>'Un responsable avec ce numéro de CNI existe déjà',
        'num_contribuable.unique'=>'Un utilisateur avec ce numéro de contribuable existe déjà',
        'digits'=>'Veuillez saisir un numéro valide à 9 chiffres',
        'digits_between'=>'Numéro CNI(Passeport) non-conforme',
        'email'=>'Ce mail est invalide. Doit inclure @',
        'date_format'=>'Invalide. Veuillez saisir une date',
        'CNI_date.after'=>'Votre CNI ou Passeport ou Récépissé est expiré',
        'NC_date.after'=>'Votre Numéro de contribuable est expiré',
        'url'=>'Invalide. Veuillez saisir un URL',
        'password.min'=>'Minimum 8 caractères',
        'num_contribuable.between'=>'Numéro de contribuable non-conforme',
    ]);
   
        if ($validator->fails())
        {
            return response()->json(['status'=>0, 'error'=>$validator->errors()->toArray()]);
        }
    }
<div class="modal-body step-2 m2">
  <center>
    <h4>Pièce d'identité</h4>
  </center>
  <div class="form-group">
    <label>Numéro CNI(ou Passeport)<i style="color:#FF0000">*</i> :</label>

    <input type="number" name="CNI_number" class="form-control" placeholder="Entrer le numéro CNI">
    <div class='alert-danger CNI_number_error'></div>
  </div>
  <div class="form-group">
    <label>Date de délivrance<i style="color:#FF0000">*</i> :</label>

    <input id="demo-one-input" name="CNI_date" class="form-control" placeholder="Entrer la date">
    <div class='alert-danger CNI_date_error'></div>
  </div>
  <div class="form-group">
    <label>Lieu de délivrance<i style="color:#FF0000">*</i> :</label>

    <input type="text" name="CNI_place" class="form-control" placeholder="Entrer le lieu">
    <div class='alert-danger CNI_place_error'></div>
  </div>
  <div class="form-group">
    <label>Votre photo :</label>

    <input type='file' accept="image/*" name="photo" class="form-control" placeholder="image portrait">
  </div>
  <div class="form-group">
    <i style="color:#FF0000">*</i> Champs obligatoires
  </div>
</div>


via Chebli Mohamed