mercredi 18 janvier 2023

How to make command in Laravel that can go thousands rows and update all data with Job that can update grouped by 50 data

I want to make command that can go through all data from database and update some data in API for every row.. I am afraid of stopping command or cron and all data will not be updated. And when command run again it will go from first id. For example if I have ids: [1,2,3,4,5,6,7,8,...100,101,..1000,1001,...] I want to first update 50 rows(1-50), then (51-100)..and so on.. How can I make Job that will save from which to which ID should be updated? I hope so that someone can help me.. I tried something like this

 $woocount=WoocommerceProduct::where('sync_status', 'IN_SYNC')->count();
        
        if($woocount>100){
            $max=intval($woocount/100);
        }else{
            $max=$woocount;

        }
       // dd($max);
        $i=1;
        while($i<=$woocount){
            dump($max);
            $wooproducts=WoocommerceProduct::where([['sync_status', 'IN_SYNC'],['id','>=',$i], ['id', '<=', $max]])->get();
            dump($wooproducts->pluck('id')->toArray());
            CheckStockJob::dispatch($wooproducts);
            $i=$max+1;
            $max=$max+100;
        }


via Chebli Mohamed

mardi 17 janvier 2023

NotFoundHttpException in Handler.php line 103: No query results for model [sistemaconvocatoria\Convocatoria]

I have a problem when I try to edit a record I get the following error: NotFoundHttpException in Handler.php line 103: No query results for model [sistemaconvocatoria\Convocatoria]. --- Here is my controller:

<?php

namespace sistemaconvocatoria\Http\Controllers;

use Illuminate\Http\Request;

use sistemaconvocatoria\Http\Requests;
use sistemaconvocatoria\Convocatoria;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\input;
use sistemaconvocatoria\Http\Requests\ConvocatoriaFormRequest;
use Carbon\Carbon;
use DB;


class ConvocatoriaController extends Controller
{
    public function __construct()
    {
        //$this->middleware('auth');

    }
    public function index(Request $request)
    {
        if ($request)
        {
            $query=trim($request->get('searchText'));
            $convocatorias=DB::table('convocatoria')
            ->where('descripcion','LIKE','%'.$query.'%')
            ->orwhere('codigo','LIKE','%'.$query.'%')
            ->orderBy('idconvocatoria','desc')
            ->paginate(10);
            return view('convocatoria.locacion.index',["convocatorias"=>$convocatorias,"searchText"=>$query]);
        }
        
    }

    public function create()
    {
       
        return view("convocatoria.locacion.create");
    }
    public function store (ConvocatoriaFormRequest $request)
    {
        $convocatoria=new Convocatoria;
        //$convocatoria->id=$request->get('id');
        $convocatoria->codigo=$request->get('codigo');
        $convocatoria->descripcion=$request->get('descripcion');
        $convocatoria->categoria_convocatoria=$request->get('categoria_convocatoria');
        $convocatoria->estado= 'VIGENTE';

        $date1 = Carbon::parse($request->get('fecha_publicacion'));
        $convocatoria->fecha_publicacion=$date1->toDateTimeString();

        $date2 = Carbon::parse($request->get('fecha_vencimiento'));
        $convocatoria->fecha_vencimiento=$date2->toDateTimeString();

        if (Input::hasFile('documento')){
         $file=Input::file('documento');
         $para_extencion=$file->getClientOriginalName();
         $extension = pathinfo($para_extencion, PATHINFO_EXTENSION);
         $nombre_archivo="pdf_".$request->get('categoria_convocatoria')."_".$request->get('codigo').".".$extension;
         $file->move(public_path().'/archivos/pdf/',$nombre_archivo);
         $convocatoria->documento=$nombre_archivo;
        }
        $convocatoria->save();
        return Redirect::to('convocatoria/locacion');

    }
    
