samedi 30 novembre 2019

update one to many using laravel eloquent

I have two models one Purchase.php and PurchaseItem.php

Purchase.php

public function purchase_items()
{
    return $this->hasMany('PurchaseItem', 'purchase_id');
}

And PurchaseItem.php

public function purchase()
{
    return $this->belongsTo('App\Models\Purchase', 'purchase_id');
}

Users can purchase multiple items at a time that he wants. During update purchase, users can choose different items. In that case, some old items may remove and some new items added. So what is the best way to update the tables? I can remove all existing items and insert the newly added item during the update purchase. But I want to know the best practice in this case.

Thanks



via Chebli Mohamed

Laravel 5 : Is there any way to chain many to many relation with one to many relation?

I have three tables in my database : 1) Teacher 2) Course 3) Timetable

Teacher and Course tables are connected through many to many relationship as each teacher can teach many courses and each course can have many teachers:

-----------------          ------------------------         ----------------      
     Teacher                   CourseTeacher                    Course
-----------------          -------------------------        ----------------
id         name            id  course_id   teacher_id        id       name
1          John             1    1            1              1       English

Teacher -> ManyToMany -> Course

Now foreach course , a teacher can have a many days with time on which he teaches that specific course,so there would be another table named timetable which has the following structure:

---------------------------------------------------
                     TimeTable
----------------------------------------------------
id    day         time       teacher_id    course_id
1     monday      10:00 pm     1              1
2     tuesday     10:00 pm     1              1

Now the question is how can i connect the timetable table with CourseStudent relation through one to many relationship . For each teacher teaching the course i need to save the timetable of teacher for that specific course .

Teacher -> ManyToMany -> Course
          |
          |
     One to Many
          |
      TimeTable


via Chebli Mohamed

Laravel Cashier 10 - Stripe payment element empty

I am trying to show a Stripe payment element, but it's not showing.

Using dd() statements, I can tell that the user PaymentMethods is empty (as expected for a new user) and the Intent is not null.

show() method in PlanController.php:

    public function show(Plan $plan, Request $request)
    {
        $user = $request->user();
        $user->createOrGetStripeCustomer();
        $paymentMethods = $user->paymentMethods();
        $intent = $user->createSetupIntent();
        return view('plans.show', compact('plan', 'intent'));
    }

Javascript, truncated because SO won't let me post it all:

<script src="https://js.stripe.com/v3/"></script>
    ...
    // Submit the form with the token ID.
    function stripeTokenHandler(paymentMethod) {
        // Insert the token ID into the form so it gets submitted to the server
        var form = document.getElementById('payment-form');
        var hiddenInput = document.createElement('input');
        hiddenInput.setAttribute('type', 'hidden');
        hiddenInput.setAttribute('name', 'paymentMethod');
        hiddenInput.setAttribute('value', paymentMethod);
        form.appendChild(hiddenInput);

        // Submit the form
        form.submit();
    }


via Chebli Mohamed

How can I get available datetime or datetime range by comparing from user x's schedule and user y's schedule

How can I get available datetime or datetime range by comparing from user x's schedule and user y's schedule.

Result should be as drop-down list of available datetime(s) for both users.

if user x available on 30/11/2019 15:00 and user y is also available on the same time. As result I can schedule them.

Could be done in JavaScript / Lodash.

I can't think of script which would able to do this.

With kind regards, Vic.



via Chebli Mohamed

Submitting larger images with Ajax Jquery to Laravel Controller

I'm trying to upload images to the database using Ajax Jquery.It works fine for small files (less than 100kb) and gets uploaded to the database. I have changed the php.ini for file uploading limits(upload_max_filesize = 40M) and post upload limits to 40M(post_max_size = 41M) and tried to upload an image with 300kb but still nothing. When i click on console, i see "No response data".

Controller

  public function store(Request $request)
{

   // ($request->all());
    $formInput=$request->except('filename');

    $product = product::create(array_merge($formInput, [
        'seller_id'=> Auth::user()->id,
        'user_id' => Auth::user()->id
    ]));
    foreach ($request->photos as $photo) {
       $filename = $photo->store('public/photos');
        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);
    }

}

Ajax

var token = $("#token").val();
$(document).ready(function(){
$("#btn").click(function(){
    var url = '';
    var form = $('form')[0]; 
    var formData = new FormData(form);
    formData.append('_token', token); // adding token
    $.ajax({
        url: url,
        data: formData, 
        type: 'POST',
        contentType: false,
        processData: false, 
        success:function(data){
         console.log(data);
        }
    });
  });
});


via Chebli Mohamed

How to print the error message of an exception of errorUserTitle

I am catching an exception on my system. The exception is thrown when I try to create a facebook ad with value less than 1.32.

I need to print the exception error message to the user. I can not print.

If I use dd ($ e) it prints this:

enter image description here

But I return $e or use json_decode ($e, true) it returns empty.

Does anyone know how I can print the error message of errorUserTitle?



via Chebli Mohamed

Submitting large files Laravel and Ajax

I have a form where user submit and add product with multiple images to the database through Ajax request. The problem is when I choose a lower(12kb) image it save the product but if it is large file(1mb) or (400kb) it doesn't save the product. I have set the limit of upload to 10000mb, how can I fix this issue?

Controller

  public function store(Request $request)
{

   // ($request->all());
    $formInput=$request->except('filename');

    $product = product::create(array_merge($formInput, [
        'seller_id'=> Auth::user()->id,
        'user_id' => Auth::user()->id
    ]));
    foreach ($request->photos as $photo) {
       $filename = $photo->store('public/photos');
        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);
    }

}

Ajax

 var token = $("#token").val();
 $(document).ready(function(){
 $("#btn").click(function(){
    var form = $('form')[0]; 
    var formData = new FormData(form);
    formData.append('_token', token); // adding token
    $.ajax({
        url: "<?php echo url('seller/product') ?>",
        data: formData, 
        type: 'POST',
        contentType: false, 
        processData: false,
        success:function(data){
         console.log(data);
        }
    });
  });
});


via Chebli Mohamed

Authentication redirect route

can you help me how to create if isadmin is true it will be redirected to admin page, else home page.

AuthController

public function postLogin(Request $request){
       if(!auth()->attempt(['email' => $request->email, 'password' => $request->password])){
        return redirect()->back();
       }
       return redirect()->route('home');
    }

the main reason's maybe because this

return redirect()->route('home');

when tried change to ('admin') it successfully redirecting.

when i tried to add

protected function authenticated(\Illuminate\Http\Request $request, $user)
    {
        if( $user->isadmin){
           return redirect('admin');
        }
        return redirect('home');
    }

it didnt works too



via Chebli Mohamed

How to handle the data received to save it in the database Laravel and Ajax?

I'm trying to add the product with multiple images to the database without refreshing the page, I don't get any errors on console but I see the long text which starting like this <script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = .... and the error comes from this line console.log(data);. The product has a relationship with ProductsPhoto,how can I make it add the product to the database?

Controller

 public function store(Request $request)
 {
    $formInput=$request->except('filename');

    $product = product::create(array_merge($formInput, [
        'seller_id'=> Auth::user()->id,
        'user_id' => Auth::user()->id
    ]));
    foreach ($request->photos as $photo) {
       $filename = $photo->store('public/photos');
        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);
    }
}

Blade

  <div class="panel-body">

   <input type="hidden" value="" id="token"/>

     <label for="pro_name">Name</label>
      <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

        <label for="pro_price">Price</label>
           <input type="text" class="form-control" name="pro_price" id="pro_price" placeholder="Enter price">

        <label for="pro_info">Description</label>
         <input type="text" class="form-control" name="pro_info" id="pro_info" placeholder="Enter product description">

           <label for="stock">Stock</label>
            <input type="text" class="form-control" name="stock" id="stock" placeholder="Enter stock">

        <label  for="category_id">Choose Category</label>
           <select name="category_name" id="category_name">
             <option value=""> --Select Category -- </option>
               @foreach ($categoryname_array as $data)
                <option value=""  ></option>
                 @endforeach
               </select>

 <label for="photos">Choose 5 Images</label>
  <input  "multiple="multiple" id="photos" name="photos[]" type="file">

  <input type="submit" class="btn btn-primary" value="Submit" id="btn"/>

</div>

Ajax

   $(document).ready(function(){
   $("#btn").click(function(){
    var category_name = $("#category_name").val()
    var pro_name = $("#pro_name").val();
    var pro_price = $("#pro_price").val();
    var stock = $("#stock").val();
    var pro_info = $("#pro_info").val();
    var photos = $("#photos").val();
    var token = $("#token").val();

    $.ajax({

        type: "post",
        data: "pro_name=" + pro_name + "&pro_price=" + pro_price + "&stock=" + stock + "&_token=" + token + "&category_name=" + category_name + "&pro_info=" + pro_info + "&photos=" + photos,
        url: "<?php echo url('seller/product') ?>",
        success:function(data){
        console.log(data);
        }

    });
  });
});

Route

 Route::post('seller/product', 'ProductController@store')->name('product.store');


via Chebli Mohamed

MapBox problem while drawing line between two points with positive / negative longitude in Laravel 5.8

I have an application where I want to draw an arc / line between two locations. Everything works fine but when I want to draw a line between two points ( 1 with positive longitude like China --- 2nd with negative longitude like USA ). It draws an additional line somewhere near or exactly on equator line. see image enter image description here

Help in this regard is requested please. I have pasted the coordinates as well from code.

    //Coords for some place in China
    $from_lng = 115.5781792430219; //16.763;
    $from_lat = 36.204409420941516; //41.138;
    $results['from_coord'] = array($from_lng, $from_lat);

    //Coords for some place in USA
    $to_lng = -122.42963325696385; //9.515;
    $to_lat = 39.804333950461285; //40.901;
    $results['to_coord'] = array($to_lng, $to_lat);


    //Calculating average to center map
    $results['posn'] = array(
      ($from_lng + $to_lng)/2,
      ($from_lat + $to_lat)/2
    );


via Chebli Mohamed

Argument 1 passed to Illuminate\\Database\\Query\\Builder::cleanBindings() must be of the type array, string given

I update 2 data, the first data is in the normal table, the second data uses EAV, therefore I have to use where to update the data that has the input ID

What im doing wrong..im getting this error..

this my controller

this is normal table
 $vendor = Vendor::find($request->id);
        $vendor->is_active = '0';
        $vendor->name = $request->name;
        $vendor->address = $request->address;
        $vendor->save();
this is EAV Table

        $values=array('detail'=> $request->detail,
                      'join_at'=>  Carbon::now(),
                    );
        VendorDetail::whereIn('vendor_id',$request->id)->update($values);



via Chebli Mohamed

API give result as per usertype

Usertypes table

User Table enter image description here

I want to create api which give data particular user_type_id.. when i click api/usertype/1 than show only player list of user



via Chebli Mohamed

vendredi 29 novembre 2019

mercadopago Fix Payment Gateway Issue

ShoppingcartController.php:- middleware('auth'); View()->share('classBody', 'shopping-cart'); $this->productRepository = $productRepository; $this->addressRepository = $addressRepository; View()->share('menuCart', true); } public function index() { SDK::setClientId("2080473907061160"); SDK::setClientSecret("DYju8iZXB6qli9GRI62VwiSFYe9AvSjf"); SDK::setAccessToken("TEST-5707324772516829-092412-d2598a4ac035e78f2a4dfffbf74648e1-293324417"); SDK::setAccessToken("APP_USR-2080473907061160-092412-dbf5e910b023e44f194553d0d90a7b15-293324417"); $ids = []; $addresses = []; $setting = null; $cart = session('items', []); foreach($cart as $item){ $ids[] = $item['id']; } $products = $this->productRepository->findWhereIn('id', $ids); $products = $this->productRepository->inject($products); $cards = array(); $setting = getSettingInstance(); if(auth()->check()){ $addresses = $this->addressRepository->findWhere(['user_id' => auth()->user()->id]); if(isset(auth()->user()->mercadopago_customer_id) && !empty(auth()->user()->mercadopago_customer_id)){ echo "hello"; exit(); $customer = MercadoPago\Customer::find_by_id(auth()->user()->mercadopago_customer_id); $cards = $customer->cards(); } } $crossSelling = $this->productRepository->crossSelling($ids); return view('shopping_cart.index', compact('products', 'cart', 'addresses', 'setting', 'crossSelling','cards')); } public function add() { $post = request()->all(); $product = $this->productRepository->find($post['id']); if(! $product){ return response()->json(['status' => 'failed', 'message' => 'Producto no encontrado o no es válido']); } $items = session('items', []); if(array_key_exists($product->id, $items)){ $items[$product->id]['qty'] = (int)$items[$product->id]['qty'] + (int)$post['qty']; $items[$product->id]['variant'] = $post['variant']; }else{ $items[$product->id] = [ 'id' => $product->id, 'qty' => $post['qty'], 'variant' => $post['variant'] ]; } session()->put('items', $items); return response()->json(['status' => 'ok']); } public function add2() { $post = request()->all(); $product = $this->productRepository->find($post['id']); if(! $product){ return response()->json(['status' => 'failed', 'message' => 'Producto no encontrado o no es válido']); } $items = session('items', []); if(array_key_exists($product->id, $items)){ $items[$product->id]['qty'] = (int)$items[$product->id]['qty'] + (int)$post['qty']; $items[$product->id]['variant'] = $post['variant']; }else{ $items[$product->id] = [ 'id' => $product->id, 'qty' => $post['qty'], 'variant' => $post['variant'] ]; } session()->put('items', $items); return response()->json(['status' => 'ok']); } function delete($id){ $product = $this->productRepository->find($id); if(! $product){ return response()->json(['status' => 'failed', 'message' => 'Producto no encontrado o no es válido']); } $items = session('items', []); if(array_key_exists($product->id, $items)){ unset($items[$product->id]); } session()->put('items', $items); request()->session()->flash('alert_success', "El producto ha sido eliminado del carrito"); return response()->redirectTo(route('web.cart.index')); } function update(){ $cart = request()->all(); $items = session('items', []); foreach($cart as $id => $product){ if(array_key_exists($id, $items)){ $items[$id]['qty'] = (int)$product['qty']; $items[$id]['variant'] = $product['variant']; } } session()->put('items', $items); request()->session()->flash('alert_success', "EL carrito ha sido actualizado con éxito"); return response()->redirectTo(route('web.cart.index')); } public function save(){ $post = request()->all(); $products = (array_key_exists('productos', $post)) ? $post['productos'] : []; $dispatch = (array_key_exists('dispatch', $post)) ? $post['dispatch'] : null; $address = (array_key_exists('address', $post)) ? $post['address'] : null; $date_delivery = (array_key_exists('date_delivery', $post)) ? $post['date_delivery'] :null; $schedule = (array_key_exists('schedule', $post)) ? $post['schedule'] : null; $payment = (array_key_exists('payment', $post)) ? $post['payment'] : null; $paymentMethodId = (array_key_exists('paymentMethodId', $post)) ? $post['paymentMethodId'] : null; $token = (array_key_exists('token', $post)) ? $post['token'] : null; $payType = (array_key_exists('payType', $post)) ? $post['payType'] : null; $installments = (array_key_exists('installments', $post)) ? $post['installments'] : null; $issuerId = (array_key_exists('issuerId', $post)) ? $post['issuerId'] : null; $notes = (array_key_exists('notes', $post)) ? $post['notes'] : null; if(count($products) === 0){ request()->session()->flash('alert_success', "No se encontraron productos en el carrito, por favor intente nuevamente"); return response()->redirectTo(route('web.cart.index')); } if(! $dispatch){ request()->session()->flash('alert_success', "Tipo de despacho no es válido, por favor intente nuevamente "); return response()->redirectTo(route('web.cart.index')); } if((int)$dispatch === 1 && ! $address){ request()->session()->flash('alert_success', "Ops! Te faltó seleccionar una dirección de envío"); return response()->redirectTo(route('web.cart.index')); } if((int)$dispatch === 1 && ! $date_delivery){ request()->session()->flash('alert_success', "Ops! Te faltó seleccionar el día de entrega"); return response()->redirectTo(route('web.cart.index')); } if((int)$dispatch === 1 && ! $schedule){ request()->session()->flash('alert_success', "Ops! Te faltó seleccionar la franja horaria de entrega"); return response()->redirectTo(route('web.cart.index')); } if(! $payment){ request()->session()->flash('alert_success', "EL Tipo de pago no es válida, por favor intente nuevamente "); return response()->redirectTo(route('web.cart.index')); } // echo $payment;die; if(! in_array($payment, ['cash', 'mercado-pago'])){ request()->session()->flash('alert_error', "Por favor, seleccione un método de pago válido"); return response()->redirectTo(route('web.cart.index')); }else if($payment == 'mercado-pago' && (! $issuerId || ! $installments)){ request()->session()->flash('alert_success', "No pudimos traer la información de cuotas para tu tarjeta, por favor intenta nuevamente o hablanos por chat."); return response()->redirectTo(route('web.cart.index')); } $items = []; foreach($products as $product){ $id = $product['product']; if(array_key_exists($id, $items)){ $items[$id]['qty'] = (int)$product['qty']; $items[$id]['variant'] = $product['variant']; }else{ $items[$id] = [ 'id' => $id, 'qty' => $product['qty'], 'variant' => $product['variant'] ]; } } session()->put('items', $items); session()->put('order_request', [ 'address' => $address, 'dispatch' => $dispatch, 'date_delivery' => $date_delivery, 'schedule' => $schedule, 'payment' => $payment, 'paymentMethodId' => $paymentMethodId, 'installments' => $installments, 'installments' => $installments, 'issuer_id' => $issuerId, 'token' => $token, 'payType' => $payType, 'notes' => $notes, ]); return response()->redirectTo(route('account.checkout.process')); // return response()->redirectTo(route('account.checkout.confirmation')); } }



via Chebli Mohamed

raises a response from the validator in the form of json data in laravel

I have a controller that generates json, how do I get an error message from the validator if the error message also becomes json,

$this->validate($request,[
        'product_type' => 'required',
        'product_name' => 'required|string',
        'qty' => 'required',
    ]);
 -- code for saving process here --

 return response()->json([
            'status' => 'success',
            'msg'  => 'data succesfuly added'
        ]);

and this my return in network preview

errors: {product_type: ["The Product Type name field is required."], product_name: ["The address field is required."],…}
product_name: ["The product_name field is required."]
0: "The address field is required."
qty: ["The qty field is required."]
0: "The qty field is required."


via Chebli Mohamed

About laravel project. Please help me

I have a school management project which created with laravel php framework. when i add subject number for class 'Four' or 'Eight' then i face a problem which is "Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message" But if i add number accept "four" or "eight" class then i have not face any problem. Again i add number in localhost there is no problem. That problem only live server. again when i login another id then i have no problem. This problem only one specific id which id is a school admin id. i can not understand what is problem. Please help me.



via Chebli Mohamed

How can I ensure that multiple Laravel Listeners for the same event are executed and finished before starting the next one?

I have a Laravel 5.7 (with PHP 7.2) application that uses events and listeners with Redis queues. I have some workers that consume the queue and execute the listeners.

this is my event and listeners interaction in the EventServiceProvider class:

protected $listen = [
    SavedObject::class => [
        Listener1::class,
        Listener2::class,
        Listener3::class,
    ],
];

My problem is that I need that Listener2 executes and finishes before Listener3 is even executed. Laravel ensures that the listeners are executed in order, but if I have multiple workers, the Listener2 is executed and before it's finished, another worker executes Listener3 and it ruins everything.

How can I ensure that Listener2 finishes before starting Listener3 execution? Maybe a way to execute all of the Listeners of the same event using the same worker to ensure that?



via Chebli Mohamed

Submitting a form with ajax and laravel

I'm trying to add product to the database with Ajax without refreshing the page and send the data to the database but I get an error Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'. on console. How can I submit the form without refreshing the page?

Blade

 <form method="POST" role="form" enctype="multipart/form-data">
        

           <label for="pro_name">Name</label>
           <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

           <label  for="category_id">Choose Category</label>
           <select name="category_name" id="category_name">
           <option value=""> --Select Category -- </option>
           @foreach ($categoryname_array as
             $data)
             <option value=""  ></option>
             @endforeach
           </select>

           <label for="photos">Choose 5 Images</label>
           <input  "multiple="multiple" name="photos[]" type="file">

           <button type="button" onclick = "submitThisForm()" class="btn btn-primary">Submit</button>

    </form> 

Ajax

<script>
function submitThisForm(id){
    let url = "".replace(':id', id);
    $.ajax( {
        url: url,
        type: 'POST',
        data: new FormData( this ),
        processData: false,
        contentType: false,
        success: function(result){
            console.log(result);
        }
    } );
    e.preventDefault();


}
</script>

Route

 Route::post('seller/product', 'ProductController@store')->name('product.store');


via Chebli Mohamed

Laravel 5.8 - Online Quiz System similar to google classroom Quiz Assignment using laravel

I am developing a learning management system application in laravel. In this system a student can enroll in multiple subjects, Each subject has many excercises which in-turn has many lectures.

I want to make an online quiz system similar to google classroom QuizAssignment but confused regarding the structure of database . The quiz will be connected with excercises in such a way that each excercise can have many quizes.

Student -> BelongToMany -> Subject -> hasMany -> Excercise-> hasMany -> Lecture

Student Model

 public function enrolledcourses(){
    return $this->belongsToMany(Subject::class,'course_student','student_id','subject_id')->withPivot('teacher_id','status');
}

Subject Model

 public function students(){
    return $this->belongsToMany(User::class,'course_student','subject_id','student_id')->withPivot('teacher_id','status');
}
 public function excercises()
{
    return $this->hasMany(Excercise::class);
}

Excercise Model

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

public function lectures()
{
    return $this->hasMany(Lecture::class);
}


public function quizes()
{
    return $this->hasMany(Quiz::class);
}

Quiz Model

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

Quiz migration

public function up()
    {
        Schema::create('quizzes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('excercise_id')->unsigned();
            $table->string('title');
            $table->integer('obtained_marks');
            $table->integer('total_marks');
            $table->integer('passing_marks');
            $table->string('remarks');
            $table->integer('attempted')->default(0);
            $table->timestamps();
        });
    }