    public function show($id)
    {
        return view("convocatoria.locacion.show",["convocatoria"=>Convocatoria::findOrFail($id)]);
    }
    public function edit($id)
    {
        return view("convocatoria.locacion.edit",["convocatoria"=>Convocatoria::findOrFail($id)]);
    }
    
    
    public function update(ConvocatoriaFormRequest $request,$id)
    {
        
        $convocatoria=Convocatoria::findOrFail($id);

        //$convocatoria->id=$request->get('id');
        $convocatoria->codigo=$request->get('codigo');
        $convocatoria->descripcion=$request->get('descripcion');
        $convocatoria->categoria_convocatoria=$request->get('categoria_convocatoria');
        

        $date1 = Carbon::parse($request->get('fecha_publicacion'));
        $convocatoria->fecha_publicacion=$date1->toDateTimeString();

        $date2 = Carbon::parse($request->get('fecha_vencimiento'));
        $convocatoria->fecha_vencimiento=$date2->toDateTimeString();

        if (Input::hasFile('documento')){
         $file=Input::file('documento');
         $para_extencion=$file->getClientOriginalName();
         $extension = pathinfo($para_extencion, PATHINFO_EXTENSION);
         $nombre_archivo="pdf_".$request->get('categoria_convocatoria')."_".$request->get('codigo').".".$extension;
         $file->move(public_path().'/archivos/pdf/',$nombre_archivo);
         $convocatoria->documento=$nombre_archivo;
        }

        $convocatoria->update();
        return Redirect::to('convocatoria/locacion');
    }

    public function destroy($id)
    {
        $convocatoria = DB::table('convocatoria')->where('idconvocatoria','=',$id)->delete();
        return Redirect::to('convocatoria/locacion');

    }
}

my edit.blade.php

@extends ('layouts.admin')
@section ('contenido')
    <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <h3>Editar Certificado: </h3>
            @if (count($errors)>0)
            <div class="alert alert-danger">
                <ul>
                @foreach ($errors->all() as $error)
                    <li></li>
                @endforeach
                </ul>
            </div>
            @endif
        </div>
    </div>
            {!!Form::model($convocatoria, ['method'=>'PATCH','route'=> ['convocatoria.locacion.update',$convocatoria->idconvocatoria],'files'=>'true'])!!}<!--creamos el formulario y le damos los prametros es importante patch es editar-->
            <!--agregamos un token-->
            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
            <div class="form-group">
                <label for="descripcion">Descripción</label>
                <input type="text" name="descripcion" required value="" class="form-control" placeholder="Descripción...">        
            </div>      
        </div>
        <!--para el codigo-->
        <div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
            <div class="form-group">
                <label for="codigo">Código</label>
                <input type="text" name="codigo" required value="" class="form-control" placeholder="Código...">           
            </div>      
        </div>
        <!--para la categoria-->
        <div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
            <div class="form-group">
                <label>Categoria</label>
                <select name="categoria_convocatoria" class="form-control">
                    <option value="Bienes" >Bienes</option>
                    <option value="Servicios" >Servicios</option>
                    
                </select>
            </div>
        </div>
        <div class="row"></div>
        <br>

        <div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
            <div class="form-group"><!--creamos la fila para ingresar el nombre-->
                <label for="fecha_publicacion">Fecha de publicacion</label><!--etiqueta-->
                <input name="fecha_publicacion" type="datetime-local" required value="" class="form-control" placeholder="Fecha de Publicación...">
                        
            </div>      
        </div>
        
        <div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
            <div class="form-group">
                <label for="fecha_vencimiento">Fecha de Vencimiento</label>
                <input name="fecha_vencimiento" type="datetime-local" required value="" class="form-control" placeholder="Fecha de Vencimiento...">
                        
            </div>      
        </div>
        
        <!--para el pdf-->
        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
            <div class="form-group">
                <label for="documento">Subir TDR</label>
                <input type="file" name="documento" class="form-control">       
            </div>      
        </div>
            <div class="form-group">
                <button class="btn btn-primary" type="submit">Guardar</button>
                
                <button class="btn btn-danger" onclick="history.go(-1); return false;">Cancelar</button>
            </div>

            {!!Form::close()!!}     
            
        
@endsection

at the beginning I thought it was because I was generating a conflict with the id and idconvocation of my convocation table, but apparently it is not that.

<td>
<a href=""><button class="fa fa-pencil-square-o btn btn-primary"> Editar</button></a>
<a href="" data-target="#modal-delete-" data-toggle="modal"><button class="fa fa-trash-o btn btn-danger"> Eliminar</button></a>
</td>

My Route

Route::resource('convocatoria/locacion','ConvocatoriaController');


via Chebli Mohamed

lundi 16 janvier 2023

How Can I display the product sales per Month using Line Graph

$monthlySales = OrderProduct::selectRaw('sum(amount) as total_sales, month(created_at) as month, year(created_at) as year') ->groupBy('month', 'year') ->get();

        $labels = $monthlySales->pluck('month')->toArray();
        $data = $monthlySales->pluck('total_sales')->toArray();

this is the line graph

var xValues = ['January','Febuary','March','April','May','June','July','August','September','October','November','December']; var yValues = [];

                      new Chart("myChart", {
                        type: "line",
                        data: {
                          labels: xValues,
                          datasets: [{
                            fill: false,
                            lineTension: 0,
                            backgroundColor: "rgba(0,0,255,1.0)",
                            borderColor: "rgba(0,0,255,0.1)",
                            data: yValues
                          }]
                        },
                        options: {
                          legend: {display: false},
                          scales: {
                            yAxes: [{ticks: {min: 0, max:}}],
                          }
                        }
                      });

I tried to use for loop to make a array for the data but still no visible data or maybe I dont have enough data in database?



via Chebli Mohamed

vendredi 13 janvier 2023

Url amigavel com 2 parametros desconfigura html

I am trying to implement friendly URLs on my website, however whenever I use "/" to separate the second argument it works and sends normally but the site doesn't load images and becomes misconfigured. Below is the .htaccess file. I want the images to load normally with one argument I can do it perfectly.

.htacess

RewriteEngine on
# If we receive a forwarded http request from a proxy...
#RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
#RewriteCond %{HTTP:X-Forwarded-Proto} =""
#RewriteCond %{HTTPS} !=on

# Redirect to https version
#RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#RewriteCond %{HTTPS} off
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Acesso http redirecionado para https
#RewriteCond %{HTTPS} off
#RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

#RewriteCond %{HTTPS} !=on
#RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$



RewriteRule ^(.*)$ %{REQUEST_URI}/ [R=301,L]


RewriteRule ^([a-z0-9-]+)/([0-9]+)/?$ index.php?id=$1&nome=$2 [NC]


via Chebli Mohamed

save and update the order of concatenation in the controller

I am looking to concatenate columns into a single , and be able to change the order that I can save it here is the schema of my table:

id col1 col2 col3 separation order ref
A 320 Audi - 'col1','col2','col3' A-320-Audi
A 120 Audi * 'col3','col2','col1' Audi120A
c 220 Aaudi / 'col2','col3','col1' 220/audi/c

in my modification form the user can change the values ​​of the columns also the separation and the order but I also want to save the order that the user has chosen to use it in other pages

in my controller:

serials = Serial::findOrFail($id);
    $serials->update([
        'col1' => $request['col1'],
        'col2' => $request['col2'],
        'col3' => $request['col3'],
        'separation' => $request['separation'],
        'order' => $request['order'],
    ]);
DB::statement(DB::raw("UPDATE serials SET ref = CONCAT_WS(separation,order????) WHERE id = $id"));

problem 1:

how to register the chosen order correctly

in my input request of order someting like = 'col1','col2','col3'

problem 2 :

how to retrieve the value of the order and correctly execute the concatenation from the column order someting like :

DB::statement(DB::raw("UPDATE serials SET ref = CONCAT_WS(separation, ???'column:order'????) WHERE id = $id"));


via Chebli Mohamed

jeudi 12 janvier 2023

how Get Multiple value in array with same id laravel & Angular

Here I am trying to get question. At first understand all system we have quiz making system in that we make quizzes but in there a problem if we put a question in any quiz then we creating other quiz the how can we know this particular question is putted in other quizzes or not if yes then which-which. So, here i am trying to get all quizzes title of particular question id. here is controller code

$questions = DB::table('questionbank')
                ->leftJoin('questionbank_quizzes', function($join)
             {
                 $join->on('questionbank_quizzes.questionbank_id','=','questionbank.id');
             })
             ->leftJoin('quizzes', function($join)
             {
                 $join->on('quizzes.id','=','questionbank_quizzes.quize_id');
                      
                      
             })
            //  ->groupBy('questionbank.id')
                ->where('questionbank.subject_id', '=', $request->subject_id)
                ->select('questionbank.id', 'questionbank.subject_id', 'topic_id', 'question_type', 'question', 'questionbank.marks', 'difficulty_level', 'status','quizzes.title')
                ->get(['questionbank.id', 'questionbank.subject_id', 'topic_id', 'question_type', 'question', 'questionbank.marks', 'difficulty_level', 'status', 'quizzes.title']);
     
      return json_encode(array('topics'=>$topics, 'questions'=>$questions, 'subject'=>$subject));

And This is angular code