Now i want each excercise to have many quizes as well like :

Excercise ->hasMany -> Quiz and Lecture

But I want Quiz to be connected with the student as well so that i could record the performance of each student in a specific quiz .In other words , I want student to select subject, then select an excercise and then select any quiz and then after conducting the quiz his data should be saved in a table . Can anyone brief how do i structure the database so that i may solve the above stated problem .



via Chebli Mohamed

Laravel Middleware page authority

the idea is i want to use middleware for filtering their roles to my ektp routes. so only the users that had been logged in can access the ektp page, if not it will be redirect it to home and give alert "you need to login".

web.php

route::get('/ektp','PagesController@ektp');

i tried to add ->middleware(users) like my login and register route so it will only displaying on a guest. but some how i got an error Auth guard [users] is not defined. if i do it like that. and when i tried to add protected $guard ='user'; inside ektp model it still show me the same error.

//register
route::get('/register','AuthController@getRegister')->middleware('guest');
route::any('/register','AuthController@postRegister')->middleware('guest');

//login
route::get('/login','AuthController@getLogin')->middleware('guest');
route::any('/login','AuthController@postLogin')->middleware('guest');


via Chebli Mohamed

Countdown inside laravel blade

enter image description here

Hi guys, I'm trying to look for a way on how to make the Time Left column count down. I was guessing on doing it via ajax and updating it every minute but I guess it will affect the performance. What is the best way to achieve this? I need it to show the real-time time left of the column also updating the values in the database. Thank you!



via Chebli Mohamed

How to fix this error in console when I create a new laravel project?

I never encounter this error, can someone helped how to fix these?

It returns this red background error

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

Heres the full errors: enter image description here



via Chebli Mohamed

jeudi 28 novembre 2019

ReferenceError Laravel and Javascript

I'm trying to add product to the database with Ajax without refreshing the page and send the data to the database but I get an error Uncaught ReferenceError: $ is not defined on console. How can I submit the form without refreshing the page?

Blade

 <form action="#" id="add-productForm" method="POST" role="form" enctype="multipart/form-data">
            

               <label for="pro_name">Name</label>
               <input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">

               <label  for="category_id">Choose Category</label>
               <select name="category_name" id="category_name">
               <option value=""> --Select Category -- </option>
               @foreach ($categoryname_array as
                 $data)
                 <option value=""  ></option>
                 @endforeach
               </select>

               <label for="photos">Choose 5 Images</label>
               <input  "multiple="multiple" name="photos[]" type="file">

            <button type="button" class="btn btn-primary">Submit</button>
        </form> 

Route

Route::post('seller/product', 'ProductController@store')->name('product.store');

Ajax

 <script>
$(document).on("click", "#save", function(e) {
    let url = "";
    e.preventDefault();
    $.ajax({
        type: "post",
        url: url,
        data: $(".add-productForm").serialize(),

        success: function(store) {

        },
        error: function() {
        }
    });
});
</script>


via Chebli Mohamed

how to retrieve the id just created in the database in laravel?

how do I retrieve the id that was just created in the database, when I press the save button, the data is created, and I want to retrieve the id from that data

this my controller code

$cart= new cart;
        $cart->user_id = $request->user_id;
        $cart>vendor_name = $request->vendor_name;
$cart->save();

I want to retrieve the id of the data just created



via Chebli Mohamed

How to match exact number of rows for pivot table in laravel many to many relationship?

I have table A, B , AB which is pivot table i have created respective relationship for them also. now when i want to get data which is exact match id's(array) for pivot table.

$idArray = [3,4]

A_Model::with(['B'=>function($q) use ($idArray) {
    $q->whereIn('B.id', $idArray)
}])->get;

with whereIn it gets even if match one id from array but i want to match exact id's.

example collection :

[
  0 : {
      sample_data,
      B:[
          0:{
              sample_data,
              id:2
          },
          1:{
              sample_data,
              id:3
          },
          2:{
              sample_data,
              id:4
          }

      ]
  },
  1 : {
      sample_data,
      B:[
          0:{
              sample_data,
              id:3
          },
          1:{
              sample_data,
              id:4
          },
          2:{
              sample_data,
              id:5
          }

      ]
  },
  2 : {
      sample_data,
      B:[
          0:{
              sample_data,
              id:3
          },
          1:{
              sample_data,
              id:4
          },
      ]
  },
  3 : {
      sample_data,
      B:[
          0:{
              sample_data,
              id:3
          },
          1:{
              sample_data,
              id:4
          },
      ]
  }

]

now i want following result only for $idArray = [3,4].

[
  0 : {
      sample_data,
      B:[
          0:{
              sample_data,
              id:3
          },
          1:{
              sample_data,
              id:4
          },
      ]
  },
  1 : {
      sample_data,
      B:[
          0:{
              sample_data,
              id:3
          },
          1:{
              sample_data,
              id:4
          },
      ]
  }

]


via Chebli Mohamed

) BadMethodCallException Method [validate] does not exist

furture more it says. note: every thing was working fine till yesterday morning.my laravel version is 5.4.36.

in Controller.php line 82.

at Controller->__call('validate', array(object(Request), array('email' => 'required|string', 'password' => 'required|string'))) in AuthenticatesUsers.php line 63



via Chebli Mohamed

How to migrate Firebase dara to mysql data in laravel?

  foreach ($data as $userId => $userData) {
        if (isset($userData['is_anonymous']) && $userData['is_anonymous'] == false) {
            try {
                $user = AppUser::whereEmail($userData['email'])->first();
                if (!$user) {
                    $user = new AppUser();
                }
                $user->fill($userData);
                if (isset($userData['dwollaUrl'])) {
                    $user->dwolla_url = $userData['dwollaUrl'];
                    $parsedURL = parse_url($userData['dwollaUrl']);
                    $user->dwolla_id = str_replace("/customers/", "", $parsedURL['path']);
                }
                $user->dwolla_status = isset($userData['dwolla_acct_status']) ? $userData['dwolla_acct_status'] : null;
                // password pattern
                $user->password = Hash::make("ABC@".$userData['dob']);
                $user->save();
                $this->info("Created User For Fire-base Id : " . $userId);
                $this->info("MySQL Id For User : " . $user->id);

error :: [user_error] => Array to string conversion (SQL: insert into app_users

please help out!!! Thank you in Advance!!!



via Chebli Mohamed

Column not found: 1054 Unknown column countries

Error like that...How can i solve that?

enter image description here

This is country model

enter image description here

This is Challenge model

enter image description here

@foreach ($challenges as $challenge)
                           
                        
                                <tr>
                                    
                                        <td></td>
                                        <td></td>
                                        <td>
                                <td></td>
@endforeach


via Chebli Mohamed

Cropped mage not showing after crop in cropper.js

i am trying to crop image but when i selected cropping area and the submit cropped image. it not showed cropped image. itshow previous original image. i dont know why this problem occure. in cropper.js

code//

view image as dynamically

$.ajax({
            url: baseUrl +'/print-uploads',
            method: 'POST',
            data: data,
            processData: false,
            contentType: false,
            success: function(pic) {
                var imgele = '<img src='+pic.imgURL+' width="'+pic.imgWidth+'" height="'+pic.imgHeight+'" class="resident_image_preview">';
                var button = '<button class="ro_90"  data-option="-90" title="rotate90"></button>'
                var crossBtn = '<div class="glyphicon glyphicon-trash remove-image" title="Remove image"></div>';
                var aspectBtn = '<div class="glyphicon glyphicon-trash remove-image" title="Remove image"></div>';
                var wrapperDiv = $('<div class="image_wrapper_div">'+crossBtn+aspectBtn+imgele+button+'</div>');
                $("#calendar_main").append(wrapperDiv);
                $(".image_wrapper_div").draggable().rotatable();

                 $('.resident_image_preview').cropper( {autoCrop:false,cropHeight: 200, rotatable :true,
        cropWidth: 200,
        srcNode: '.resident_image_preview',
        x: 50,
        y: 50});

update function//
$(document).on('click', '#calendar_update', function() {
        var id  = $('#calendar_list, .resident_image_preview ').val();
        //before saving remove resize.
         //$('.resident_image_preview').resizable("destroy");
        $('.resident_image_preview').cropper("destroy");
        var calendarhtml = encodeURIComponent($('#calendar_main').html().replace(/\n\s+|\n\t/g, ""));
        // $('.resident_image_preview').resizable();
        $('.resident_image_preview').cropper('getCroppedCanvas');
        //$('.resident_image_preview').cropper();
        $('#calendar-loader').html('<img id="loader" align="center" src=' + baseUrl + '/images/fancybox_loading@2x.gif>');

        if(id){
            $.ajax({
                    url  : baseUrl+'/updatecalendar',
                    data :'payload='+calendarhtml+'&id='+id,
                    type : 'POST',
                    success : function(data){
                    if(data == 1){
                       $('#calendar-loader').html('');
                       alert("Calendar updated successfully");
                    }
                }
            });
        }
    });//update calendar end

i am trying to crop image but when i selected cropping area and the submit cropped image. it not showed cropped image. itshow previous original image.



via Chebli Mohamed

How can I verify if the user is logged in? I need to show stuff only if users are loged in.This is the code Im using

@if(auth()->user()->isAdmin())

content

@endif

@if(auth()->user()->isNormal())

content

@endif

and then if the is not logged in i get this error:

Call to a member function isAdmin() on null (View: C:\Users\marco\laravel projects\final\resources\views\layouts\user.blade.php)



via Chebli Mohamed

Reply to in mail in Laravel

I am beginner in Laravel. I use in my project Laravel 5.8.

I have function to send email:

Mail::to($request->input('email'))->send(new ContactMail($message, $mailTitle, $userEmail, $request->input('email')));

It's work fine. I want add in this function repy to address ($request->input('email')).

How can I add this?



via Chebli Mohamed

Laravel: how to generate https url

I'm using Laravel 5.4 and have a question. Is it possible to generate an https URL of the specific URL? I have a URL, e.g: login, and want to open it in https, not HTTP. how can I force Laravel to open url('login') in https mode?



via Chebli Mohamed

include_path='.;C:\php\pear') in C:\wamp64\www\homebuddies\artisan on line 18

i download a laravel project from github.I am new in this when i run php artisan serve command it gives me following statement.



via Chebli Mohamed

how to get the nearest date excluding reservations saved in the database?

How to get the nearest date excluding reservations saved in the database?

Reservations always start from Monday and end on Sunday.

I want to get the next week apart from the dates in the table.

Reservation table:

id        start        end
1         2019-12-02   2019-12-08
2         2019-12-23   2019-12-29
...
...


via Chebli Mohamed

Use of undefined constant login - assumed 'login' (this will throw an Error in a future version of PHP) when trying to logout

when ever i want to logout, it always show "Use of undefined constant login - assumed 'login'" error. what did i do wrong?

web.php

route::get('/logout','AuthController@logout')->name('logout');

route::get('/','PagesController@home')->name('home');

AuthController.php

public function getLogin(){
        return view('login');
    }

    public function postLogin(Request $request){
       if(!\Auth::attempt(['email' => $request->email, 'password' => $request->password])){
        return redirect()->back();
       }
        return redirect()->route('home');
    }

public function logout(){
        \Auth::logout();
        return redirect()->route(login);
    }

PagesController.php

public function home()
    {
        return view('index') ;
    }

main.blade.php

<a href="">logout</a>


via Chebli Mohamed

How to pass nested foreach from laravel controller to view on blade

**

how to pass the value to laravel blade view in from every nested foreach loop

How to pass nested foreach from laravel controller to view on blade for a tree structure based in three levels based on the referende_id on the above code i have fetched the three levels and now i would like to pass the value to the blade in laravel can anyone help me to sort out this..
class ClientController extends Controller { public function index($reference_id){

          $clients = table1::leftjoin('table2', function($join) {
              $join->on('table2.user_id', '=', 'table1.id');
          })->where('table1.reference_id','=',$reference_id)->get();

            foreach($clients as $levelOne)
          {//here $row is the current $data's collection 
              $clientsLevelOne = table1::leftjoin('table2', function($join) {
                  $join->on('table2.user_id', '=', 'table1.id');
              })->where('table1.under_reference','=',$levelOne->reference_id)->get();

              //$clientsLevelOne = arrayName["levelOne"];
              //$variable_name['one'] = value;

              $datas = array($clientsLevelOne);

              foreach ($datas as $items) 
              {   
                  //echo 'LEVEL ONE:<br><br>';
                  foreach ($items as $values){                    
                      $LevelOne =  $values;                                                                                   
                      //echo $LevelOne.'<br><br>';
                  }
              }

              //return $LevelOne;

              foreach ($datas as $items) 
              {   //echo '<br>LEVEL TWO:<br><br>';
                  foreach ($items as $values){                                            
                      $levelTwo = $values['reference_id'];    
                      $clientsLevelTwo = table1::leftjoin('table2', function($join) {
                          $join->on('table2.user_id', '=', 'table1.id');
                      })->where('table1.under_reference','=',$levelTwo)->get();

                      //dump($clientsLevelTwo);

                      $LevelDatas = array($clientsLevelTwo);

                      //$LevelDatas = array_merge($LevelTwo);
                      //print_r($LevelDatas);
                      //echo '<br>LEVEL TWO:<br><br>';

                      foreach($LevelDatas as $two)
                      {                       
                          foreach ($two as $values)
                          {
                              $levelThree =  $values;                             
                          }
                      }
                  }
              }

              foreach ($datas as $items) 
              {   //echo '<br>LEVEL THREE:<br><br>';
                  foreach ($items as $values){                                            
                      $levelThree = $values['reference_id'];  
                      $clientsLevelThree = table1::leftjoin('table2', function($join) {
                          $join->on('table2.user_id', '=', 'table1.id');
                      })->where('table1.under_reference','=',$levelThree)->get();

                      $LevelDatas = array($clientsLevelThree);

                      foreach($LevelDatas as $two)
                      {                       
                          foreach ($two as $values)
                          {
                              $levelDatasThree =  $values['reference_id'];    
                              $clientsLevelDatasThree = table1::leftjoin('table2', function($join) {
                                  $join->on('table2.user_id', '=', 'table1.id');
                              })->where('table1.under_reference','=',$levelDatasThree)->get();

                              $ThreeDatas = array($clientsLevelDatasThree);

                              foreach($ThreeDatas as $three)
                              {                       
                                  foreach ($three as $values)
                                  {
                                      $levelThreeDatas =  $values;    
                                  }}}}}}}           


via Chebli Mohamed

How to exe procedure sql server for laravel?

I have query, how can I do it with laravel:

exec SRO_VT_SHARD.dbo._ADD_ITEM_EXTERN 'jonh','ITEM_ETC_ALL_POTION_01',25,0


via Chebli Mohamed

How to upload multiple images with the same order of selection in Laravel?

How can i insert images to database in the same order I selected the images. Right now, a random image is selected as the first image and not the image I chose first.

Here is how I upload images to database(ProductController.php)

        $formInput=$request->except('filename');
        $product = product::create(array_merge($formInput, [
            'seller_id'=> Auth::user()->id,
            'user_id' => Auth::user()->id
        ]));
        foreach ($request->photos as $photo) {
           $filename = $photo->store('public/photos');
            ProductsPhoto::create([
                'product_id' => $product->id,
                'filename' => $filename
            ]);
        }
        return redirect()->back()->with('success', 'Product added successfully.');
    }

And this is how i retreive the first image

<img src="" alt="" width="80">



via Chebli Mohamed

how to prevent redirection to a domain from other domains

Recently found out that there are other domain names pointing to my Laravel website.

Suppose I have a Laravel website abc.com. If someone browse for xyz.com and it redirects to my site abc.com. But I want to prevent this.

Is there any way to do this in Laravel.



via Chebli Mohamed

How to deploy laravel vue site to shared hosting

Deploy laravel vue app in shared hosting

I coppied index.js from public folder to root and changed autoload and bootstrap path.

public folder contains-

dist/css/app.css
dist/js/app.js
mix-manifest.json

mix-manifest.json

{
    "/dist/js/app.js": "/dist/js/app.js",
    "/dist/css/app.css": "/dist/css/app.css"
}

when i browse, http://domain_name/dist/css/app.css not found error

I deleted public folder and coppied everything to root. But i m getting The Mix manifest does not exist error

Is there a way to overcome this.?

Deploying laravel vue app is a headache? Can i use RewriteBase in htaccess to resolve issue



via Chebli Mohamed

mercredi 27 novembre 2019

Call to undefined method Illuminate\Database\Query\Builder::colFunction()

i am geting this called to undeifne method and i am totally new dont now how to define method this is route line Route::post('/colFunction','Controller@colFunction'); this is my controller function

function colFunction(Request $req)
{
 $column =$req->input('column');

 $data =array('column'=>$column);
 \DB::table('column')->colFunction($data);
}


via Chebli Mohamed

Can't get into referring page in Laravel 5.3

I don't know if this question might have a duplicate but I can't find any solution. I am new to laravel and I used version 5.3 and PHP 5.6.4, I have a hard time saving my data into mysql database with php form with action="addFriend" the problem is it can't get into the referring page. This is my code in friend_add.blade.php

        <form method = "post" action = "/addFriend">
        
            <table>
                <tr>
                    <td>Friend ID</td>
                    <td><input type='text' name='friend_id' /></td>
                <tr>
                    <td>Friend Name</td>
                    <td><input type="text" name='friend_name'/></td>
                </tr>
                <tr>
                    <td>Place</td>
                    <td><input type="text" name='place'/></td>
                </tr>
                <tr>
                    <td colspan = '1'>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </td>
                </tr>
            </table>
        </form>

web.php

Route::post('/addFriend','FriendController@post');

and this is my code in FriendController.php

  {
    $friend_id = $request->input('friend_id');
    $friend_name = $request->input('friend_name');
    $place = $request->input('place');
    $data=array('FriendID'=>$friend_id,"FriendName"=>$friend_name,"Place"=>$place);
    DB::table('friend')->insert($data);
    echo "Record inserted successfully.<br/>";

  }

The localhost will return No Object Found. Can anyone help me? Thanks. It will mean a lot.



via Chebli Mohamed

PHPUnit show errors but not show successful alert

I use Laravel 5.8 and phphunit version 7.5. When I run PHPUnit with error, show me error but when not has error show me only this line

PHPUnit 7.5.0 by Sebastian Bergmann and contributors. My test class:

use Tests\TestCase;

class leadTest extends TestCase
{
    public $Array= ['lead_name' => 'Jon','lead_family'=>'Doe']
    public function test_store()
    {
        $this->withoutExceptionHandling();
        $this->post('leads', $this->Array();
        $this->assertDatabaseHas('leads', $this->Array);
    }
}


via Chebli Mohamed

Is there any javascript function or any laravel query to optimize cash transaction history page loding time?

I want to optimize cash transactions history page loading time and optimize bankDetails function

Every time i load Cash Ledger or "accounts/bank-details/cash" page either my whole laravel serve is crush neither this page loading time minimum about 10m, it is too difficult to handle this page or reset every time laravel serve.

Is there any optimization function or method to optimize the loading time of Cash Ledger page?

My Route is

Route::get('/bank-details/{id}', 'BankController@bankDetails')->name('bank.show');

BankController.php bankDetails function

public function bankDetails($id) {
        if(!Auth::user()->isAdmin() && !Auth::user()->isAccountant()) {
            return redirectBackWithNotification('error', 'You are not authorised!');
        }

        if($id == 'cash') {
            $projects = Project::select(['bsoft_projects.project_id', 'bsoft_projects.project_name'])->get();

            return view('admin.accounting.banks.show')
                ->with([
                    'projects'   => $projects
                ]);
        }

        $bank = BankAccount::findOrFail($id);

        if(!$bank->user) {
            $payments = Payment::where('payment_from_bank_account', '=', $bank->bank_id)
                ->orWhere('payment_to_bank_account', '=', $bank->bank_id)
                ->get();
            $balance = $bank->bank_balance;
        }
        else {
            $payments = Payment::where('payment_from_bank_account', '=', $bank->bank_id)
                ->orWhere('payment_to_bank_account', '=', $bank->bank_id)
                ->orWhere('payment_to_user', '=', $bank->user->id)
                ->orWhere('payment_from_user', '=', $bank->user->id)
                ->get();
            $balance = 0;
            $exp = 0;
            $inc = 0;
            foreach ($payments as $payment) {
                if($payment->payment_from_user == $bank->user->id) {
                    $exp += $payment->payment_amount;
                }
                elseif ($payment->payment_to_user == $bank->user->id) {
                    $inc += $payment->payment_amount;
                }
            }
            $balance = $inc - $exp;
        }

        return view('admin.accounting.banks.show')
            ->with([
                'bank'       => $bank,
                'payments'   => $payments,
                'balance'    => $balance
            ]);
    }

index.blade.php

<div class="card-footer text-center">
                    <a href="" class="btn btn-link text-white">Cash Transaction History</a>
                </div>

TransactionsDataTable.vue


<template>
    <div class="rbt-data-table">
        <div class="card">
            <div class="card-header">
                <h4 class="text-center w-100">Cash Ledger</h4>
            </div>
            <div class="card-body">

                <div class="selection-form">
                    <form>
                        <div class="form-group">
                            <strong class="font-weight-bold">Select Type: &nbsp;&nbsp;</strong>
                            <div class="custom-control custom-radio custom-control-inline">
                                <input type="radio" id="customRadioInline1" class="custom-control-input" v-model="type" value="all">
                                <label class="custom-control-label" for="customRadioInline1">All</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                                <input type="radio" id="customRadioInline2" class="custom-control-input" v-model="type" value="loan">
                                <label class="custom-control-label" for="customRadioInline2">Loans</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                                <input type="radio" id="customRadioInline3" class="custom-control-input" v-model="type" value="project">
                                <label class="custom-control-label" for="customRadioInline3">By Project</label>
                            </div>
                        </div>
                    </form>
                </div>

                <div class="data-table-header" v-if="!isLoading">
                    <div class="row justify-content-between">
                        <div class="col-sm-4 d-none d-sm-block">
                            <div class="data-per-page">
                                <label>
                                    Show:
                                    <select v-model="perPage" class="custom-select">
                                        <option value="15">15</option>
                                        <option value="25">25</option>
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                    </select>
                                </label>
                            </div>
                        </div>

                        <div class="col-sm-8">
                            <div class="data-search float-right">
                                <!--<label class="sr-only" for="Search">Search</label>
                                <div class="input-group">
                                    <input v-model="search" @keyup="fetchData()" type="text" class="form-control" id="Search" placeholder="Search Here">
                                    <div class="input-group-append">
                                        <div class="input-group-text"><i class="feather icon-search text-dark"></i></div>
                                    </div>
                                </div>-->
                                <div class="data-search" v-if="type === 'project'">
                                    <label for="project_id">
                                        For Project:&nbsp;
                                        <select class="custom-select" id="project_id" style="width: auto !important;" v-model="projectId">
                                            <option value="">Select A Project</option>
                                            <option v-for="project in projects" :value="project.project_id"></option>
                                        </select>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-bordered table-striped" id="FranchiseTable" style="width: 100%;">
                        <thead>
                        <tr>
                            <th scope="col">Date</th>
                            <th scope="col">Method</th>
                            <th scope="col">Type</th>
                            <th scope="col">Amounts</th>
                            <th scope="col">Purpose</th>
                            <th scope="col" v-if="type === 'all'">Project</th>
                            <th scope="col">From</th>
                            <th scope="col">To</th>
                            <th scope="col">Received By</th>
                        </tr>
                        </thead>

                        <tbody>
                        <tr v-for="data in paginatedData.data">

                            <th scope="row"></th>
                            <td></td>
                            <td></td>
<!--                            <td class="font-weight-bold"></td>-->
                            <td style="text-transform: capitalize;"></td>
                            <td v-if="type === 'all'">
                                <a :href="'/project/show/' + data.project_id"></a>
                            </td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                        </tbody>
                    </table>
                </div>

                <div class="data-table-footer">
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="data-showing">
                                Showing <strong> - </strong>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="data-pagination">
                                <ul class="pagination float-right">
                                    <li class="page-item pagination-page-nav" v-if="paginatedData.current_page > 1">
                                        <a href="#" class="page-link" @click.prevent="previousPage">
                                            <i class="fa fa-angle-double-left"></i>
                                        </a>
                                    </li>
                                    <li class="page-item pagination-page-nav" v-if="paginatedData.current_page > 1">
                                        <a href="#" class="page-link" @click.prevent="fetchData(1)">
                                            1
                                        </a>
                                    </li>
                                    <li class="page-item pagination-page-nav active" v-if="paginatedData.current_page">
                                        <a href="#" class="page-link">
                                            
                                        </a>
                                    </li>
                                    <li class="page-item pagination-page-nav" v-if="paginatedData.current_page !== paginatedData.last_page">
                                        <a href="#" class="page-link" @click.prevent="nextPage">
                                            <i class="fa fa-angle-double-right"></i>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['projects'],
        data() {
            return {
                isLoading: true,
                paginatedData: {},
                apiUrl: '/bsoft-api/cash-transactions/',
                perPage: 5,
                search: '',
                type: 'all',
                projectId: '',
                deleteFranchiseId: ''
            }
        },
        mounted() {
            this.fetchData();
        },
        watch: {
            perPage(newVal, oldVal) {
                if(newVal !== oldVal)
                    this.fetchData();
            },
            type(newVal, oldVal) {
                if(newVal !== oldVal) {
                    if(newVal === 'project') {
                        this.paginatedData = {};
                    }
                    else {
                        this.fetchData();
                    }
                }
            },
            projectId(newVal, oldVal) {
                if(newVal !== oldVal)
                    this.fetchData();
            }
        },
        methods: {
            fetchData(page = 1) {
                let self = this;
                self.isLoading = true;
                let url = self.apiUrl + self.type;
                if(self.type === 'project') {
                    url = url + '/' + self.projectId;
                }
                axios.get(`${url}?page=${page}&per_page=${self.perPage}&search=${self.search}`)
                    .then(function (response) {
                        console.log(response.data);
                        self.paginatedData = response.data;
                        self.isLoading = false;
                    })
                    .catch(function (error) {
                        console.log(error.response);
                    });
            },
            previousPage() {
                let page = this.paginatedData.current_page - 1;
                this.fetchData(page);
            },
            nextPage() {
                let page = this.paginatedData.current_page + 1;
                this.fetchData(page);
            },
            openDeleteModal(id) {
                this.deleteFranchiseId = id;
                $('#franchiseDeleteModal').modal('show');
            },
            deleteFranchise() {
                axios.delete('/bs-admin-api/franchise-control/delete/' + this.deleteFranchiseId)
                    .then((response) => {
                        this.showToastMsg('Franchise deleted successfully...!', 'success', 3000);
                        $('#franchiseDeleteModal').modal('hide');
                        this.fetchData();
                    })
                    .catch((error) => {
                        this.showToastMsg('Something went wrong...! Try again later.', 'error', 5000);
                    });
            },
            showToastMsg(msg, method = 'show', duration = 2500) {
                this.$toasted[method](msg, {
                    action : {
                        text : '',
                        icon: 'times',
                        onClick : (e, toastObject) => {
                            toastObject.goAway(0);
                        }
                    },
                    duration: duration
                });
            },
        }
    }
</script>


Api Route

Route::get('cash-transactions/{type}/{id?}', 'BankController@cashTransactions');

Api Controller

public function cashTransactions(Request $request, $type, $id = null) {
        $per_page = ($request->get('per_page'))? $request->get('per_page') : 5;
        $search = htmlspecialchars($request->get('search'));

        $roles = Role::whereIn('role_slug', ['administrator', 'accountant'])
            ->pluck('role_id')
            ->toArray();

        if($type === 'project') {
            if(!$id) {
                return response()->json('Project Id Required!', 404);
            }
            $payments = Payment::wherePaymentBy('cash')
                ->where('payment_for_project', '=', $id)
                ->orderByDesc('payment_date')
                ->get()
                ->filter(function ($payment) use ($roles) {
                    return in_array($payment->activity->activityBy->role_id, $roles);
                });
//        } else if($type === 'loan') {
//            $payments = Payment::wherePaymentBy('cash')
//                ->whereIn('payment_purpose', ['loan_received', 'loan_payment'])
//                ->orderByDesc('payment_date')
//                ->get()
//                ->filter(function ($payment) use ($roles) {
//                    return in_array($payment->activity->activityBy->role_id, $roles);
//                });
       } else {
            $payments = Payment::wherePaymentBy('cash')
                ->orderByDesc('payment_date')
                ->get()
                ->filter(function ($payment) use ($roles) {
                    return in_array($payment->activity->activityBy->role_id, $roles);
                });
        }
        $page = $request->get('page') ?: (Paginator::resolveCurrentPage() ?: 1);
        $paginatedPayments = new LengthAwarePaginator($payments->forPage($page, $per_page), $payments->count(), $per_page, $page);

        return response()->json($this->makePaymentCollection($paginatedPayments), 200);
    }

I want to know where is the problem facing i am?

is there any solution to solve this optimization problem is there any api function to optimize the whole cash transaction history?

in cashTransactions from API controller query to optimize this page loading time?

if i want to show date to date or month to month cash transaction history What should i do and where i can add this? and is it better to show date to date or month to month showing history or is it better to show all history of loan, by project or All



via Chebli Mohamed

Changing the author name In already built plugin in octobercms

I am building plugins that do simple CRUD in octobercms but the url in the backend has author name in it. I want to change it to something reliable to the website like max/home/home to page/home/home



via Chebli Mohamed

Division by zero in Laravel

I want to ask, Why can I use the first SQL command, the second fails? Note: Error occurs when data is empty Success

$barang = KeluarTmp::LeftJoin('data_barang', function($join){
        $join->on('data_barang.kode_barang','=','barang_keluar_tmp.kode');
    })->leftjoin('data_jasa','barang_keluar_tmp.kode','=','data_jasa.kode_jasa')
    ->WHERE('barang_keluar_tmp.keterangan', $user)
    ->orderBy('barang_keluar_tmp.created_at','ASC')
    ->get(['barang_keluar_tmp.id as id',
        'data_barang.nama_barang as nama_barang',
        'barang_keluar_tmp.kode as kode_barang',
        'barang_keluar_tmp.qty as jumlah',
        'barang_keluar_tmp.total_harga as total_harga',
        'barang_keluar_tmp.total_harga_awal as total_harga_awal',
        'data_jasa.nama_jasa as nama_jasa',
        'barang_keluar_tmp.diskon as diskon'
        ]);

Error Devision Zero

$barang = DB::select('SELECT barang_keluar_tmp.id as id, data_barang.nama_barang as nama_barang, barang_keluar_tmp.kode as kode_barang, barang_keluar_tmp.qty as jumlah, barang_keluar_tmp.total_harga as total_harga, barang_keluar_tmp.total_harga_awal as total_harga_awal, data_jasa.nama_jasa as nama_jasa, barang_keluar_tmp.diskon as diskon, SUM(h.masuk - (i.keluar + barang_keluar_tmp.qty)) as stok
        FROM barang_keluar_tmp 
        JOIN data_barang on data_barang.kode_barang = barang_keluar_tmp.kode
        LEFT JOIN data_jasa on barang_keluar_tmp.kode = data_jasa.kode_jasa
        LEFT JOIN 
                    (SELECT barang_masuk.kode_barang, SUM(barang_masuk.qty) as masuk from barang_masuk group by barang_masuk.kode_barang) 
                    AS h ON barang_keluar_tmp.kode = h.kode_barang
        LEFT JOIN 
                    (SELECT barang_keluar.kode, SUM(barang_keluar.qty) as keluar from barang_keluar group by barang_keluar.kode) 
                    AS i ON barang_keluar_tmp.kode = i.kode
        WHERE barang_keluar_tmp.keterangan = "'.$user.'"
        ORDER By barang_keluar_tmp.created_at ASC');


via Chebli Mohamed

Create Many to Many Polymorphic Relationship using custom table

How can I create a Many to Many relationships using the custom polymorphic table?

model_has_tags

$table->increments('id');
$table->integer('tag_id';
$table->string('model_type');
$table->integer('model_id');

tags

$table->increments('id');
$table->string('name');

user

$table->increments('id');
$table->string('full_name');

I try this but not working. Tag Model

public function users()
    {
        return $this->morphedByMany(User::class, 'model')->using(ModelHasTags::class);
    }

User Model

public function tags()
    {
        return $this->morphToMany(Tag::class, 'model')->using(ModelHasTags::class);
    }

error :

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'stormport.models' doesn't exist (SQL: select `tags`.*, `models`.`model_id` as `pivot_model_id`, `models`.`tag_id` as `pivot_tag_id`....

How to solve this?



via Chebli Mohamed

Updating Existing Record of Pivot Table in Laravel. How to use updateExistingPivot when I do not have second parameter?

The two tables sites and terms have many to many relationship. The pivot table for them is:

site_terms 
----------
site_id
term_id 

While saving a site and its relationship with the terms work fine with the following:

$site->terms()->attach($term_id);

Say I have added a site to a term and the record is in the table:

site_term 
-----------
site_id term_id 
101     501

When I edit the site and add a different term whose id is 502 how can I update the record of the relationship in the pivot table so that the record is now

site_term 
-----------
site_id term_id 
101     502


via Chebli Mohamed

How to configure multiple laravel site/projects on a VPS?

I have the following two Laravel projects:

1.lsapp 2.larvel

I'm trying to achieve something like this: myIPaddress/lsapp and myPIaddress/laravel respectively. At the moment, I'm using my IP address.

I have the following /etc/nginx/sites-available/my-projects file:

server {
listen 80;
listen [::]:80;

root /var/www/lsapp/public;
index index.php index.html index.htm index.nginx-debian.html;

server_name myIPaddress;

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location /laravel{
root /var/www/laravel/public;
rewrite ^/laravel/(.*)$ /var/www/laravel/public/index.php?$1 last;
try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

location ~ /\.ht {
deny all;
}

}

I have the following hosts file. Not sure if it matters:

127.0.0.1   localhost
127.0.1.1   guest

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

127.0.0.1 laravel_test
::1       laravel_test

By the way, I am using Ubuntu 16.04 with NGINX. I am using Vultr for my VPS.

I've been trying to look for answers on Google and among other websites, but I haven't found a solution. I did find that people suggest to install Laravel Homestead. Any help will be appreciated!



via Chebli Mohamed

Create a Many to Many Polymorphic relationship custom table

How can I create a Many to Many Polymorphic relationship using this table:

model_has_tags

$table->increments('id');
$table->integer('tag_id');
$table->string('model_type');
$table->integer('model_id');
$table->timestamps();

Tags

$table->increments('id');
$table->string('name');

Users

$table->increments('id');
$table->string('full_name');


via Chebli Mohamed

failed to authenticate on SMTP server with username using 2 possible authenticators (even using same username)

We have 2 nginx web server and using AWS SES email service to send notification email in Laravel 5.5.But i got this issue in one server and i checked all smtp config are correct. This username works in other server. Both web server configuration are same and correct. I have no idea why happened this error. Anyone can help me to solve this problem as soon as possible.



via Chebli Mohamed

Laravel - Get queue data before run

I want to send a custom data in my queues and want to catch this data before action running.

The best possibility for me would be to send a header value, so I could use getallheaders() to read this data, but I did read and don't found this possibility.

Since it isn't possible send header, how can I read data before async back execute?



via Chebli Mohamed

Je veux charger la page avec jquery avec un petit loader en bas du page

I use Laravel 5.8, I created a view in which I retrieve all my users via the database. Suppose there are many users but I do not want to use pagination and I do not want all users to appear at the same time when I refresh the page. I want that when I refresh the page once only a few users will appear and if I start to go down the page a small loader will be displayed and the others will appear one by one until the last one. I want to use this system with jquery.

Here is my code to control

Public function users(){
 $users = user::all();
 Return view('users', compact ('users');

}

In the view

@foreach($users as $user)
   
   
@endforeach

Please help me



via Chebli Mohamed

Which Passport version is compatible with Laravel 5.7.15, default installation does not work

As a part of Laravel 5.7 setup, I am trying to install Passport using the command:

composer require laravel/passport

But it doesn't work and gives the error:

Using version ^8.0 for laravel/passport
./composer.json has been updated
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove laravel/framework v5.7.15
    - Conclusion: don't install laravel/framework v5.7.15
    - laravel/passport 8.x-dev requires illuminate/support ^6.0|^7.0 -> satisfiable by laravel/framework[6.x-dev], illuminate/support[6.x-dev, 7.0.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6.5.1, v6.5.2, v6.6.0].
    - laravel/passport v8.0.0 requires illuminate/support ^6.0|^7.0 -> satisfiable by laravel/framework[6.x-dev], illuminate/support[6.x-dev, 7.0.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6.5.1, v6.5.2, v6.6.0].
    - laravel/passport v8.0.1 requires illuminate/support ^6.0|^7.0 -> satisfiable by laravel/framework[6.x-dev], illuminate/support[6.x-dev, 7.0.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6.5.1, v6.5.2, v6.6.0].
    - laravel/passport v8.0.2 requires illuminate/support ^6.0|^7.0 -> satisfiable by laravel/framework[6.x-dev], illuminate/support[6.x-dev, 7.0.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6.5.1, v6.5.2, v6.6.0].
    - Can only install one of: laravel/framework[6.x-dev, v5.7.15].
    - don't install illuminate/support 6.x-dev|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.0.0|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.0.1|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.0.2|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.0.3|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.0.4|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.1.0|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.2.0|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.3.0|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.4.1|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.5.0|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.5.1|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.5.2|don't install laravel/framework v5.7.15
    - don't install illuminate/support v6.6.0|don't install laravel/framework v5.7.15
    - don't install illuminate/support 7.0.x-dev|don't install laravel/framework v5.7.15
    - Installation request for laravel/framework (locked at v5.7.15, required as 5.7.*) -> satisfiable by laravel/framework[v5.7.15].
    - Installation request for laravel/passport ^8.0 -> satisfiable by laravel/passport[8.x-dev, v8.0.0, v8.0.1, v8.0.2].


Installation failed, reverting ./composer.json to its original content.

It looks like the Passport version 8.0 is not compatible with the Version 5.7.15 of Laravel, which version is compatible here?



via Chebli Mohamed

Should I use Get or Delete method to delete a record in laravel?

I've seen many questions and posts using the Get method passing the ID on the url like /articles/delete/{id}.

The route in this case is defined with the GET method. Whats the difference if I use the Delete method and how can I use it?

Which one should I use?



via Chebli Mohamed

Check if link is from an external Domain

I'm Working with Laravel and jquery. I have e-commerce and I have a list of my products some of them are on my web site and some of them Don't I need to redirect the ones that are inside my web and open a new tab the others. for example:

<a href="www.MYWEB.COM" > MY PRODUCTS</a>

<a href="https://www.w3schools.com" target="_blank"> Producs from other website </a>

is it possible? So far I have this. I really need help.

<div class="dropdown-menu dropdown-menu-right">
   <div class="header-items">My Products<span class="count-items ml-1"></span></div>
     @foreach ($notifications as $item)
       <a href=""  class="idNote" data-note="" style="color: #000000;" data-redirect="">
         <div id="note-" class="item "  >
              <p class="mb-0 font-medium"></p>
              <p class="mb-0"></p>
              <span class="point-not-read"></span>
         </div>
       </a>
     @endforeach                   
</div>

my jquery

<script>
    $('.idNote').click(function(e){
        e.preventDefault();

        var noteId = $(this).attr('data-note');
        var redirecTwo = $(this).attr('data-redirect');
        console.log(noteId);
        $.ajax({
            url : "",
            type : "POST",
            data : {
                jsNoteId : noteId
            },
            beforeSend : function(){
                $('#note-'+noteId).removeClass('not-read');
                //window.location = redirecTwo;
                window.open(redirecTwo, '_blank');
            },
            success : function(r){                    
                console.log(r);                    
            }
        });
    });
</script>


via Chebli Mohamed

Bootstrap Tagsinput how to get multiple values as an array

Hey guys I have a problem with Bootstrap Tagsinput I'm trying to get an array with all the tags from the input text as values

<input type="text" name="designation" data-role="tagsinput" id="tags_id">

here's the js code

<script>
$('#tags_id').tagsinput('items');
</script>

When i insert some values in the input i get this "123,2131,12" but i need to get somthing like this ["123","2131","12"], and sorry for my english



via Chebli Mohamed

After deployment to heroku, modifications to vuejs components and app.scss of laravel app does not update

I have a laravel/vuejs app that works well on localhost. After deploying to heroku, i realized that styles added to app.scss does not compile into my public/css file, thus have no effect. Also, modifications to my vuejs components does not update the app after i push to heroku like so;

git push heroku master

I have added heroku/nodejs buildpack on my heroku dashboard. Here is my webpack.mix.js file content;

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css');

mix.browserSync({
    proxy: 'localhost:8000'
});

My package.json scripts;

"scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "heroku-prebuild": "export NPM_CONFIG_PRODUCTION=false; export NODE_ENV=; NPM_CONFIG_PRODUCTION=false NODE_ENV=development npm install --only=dev --dev",
        "heroku-postbuild": "export NPM_CONFIG_PRODUCTION=true; export NODE_ENV=production"
    },

NB: I have googled around for solution but didn't find any. Please what am i doing wrong?



via Chebli Mohamed

Using Imagick to convert PDF in landscape format to image but not working

i wanna convert pdf to image and i use imagick (installed imagick & ghostscript 9.26 on linux server) but have error:

PDFDelegateFailed `The system cannot find the file specified. ' @ error/pdf.c/ReadPDFImage/794

$uploadFile = $request->file('file');

    if ($uploadFile->getClientOriginalExtension() == FileFormat::PDF && $request->input('convert_to')) {
        $imagick = new \Imagick();
        if($imagick->getNumberImages()!=0)
        {
            $response->code = HttpStatusCode::UNPROCESSABLE_ENTITY;
            $response->error->add('converting have error.', 'Not convertible. Your file have more than 1 page.');
            return $response->json();
        }
        $imagick->setResolution(300, 300);
        $imagick->readImage(($uploadFile->getFileInfo())->getPathname());
        $imagick->setImageCompressionQuality(100);
        $imagick->setImageFormat($request->input('convert_to'));
        $extension = $request->input('convert_to');
        $fileType = $imagick->getImageMimeType();
    } 


via Chebli Mohamed

Global variable in laravel 5.5

I'm new to laravel and currently making a dashboard with laravel and stuck on how to store variable that can be accessed by all view and controller and can be changed by controller. For example i'm logging in into the dashboard and i want to store the query i got from the database .

$admin = DB::table('admin')->where('username',$request->user)->select('admin_name')->first();

After that i want $admin to be stored globally so all the view and controller can use it. I've tried session but it doesn't work and always return null value. Any anybody tell me another solution ?



via Chebli Mohamed

How to adapt Laravel controller code to follow DRY principle when there is overlap between assumptions?

My aim is to adapt the following controller methods to follow the DRY principle by moving the validation to form requests. However, I have a problem which is that there are overlaps between validation for different methods. For example, let's say that the input form has only one field and that's name, and that it's related to a Task model. Let's consider 3 controller methods now:

  • store method: validate that name isn't empty
  • update method: validate that name isn't empty and that a Task with the given $id exists
  • destroy method: validate that a Task with the given $id exists

So for the store method I am checking the first assumption, for the destroy method I am checking the second assumption, and for the update method I am checking both.

So, ideally, I would like to be able to do something like...

public function store(StoreTask $request)...
public function update(Store Task TaskExists $request, $id)...
public function destroy(TaskExists $id)...

...but I am very unclear on how to write the syntax for this, and whether there is some other approach which I'm missing to accomplish the same thing.



via Chebli Mohamed

mardi 26 novembre 2019

Combine array and add key for each array

I just can't find the right question for this

pretty much merging array From this

$arr1 = ["temp1", "temp2", "temp3"];
$arr2 = [5, 7, 2];

to this

$combined = [["name" => "temp1", "number" => 5], ["name" => "temp2", "number" => 7], ["name" => "temp3", "number" => 2]];

any idea to do it in most efficient way other than foreach?



via Chebli Mohamed

Laravel validation username must not start with specific string

I want to register user but I want to put validation rule on username that username should not start with special characters and also should not start with web. I found regex that work fine special characters but detect the string it give me error of Invalid format

return [
          'username' => [
                    'required',
                    'regex:/^\S*$/u',
                    'regex:/^[_]?[a-zA-Z0-9]+([_.-]?[a-zA-Z0-9])*$/',
                    'unique:users'
                ],
          'full_name' => 'required',
       ];


via Chebli Mohamed

How to make api in laravel 5.4 with websocket ..?

i want to make a api system in laravel using websocket .if any body know please help me with sone video or tutorial links , because i am new in laravel and websocket.



via Chebli Mohamed

How to update database base on laravel checkbox value

I load check boxes from database with they are checked or not,

  <div class="row">
                <div class="col-xs-12">
                    <div class="form-group">

                        @php
                            $json = $orders->data;
                            $json = json_decode($json, true);
                            $products = $json['order_info']['products'];

                            $data = '';

                                foreach ($products as $hitsIndex => $hitsValue) {
                                    $data .= $hitsValue['type']. ', ';
                                }
                            $data = rtrim($data, ', ');

                            $agosProducts = Utility::constant('agos_products1');
                        @endphp

                        
                        <label for="products" class="control-label"></label><br><br>

                        @foreach($agosProducts as $product)

                                    <label class="control-label "for="">
                                        <input id="" name="" type="checkbox" value=""
                                               @foreach ($products as $hitsIndex => $hitsValue)
                                                    @if(in_array($hitsValue['type'], $product)) checked=checked @endif
                                               @endforeach
                                        >
                                        
                                    </label>
                                <br>

                        @endforeach

                    </div>
                </div>
            </div

Now i want to update my database base on checkbox value.

For example if say i load checkbox 1 as checked from database and now it's unchecked i need to update it in database.

This code i can get all the current status of checkbox but i don't know previous values of this to update in database,

$chks = array('multicolor','resizable','showRuler','namesNumbersEnabled');
foreach ($chks as $chk) {
   $product->setAttribute($chk, (Input::has($chk)) ? true : false);
}

Can someone helps me?



via Chebli Mohamed

Composer not installing a package

"staudenmeir/eloquent-json-relations" not installing on composer install.But downloading on composer update. Here is my composer.json

{ "name": "laravel/lumen", "description": "The Laravel Lumen Framework.", "keywords": ["framework", "laravel", "lumen"], "license": "MIT", "type": "project", "require": { "php": ">=7.1.3", "doctrine/dbal": "^2.9", "guzzlehttp/guzzle": "^6.3", "kreait/firebase-php": "^4.0", "laravel/lumen-framework": "5.7.*", "lcobucci/jwt": "^3.2", "league/flysystem-aws-s3-v3": "~1.0", "staudenmeir/eloquent-json-relations": "^1.1", "vlucas/phpdotenv": "~2.2" }, "require-dev": { "fzaninotto/faker": "~1.4", "phpunit/phpunit": "~7.0", "mockery/mockery": "~1.0" }, "autoload": { "classmap": [ "database/seeds", "database/factories" ], "psr-4": { "App\": "app/" } }, "autoload-dev": { "classmap": [ "tests/" ] }, "scripts": { "post-root-package-install": [ "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ] }, "config": { "preferred-install": "dist", "sort-packages": true, "optimize-autoloader": true }, "minimum-stability": "dev", "prefer-stable": true }



via Chebli Mohamed

how to get student rank in exam

I have a grading table and in the grading table there are columns of user id, schedule id, class id, in class, grades, time worked, and information (graduated or not).

and this is a script that I tried, I can only display data based on information (graduated or not) and the fastest processing time.

$data['rank'] = DB::table('grading') ->select('grading.id_user','lesson.name_lesson','grading.id_lesson','grading.grade','grading.time_worked','gradinng.information','grading.id','grading.created_at', 'grading.id_class', 'class.name_class') ->join('lesson','grading.id_lesson','=','lesson.id') ->join('schedule','penilaian.id_jadwal','=','schedule.id') ->join('class', 'penilaian.id_class', '=','class.id') ->orderBy('grading.grade','desc') ->orderBy('grading.time_worked', 'asc') ->get(); I want to display the ranking of students 1-3 with the criteria for passing the exam and the fastest time to do it. I want to display the class ranking and rank in 1 school. how to display rank 1-3 in this exam, thank you for your help. this is example my grading table



via Chebli Mohamed