$scope.subjectChanged = function(selected_number) {
         
        if(selected_number=='')
            selected_number = $scope.subject_id;
        subject_id = selected_number;
        if(subject_id === undefined)
            return;
        route = '';  
        data= {  _method: 'post', 
                '_token':httpPreConfig.getToken(),
                 'subject_id': subject_id
               };

          httpPreConfig.webServiceCallPost(route, data).then(function(result){

            result = result.data;
            $scope.subjectQuestions = [];
            $scope.subject          = result.subject;
            $scope.subjectQuestions = result.questions;
 
            $scope.contentAvailable = true;

           $scope.removeDuplicates();
        
            });
        }

        $scope.removeDuplicates = function(){
           
            if($scope.savedQuestions.length<=0 || $scope.subjectQuestions.length<=0)
                return;

             angular.forEach($scope.savedQuestions,function(value,key){
                    if(value.subject_id != $scope.subjectQuestions[0].subject_id)
                        return;

                    res = httpPreConfig.findIndexInData($scope.subjectQuestions, 'id', value.question_id);
                    if(res >= 0)
                    {
                         $scope.subjectQuestions.splice(res, 1);
                    }
                    
            });
        }

This is blade view

    <div ng-if="subjectQuestions!=''" class="vertical-scroll" >

                                <h4 class="text-success">Questions @ </h4>
                                <table  class="table table-hover">
                                    <th ></th>

                                    <th></th>

                                    <th></th>

                                    <th></th>

                                    <th></th> 

                                    <th></th>    
                                    <tr ng-repeat="question in subjectQuestions | filter: { difficulty_level:difficulty, question_type:question_type, show_in_front_end:show_in_front_end , topic_id:topic, sub_topic_id:sub_topic } | filter: question_model track by $index ">

                                        <td>@</td>
                                        <td title="@" ng-bind-html="trustAsHtml(question.question)">
                                        </td>
                                        <td>  @ </td>
                                        <td>@</td>
                                        <td>@</td>
                                        <td><a ng-click="addQuestion(question, subject);" class="btn btn-primary" ></a>
                                          </td>
                                    </tr>
                                </table>
                                </div>  
                                </div>
                            </div>

Its result is like this

questions:[
0: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
1: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
2: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
3: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
4: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
5: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
6: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26", topic_id: "120"}
7: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
]

In result you can see with same id title is different but i am stuck here how can i do that. Please help us in this problem. I want result like this..

questions:[
0: {id: "4599", subject_id: "104", topic_id: "120", question_type: "radio",status: "1" subject_id: "104", title: "MOCK TEST NCERT BOOKS CHEMISTRY 26(<br> or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
1: {id: "4600", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(<br> or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
2: {id: "4602", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(<br> or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
3: {id: "4603", subject_id: "104", topic_id: "120", question_type: "radio",status: "1", subject_id: "104", title: ""MOCK TEST NCERT BOOKS CHEMISTRY 26(<br> or ,)MOCK TEST NCERT BOOKS CHEMISTRY 23", topic_id: "120"}
]


via Chebli Mohamed

mercredi 11 janvier 2023

How to implement prepared statement in array_push()

I'm trying to prevent my query from being injected with SQL injection by using a prepared statement. but how to implement prepared statement into array_push()? here I use array push for custom search purposes.

Here is the code snippet that I have now.

public function getDataTable(Request $req) {
    $start = $req->start;
    $length = $req->length;
    $draw = $req->draw;
    $order = $req->order;
    $type = '';
    $where = $this->storeParams($req);
    
    $data = $this->getData($where, $start, $length, $order, $type);
    
    .
    .
    .
    .

    $output = [
        'draw' => (int) $draw,
        'recordsTotal' => $total,
        'recordsFiltered' => $filtered,
        'data' => $data,
    ];
    return json_encode($output);
}

public function storeParams(Request $req) {
    $param = [];

    $start_date = date('Y-m-d');
    $end_date = date('Y-m-d');

    if (!empty($req->studentid)) {
        array_push($param, 'studentid LIKE \'' . $req->studentid . '\'');
    }

    if (!empty($req->studentnm)) {
        array_push($param, 'studentnm LIKE \'' . $req->studentnm . '%\'');
    }

    if (!empty($start_date) && !empty($end_date)) {
        array_push($param, "entrydate between '" . $start_date . "' and '" . $end_date . "'");
    }

    if (count($param) > 0) {
        $where = implode(' and ', $param);
    } else {
        $where = "1";
    }
    return $where;
}

public function getData($where, $start = null, $length = null, $order = null, $type = null) {
    .
    .
    .
    .
    $dataSet = DB::connection('mysql5')->table('tbl_datastudent')
        ->selectRaw("studentid, stuidentnm, address, entrydate, payment, paymentdate")
        ->whereRaw($where);
    .
    .
    .
    .
}

how do i apply the prepared statement into the storeParams() function? anybody can guide or help me?



via Chebli Mohamed