mercredi 30 septembre 2020

How to write if elseif else condition laravel query builder?

Below is my query,

rows = "SELECT * FROM `table` WHERE score = 1"
if (rows.Count < 3) //at least one row
return if;
else if(rows.Count >7)
return 'else if';
else
return 'else';

How to write above query with when using querybuilder laravel. Actually I want to know about how to write else condition.

Below is my code;

$query=DB::table('aaa')
->select('*')
->when($count<3,function ($q){
    echo 'if';
})
->when($count>7,function ($q){
    echo 'else if';
})

///I dont know how to write else condition here


via Chebli Mohamed

Laravel Echo not listening channel using beyondcode / laravel-websockets package

enter image description here I have spent whole day on it can not figure out what is actual problem . When I trigger event it successfully push event to laravel websocket but when it comes to listening the channel it is not listening the channel.

I have run npm run watch Websocket server is running Jobs are also running. My laravel version is 5.8 and beyondcode/laravel-websockets version is 1.6

In my app.js file when I am listening channel here I think is a problem. I also try to console.log() in app.js but it is also not working . I included app.js file in my app.blade.js file like <script src="" ></script>

Here is my app.js file

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

// Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
});

Echo.channel('PrintLabel') // Broadcast channel name
    .listen('.PrintLabel', (e) => { // Message name

        console.log(e); 

    }
    );
    console.log("Hello");
Pusher.logToConsole = true;


via Chebli Mohamed

Get All Products from a single category and its subcategories in laravel

I want to get all products from a category and its subcategory too. But I keep getting the products of the parent and its child category, But neglecting its Grand-Children`

This is my Category structure:

| id | parent_id | name        |
|----|-----------|-------------|
| 1  | NULL      | Vehicles    |
| 2  | 1         | Cars        |
| 3  | 2         | Toyota      |

Category model

public function parent() {
  return $this->belongsTo(self::class,'parent_id','id');
}

public function children() {
  return $this->hasMany(self::class, 'parent_id', 'id');
}

public function products() {
  return $this->hasMany(Product::class);
}

Product model

public function categories() {
  return $this->hasMany(Category::class);
}

In the Controller, my attempt we have

$categoryIds = Category::where('parent_id', $parentId = Category::where('type', 'Vehicle')
->value('id'))
->pluck('id')
->push($parentId)
->all();
Product::whereIn('category_id', $categoryIds)->get();

But like I said, this doesn't get me the products of the grand-children of the parent or even the great-grand children of the category. How can I achieve this?

Thanks.



via Chebli Mohamed

Laravel Eloquent query recursive relationship model with pagination

I am building a store, where I have to display to the user all products in a given category and all other products that are contained in the subsequent subcategories of the currently accessed one. The categories have the N+1 problem since there can be infinite subcategories. I want to be able to filter trough these products and also to be able to paginate them. This is my categories model:

   class CatalogCategory extends Model
   {

    public function parent()
    {
        return $this->belongsTo('App/CatalogCategory','parent_id');
    }

    public function children()
    {
        return $this->hasMany($this,'parent_id')
            ->orderBy('order_place','ASC')
            ->with('children');
    }

    /*
    *   Return products, that belong just to the parent category.
    */

    public function products()
    {
        return $this->hasMany('App\CatalogProduct','parent_id')
            ->where('is_active', 1)
            ->whereDate('active_from', '<=', Carbon::now('Europe/Sofia'))
            ->orderBy('created_at','DESC');
    }

    /*
    *   Return all products contained in the parent category and its children categories.
    */

    public function all_products()
    {
        $products = $this->products;

        foreach ($this->children as $child) {
            $products = $products->merge($child->all_products());
        }

        return $products;
    }

}

The all_products() method returns all of the products, that I want, but since it's a collection i'm unable to paginate or filter through it. My question is if there is a better way to retrieve the products and how to retrieve them so, that i can query them for filtering and paginate them?



via Chebli Mohamed

How to found item in sql Array laravel

I am trying to find an item by id, but my column is a comma separated string(primaryCategory in below screenshot). I want to get this field in my result when query by any string (i.e. by 50,20,41 etc).

I know there could be options like whereIn, whereHas etc. but not able to find correct syntax. Please help me with this.

enter image description here



via Chebli Mohamed

PHP - Adding element dynamically to each json object in array

I am using PHP for adding the JSON element to array.

This is my database table:

enter image description here

Here is my json array:

array:8 [

  0 => {#305
    +"Queue": "755"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
  }
  1 => {#306
    +"Queue": "752"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
  }
  2 => {#304
    +"Queue": "750"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
  }
]

Now I want to add callQueueName to every json object. Tried using put function as shown in below code but not getting added.

Here is my working code:

public static function getLoginAgentInfoTest(){
    $loginAgentInfo = 
      '[{"Queue":"755","Location":"427","MemberName":"PJSIP\/427","Status":"5"},
        {"Queue":"752","Location":"427","MemberName":"PJSIP\/427","Status":"5"},
        {"Queue":"750","Location":"427","MemberName":"PJSIP\/427","Status":"5"}]';

    $loginAgentInfo = json_decode($loginAgentInfo);
    
    $i = 0;
      
    foreach($loginAgentInfo[$i] as $loginData){ 
        
        $callQueueName = Tbcdrqueues::where('callqueue_no',$loginAgentInfo[$i]->Queue)->value('callqueue_name');
 
        $loginAgentInfo[$i].put('callQueueName',$callQueueName);
    
        $i++;
    }

    return $loginAgentInfo;
}

Expected output is:

array:8 [

  0 => {#305
    +"Queue": "755"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
    +"callQueueName" : "New claims"
  }
  1 => {#306
    +"Queue": "752"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
    +"callQueueName" : "Billing"
  }
  2 => {#304
    +"Queue": "750"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
    +"callQueueName" : "Customer_Service"
  }
]

How can I achieve that ?



via Chebli Mohamed

why server not answer to some client but other client not with others

i have a webApp that some people can input data in it . About 100 people that all are company's employee can do this with no problem but one of them is facing with a problem with my webApp . when he/she loads a page of application or query data from server , server does not answer him/her . By replacing his/her computer with another computer , problem will be solved . it depend on the computer . but why this happen . this problem takes place in some special computer and has no related to program .is there ant setting in window or pc that causes this problem? . i wrote this program with laravel 5.2 . i have no idea about it and am so confused . any idea is appreciated .



via Chebli Mohamed

laravel websocket package is not connecting in laravel 5.8

I am using laravel websocket package instead of pusher . I have followed all the steps. server is also running when I connect it it gives these errors.

POST http://127.0.0.1:8000/auth 404 (Not Found)
GET http://127.0.0.1:8000/api/1234567/statistics

It is working fine with pusher but with this package it is creating issue



via Chebli Mohamed

mardi 29 septembre 2020

Fetching report taking lot of time laravel

I have project which contains questions and answer about their vehicle buying experience and generate complaints before and after purchasing vehicle from the showroom,So they call customer and ask set of question regards to vehicle experience, This is outline of the project it's a old project with laravel 5.3 or 5.6 something,Now the problem is

When they taking 1 month report that contains details of cutomer details and vehicle details along with question and their answer to the questions,but if i take 1 month report it taking long time i mean long time,i tried to clear cache and stuff,still problem occurs Can any one help me on this,the data contains about 2000+ data

   public function excelquerep24(Request $request)
    {

        //getting all questions
        $questions = Question::where([['question_schedul', 2], ['status', 0]])->orderBy('order_no', 'asc')->get();

        //get answered customers;
        $answeredcalls =  Registration::
        join('ssi_tracks', 'ssi_tracks.ssi_track_id','=','registrations.registration_id')
        ->select('registrations.customerid', 'registrations.customername', 'registrations.phone', 'registrations.chassis', 'registrations.model', 'registrations.invoicedate', 'registrations.delivery', 'registrations.dealership', 'registrations.zone', 'registrations.branchcode', 'registrations.dh','registrations.zsm', 'registrations.branch', 'registrations.dse',  'ssi_tracks.ssi_track_id')
        ->where('ssi_tracks.track_first_status', '>','0')
        ->whereDate('registrations.delivery', '>=', $request->input('datefrom'))
        ->whereDate('registrations.delivery', '<=', $request->input('dateto'))
        ->distinct('registrations.customerid')
        ->get();
     
            $compsArray = [];


            // Define the Excel spreadsheet headers
        $compsArray[] = ['sl_no', 'Customer ID', 'Customer Name', 'Mobile', 'Chassis No', 'Vehicle Model', 'Invoice Date', 'Delivery Date', 'Dealership','Zone','Branch Code', 'DH','ZSM/SM',  'Branch', 'DSE',   'Status','PSF Date'];
        // return $compsArray;
         foreach ($questions as $question) {
            array_push($compsArray[0], $question->question);
            }
        // Convert each member of the returned collection into an array,
        // and append it to the payments array.

        $array = [];
        $i = 1;
        foreach ($answeredcalls as $call) {
            $newDateFormat3 = date('d-m-Y', strtotime((string)$call->delivery));
            $newDateFormat4 = date('d-m-Y', strtotime((string)$call->invoicedate));
            $call->delivery = $newDateFormat3;
            $call->invoicedate=$newDateFormat4;
            $psf24LastCallDate='';
            if ($call->zsm == '') {
                $sm = Registration::select('sm')->where('customerid', $call->customerid)->first();
                $call->zsm = $sm->sm;
            }
            $ssi = Ssi_track::where('ssi_track_id', $call->ssi_track_id)->first();
            if ($ssi->track_first_status == 1)
                $status = 'Partilly Called';
            if ($ssi->track_first_status == 2)
            {
               $lastcall= Call_track::where([['ssi_track_id', $call->ssi_track_id], ['call_schedule', 1]])->orderBy('call_track_id', 'desc')->first();
               if($lastcall)
               {
                
               
                if ($lastcall->call_responce == 1)
                   $status = 'Call Attended';
               if ($lastcall->call_responce == 2)
                   $status = 'Switched Off';
               if ($lastcall->call_responce == 3)
                   $status = 'Not Responding' ;
               if ($lastcall->call_responce == 4)
                   $status = 'Network Busy';
               if ($lastcall->call_responce == 5)
                   $status = 'Out of Coverage';
                 }  }      
            if ($ssi->track_first_status == 3)
                $status = 'Black listed call';
            if ($ssi->track_first_status == 4)
                $status = 'Call Completed';
            if ($ssi->track_first_status ==5 )
                $status = 'Call Closed';
            $tempArray = json_decode($call, true);
            array_unshift($tempArray, $i);
            $answeredArray = $tempArray;
            array_push($answeredArray,$status);
           $lastcall= Call_track::where([['ssi_track_id', $call->ssi_track_id], ['call_schedule', 1]])->orderBy('call_track_id', 'desc')->first();
           if($lastcall)
           $psf24LastCallDate = date('d-m-Y', strtotime((string)$lastcall->created_at));
                array_push($answeredArray,$psf24LastCallDate );
            
        
            foreach ($questions as $question) {
                $answer = Customer_answer:: join('questions', 'customer_answers.question_id', '=', 'questions.question_id')
                ->select('customer_answers.answer')->where([['customer_answers.ssi_track_id',$call->ssi_track_id ], ['questions.question_schedul', 2],['questions.status', 0],['customer_answers.question_id',$question->question_id]])
                ->orderBy('questions.order_no', 'asc')
                ->first();
                if($answer)
                    array_push($answeredArray, $answer->answer);
                else
                    array_push($answeredArray, " ");
            }
            
            unset($answeredArray['ssi_track_id']);

            $compsArray[] = $answeredArray;

            $i++;
        }

        // Generate and return the spreadsheet
        Excel::create('questionwise report 24 hours', function ($excel) use ($compsArray) {

            // Set the spreadsheet title, creator, and description
            $excel->setTitle('Questionwise');
            $excel->setCreator('Laravel')->setCompany('Beegains, LLC');
            $excel->setDescription('payments file');

            // Build the spreadsheet, passing in the payments array
            $excel->sheet('sheet1', function ($sheet) use ($compsArray) {
                $sheet->fromArray($compsArray, null, 'A1', false, false)
                    ->getStyle('A1')
                    ->getAlignment()
                    ->setWrapText(true);
            });

        })->download('xlsx');
    }


via Chebli Mohamed

Stopping a Laravel Queue after it has finished running

I am running a web application on Laravel 5.5. I have a requirement to run the jobs in a queue and then stop the queue. The queue cannot be allowed to stay running.

I am running the below command but this just endlessly carries on.

php artisan queue:work --tries=3

If I use supervisord can I stop the queue from inside the Laravel application.

Any help is really appreciated.



via Chebli Mohamed

How to edit $request-url in middleware in Laravel 5.8 before it hits route API

I'm developing an API. I want to edit the incoming $request->url so it hits different routes based on the authorization. It should work for any kind of request (POST, GET , DELETE etc...). By now I 've come this far. The middleware get hit, but $request->server->set('REQUEST_URI','http://...'); doesn 't have any effect. The incoming $request url stays at it is. This is the simplified middleware code of the class RedirectToUrl:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Illuminate\Http\Request;
class RedirectToUrl
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
     if($request->user()->role()->first()->role === "admin"){
        $request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/admin');
     }elseif($request->user()->role()->first()->role === "basic"){
        $request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/basic');
     }else{
        $request->server->set('REQUEST_URI','http://rest-api-with-session-httponly:8888/api/basic');
     }
       
         
        return $next($request);
        
    }
} 

I`ve put the middleware RedirectToUrl::class at the end of the middleware priority:

protected $middlewarePriority = [
        \App\Http\Middleware\AddAuthHeader::class,
        \Illuminate\Auth\Middleware\Authenticate::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
        \App\Http\Middleware\CheckRole::class,
        \App\Http\Middleware\RedirectToUrl::class,
    ];

Any hint appreciated. Thx!



via Chebli Mohamed

Laravel: Remove Request Throttling For Authenticated Users

I wish to disable request throttling for users that are authenticated through the API.

Kernel:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:240,1'
    ],
];

Throttle here will limit the requests to 240 per minute regardless of whether or not a user is authenticated.

How would it be possible to do this so it only throttles unauthenticated users?



via Chebli Mohamed

laravel monitor check is getting failed

I am using spatie/laravel-server-monitor package . This package is Failed when run php artisan server-monitor:run-checks

Here is the error

update
  `checks`
set
  `last_run_output` = '{\"output\":\"\",\"error_output\":\"ssh: connect to host xdock.com.au port 22: Connection timed out\r\n\",\"exit_code\":255,\"exit_code_text\":\"Unknown error\"}',
  `checks`.`updated_at` = '2020-09-29 19:28:16'
where
  `id` = 5

host name is correct . but still giving this error



via Chebli Mohamed

Laravel WhereIn

i have maded and database that's name is l6app and i have maked an table product_adds in this table i have save secondary id in array formate. now i am getting data behalf of arrays id using this Query in phpmyadmin

saved data in database like [4,6,5,7,8,]

SELECT * FROM tbl_product WHERE secondy_id IN (4, 5, 6)

above query woring fine in mysql but after that i am using this query in laravel

$product = Product::select("*")
                ->whereIn('secondy_id', [4, 5, 6])
                ->get();

this query not woring in laravel 6.0 showing blank array when i am fetching data from this table



via Chebli Mohamed

lundi 28 septembre 2020

How to installlaravel-server-monitor on laravel 5.8?

I am installing laravel-server-monitor on laravel 5.8 but latest version of it not compatible with it so I tried to install version 1.0 of package but it gives me this error.

Problem 1
    - Conclusion: remove symfony/console v4.4.13
    - Conclusion: don't install symfony/console v4.4.13
    - symfony/process 3.2.x-dev conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.0 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.0-BETA1 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.0-RC1 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.0-RC2 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.1 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.10 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.11 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.12 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.13 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.14 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.2 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.3 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.4 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.5 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.6 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.7 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.8 conflicts with symfony/console[v4.4.13].
    - symfony/process v3.2.9 conflicts with symfony/console[v4.4.13].
    - Installation request for symfony/console (locked at v4.4.13) -> satisfiable by symfony/console[v4.4.13].
    - Installation request for spatie/laravel-server-monitor 1.0 -> satisfiable by spatie/laravel-server-monitor[1.0.0].
    - Conclusion: don't install symfony/process v4.4.13|install symfony/process 3.2.x-dev|install symfony/process v3.2.0|install symfony/process v3.2.0-BETA1|install symfony/process v3.2.0-RC1|install symfony/process v3.2.0-RC2|install symfony/process v3.2.1|install symfony/process v3.2.10|install symfony/process v3.2.11|install symfony/process v3.2.12|install symfony/process v3.2.13|install symfony/process v3.2.14|install symfony/process v3.2.2|install symfony/process v3.2.3|install symfony/process v3.2.4|install symfony/process v3.2.5|install symfony/process v3.2.6|install symfony/process v3.2.7|install symfony/process v3.2.8|install symfony/process v3.2.9
    - Conclusion: remove symfony/process v4.4.13|install symfony/process 3.2.x-dev|install symfony/process v3.2.0|install symfony/process v3.2.0-BETA1|install symfony/process 
v3.2.0-RC1|install symfony/process v3.2.0-RC2|install symfony/process v3.2.1|install symfony/process v3.2.10|install symfony/process v3.2.11|install symfony/process v3.2.12|install symfony/process v3.2.13|install symfony/process v3.2.14|install symfony/process v3.2.2|install symfony/process v3.2.3|install symfony/process v3.2.4|install symfony/process v3.2.5|install symfony/process v3.2.6|install symfony/process v3.2.7|install symfony/process v3.2.8|install symfony/process v3.2.9
    - spatie/laravel-server-monitor 1.0.0 requires symfony/process ^3.2 -> satisfiable by symfony/process[3.2.x-dev, 3.3.x-dev, 3.4.x-dev, v3.2.0, v3.2.0-BETA1, v3.2.0-RC1, v3.2.0-RC2, v3.2.1, v3.2.10, v3.2.11, v3.2.12, v3.2.13, v3.2.14, v3.2.2, v3.2.3, v3.2.4, v3.2.5, v3.2.6, v3.2.7, v3.2.8, v3.2.9, v3.3.0, v3.3.0-BETA1, v3.3.0-RC1, v3.3.1, v3.3.10, v3.3.11, v3.3.12, v3.3.13, v3.3.14, v3.3.15, v3.3.16, v3.3.17, v3.3.18, v3.3.2, v3.3.3, v3.3.4, v3.3.5, v3.3.6, v3.3.7, v3.3.8, v3.3.9, v3.4.0, v3.4.0-BETA1, v3.4.0-BETA2, 
v3.4.0-BETA3, v3.4.0-BETA4, v3.4.0-RC1, v3.4.0-RC2, v3.4.1, v3.4.10, v3.4.11, v3.4.12, v3.4.13, v3.4.14, v3.4.15, v3.4.16, v3.4.17, v3.4.18, v3.4.19, v3.4.2, v3.4.20, v3.4.21, v3.4.22, v3.4.23, v3.4.24, v3.4.25, v3.4.26, v3.4.27, v3.4.28, v3.4.29, v3.4.3, v3.4.30, v3.4.31, v3.4.32, v3.4.33, v3.4.34, v3.4.35, v3.4.36, v3.4.37, v3.4.38, v3.4.39, v3.4.4, v3.4.40, v3.4.41, v3.4.42, v3.4.43, v3.4.44, v3.4.45, v3.4.5, v3.4.6, v3.4.7, v3.4.8, v3.4.9].
    - Can only install one of: symfony/process[3.3.x-dev, v4.4.13].
    - Can only install one of: symfony/process[3.4.x-dev, v4.4.13].
    - Can only install one of: symfony/process[v3.3.0, v4.4.13].
    - Can only install one of: symfony/process[v3.3.0-BETA1, v4.4.13].
    - Can only install one of: symfony/process[v3.3.0-RC1, v4.4.13].
    - Can only install one of: symfony/process[v3.3.1, v4.4.13].
    - Can only install one of: symfony/process[v3.3.10, v4.4.13].
    - Can only install one of: symfony/process[v3.3.11, v4.4.13].
    - Can only install one of: symfony/process[v3.3.12, v4.4.13].
    - Can only install one of: symfony/process[v3.3.13, v4.4.13].
    - Can only install one of: symfony/process[v3.3.14, v4.4.13].
    - Can only install one of: symfony/process[v3.3.15, v4.4.13].
    - Can only install one of: symfony/process[v3.3.16, v4.4.13].
    - Can only install one of: symfony/process[v3.3.17, v4.4.13].
    - Can only install one of: symfony/process[v3.3.18, v4.4.13].
    - Can only install one of: symfony/process[v3.3.2, v4.4.13].
    - Can only install one of: symfony/process[v3.3.3, v4.4.13].
    - Can only install one of: symfony/process[v3.3.4, v4.4.13].
    - Can only install one of: symfony/process[v3.3.5, v4.4.13].
    - Can only install one of: symfony/process[v3.3.6, v4.4.13].
    - Can only install one of: symfony/process[v3.3.7, v4.4.13].
    - Can only install one of: symfony/process[v3.3.8, v4.4.13].
    - Can only install one of: symfony/process[v3.3.9, v4.4.13].
    - Can only install one of: symfony/process[v3.4.0, v4.4.13].
    - Can only install one of: symfony/process[v3.4.0-BETA1, v4.4.13].
    - Can only install one of: symfony/process[v3.4.0-BETA2, v4.4.13].
    - Can only install one of: symfony/process[v3.4.0-BETA3, v4.4.13].
    - Can only install one of: symfony/process[v3.4.0-BETA4, v4.4.13].
    - Can only install one of: symfony/process[v3.4.0-RC1, v4.4.13].
    - Can only install one of: symfony/process[v3.4.0-RC2, v4.4.13].
    - Can only install one of: symfony/process[v3.4.1, v4.4.13].
    - Can only install one of: symfony/process[v3.4.10, v4.4.13].
    - Can only install one of: symfony/process[v3.4.11, v4.4.13].
    - Can only install one of: symfony/process[v3.4.12, v4.4.13].
    - Can only install one of: symfony/process[v3.4.13, v4.4.13].
    - Can only install one of: symfony/process[v3.4.14, v4.4.13].
    - Can only install one of: symfony/process[v3.4.15, v4.4.13].
    - Can only install one of: symfony/process[v3.4.16, v4.4.13].
    - Can only install one of: symfony/process[v3.4.17, v4.4.13].
    - Can only install one of: symfony/process[v3.4.18, v4.4.13].
    - Can only install one of: symfony/process[v3.4.19, v4.4.13].
    - Can only install one of: symfony/process[v3.4.2, v4.4.13].
    - Can only install one of: symfony/process[v3.4.20, v4.4.13].
    - Can only install one of: symfony/process[v3.4.21, v4.4.13].
    - Can only install one of: symfony/process[v3.4.22, v4.4.13].
    - Can only install one of: symfony/process[v3.4.23, v4.4.13].
    - Can only install one of: symfony/process[v3.4.24, v4.4.13].
    - Can only install one of: symfony/process[v3.4.25, v4.4.13].
    - Can only install one of: symfony/process[v3.4.26, v4.4.13].
    - Can only install one of: symfony/process[v3.4.27, v4.4.13].
    - Can only install one of: symfony/process[v3.4.28, v4.4.13].
    - Can only install one of: symfony/process[v3.4.29, v4.4.13].
    - Can only install one of: symfony/process[v3.4.3, v4.4.13].
    - Can only install one of: symfony/process[v3.4.30, v4.4.13].
    - Can only install one of: symfony/process[v3.4.31, v4.4.13].
    - Can only install one of: symfony/process[v3.4.32, v4.4.13].
    - Can only install one of: symfony/process[v3.4.33, v4.4.13].
    - Can only install one of: symfony/process[v3.4.34, v4.4.13].
    - Can only install one of: symfony/process[v3.4.35, v4.4.13].
    - Can only install one of: symfony/process[v3.4.36, v4.4.13].
    - Can only install one of: symfony/process[v3.4.37, v4.4.13].
    - Can only install one of: symfony/process[v3.4.38, v4.4.13].
    - Can only install one of: symfony/process[v3.4.39, v4.4.13].
    - Can only install one of: symfony/process[v3.4.4, v4.4.13].
    - Can only install one of: symfony/process[v3.4.40, v4.4.13].
    - Can only install one of: symfony/process[v3.4.41, v4.4.13].
    - Can only install one of: symfony/process[v3.4.42, v4.4.13].
    - Can only install one of: symfony/process[v3.4.43, v4.4.13].
    - Can only install one of: symfony/process[v3.4.44, v4.4.13].
    - Can only install one of: symfony/process[v3.4.45, v4.4.13].
    - Can only install one of: symfony/process[v3.4.5, v4.4.13].
    - Can only install one of: symfony/process[v3.4.6, v4.4.13].
    - Can only install one of: symfony/process[v3.4.7, v4.4.13].
    - Can only install one of: symfony/process[v3.4.8, v4.4.13].
    - Can only install one of: symfony/process[v3.4.9, v4.4.13].
    - Installation request for symfony/process (locked at v4.4.13) -> satisfiable by symfony/process[v4.4.13].

What could be issue?



via Chebli Mohamed

Multiple groupBy with date in Laravel?

How can I achieve this output (image below).

enter image description here

This is my Types Table.

enter image description here

and this is my Accounts Table.

enter image description here

This is my Type Model.

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

This is my Account Model.

public function type()
{
    return $this->belongsTo('App\Type', 'type_id');
}

What I want to do is, I want to group the accounts table by types and by month, and then I want to add all amount on each month, and display to the table using DataTables.

I tried this code, but it's not giving the expected output.

$query = Accounts::with('type')->whereYear('created_at', $selectedYear)->select('type_id',
    DB::raw('type_id as type_id'), 
    DB::raw('sum(amount) as total_amount'),
    DB::raw("DATE_FORMAT(created_at,'%m') as months")
)->groupBy('months')->get();

I'm still stuck on this part,

Thanks in advance



via Chebli Mohamed

Laravel: Using whereBetween to get back Orders is coming as undefined

I store a timestamp as a string and pass it in to getOrders. I am logging $time so I can see it's valid and being logged as a string timestamp.

I am getting undefined returned back but I can't see how. I am using count($paidOrders) > 0 ? array_values($customers) : [] in the return to protect me from getting back an empty value so that if there are no $paidOrders, I get back an empty array of [], which I would expect if it queries and gets not matching orders within those times.

public function getOrders($time)
{
    try {
        // $time is a timestamp in string format; ex: "1601339962"

        $paidOrders = Order::whereBetween('orders.created_at', [ Carbon::createFromTimestamp($time) , Carbon::now()])->get()->all();
        $customers = [];

        if (count($paidOrders) > 0) {
            foreach ($paidOrders as $paidOrder) {
                if(!isset($customers[$paidOrder->customer_id])) {
                    $customers[$paidOrder->customer_id]['customer_name'] = $paidOrder->ship_name;
                    $customers[$paidOrder->customer_id]['customer_id'] = $paidOrder->customer_id;
                    $customers[$paidOrder->customer_id]['total'] = $paidOrder->subtotal;
                }
                else{
                    $customers[$paidOrder->customer_id]['total'] += $paidOrder->subtotal;
                }
                $customers[$paidOrder->customer_id]['orders'][] = $paidOrder->id;
            }
        }

        return [
            'paidOrdersDuringStream' =>  count($paidOrders) > 0 ? array_values($customers) : [],
        ];
    }


via Chebli Mohamed

Hide url segment in Laravel using htaccess (routes with the same number of segments)

I have these routes in web.php

Route::get('/book/{book}', booksController@show);
Route::get('/user/{user}', UsersController@show);
Route::get('/{category}', CategoriesController@show);

I want to hide book and user from url using htaccess as long as they can't be removed in routes. I tried this in both /.htaccess and in /public/.htaccess but none have worked

RewriteEngine on
RedirectMatch 301 /book/(.*) /$1

RewriteEngine on
RewriteRule ^/book/(.+)$ /$1 [L,QSA]

RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ book/$1 [L]

when I visit a url contains the word book it doesn't get removed it's always there. Now how can I have all three routes without any static word like book or user without any conflict to be like this

Route::get('/{book}', booksController@show);
Route::get('/{user}', UsersController@show);
Route::get('/{category}', CategoriesController@show);


via Chebli Mohamed

How to confirm Laravel Version is updated properly?

I have update laravel version from laravel 5.8 to 6 . When i check php artisan --version it shows me to 6.0 . But it didn't ask me to install laravel/ui package. and its debug screen still looks like laravel 5.8 . How i can confirm that Version is updated correctly



via Chebli Mohamed

How to store Hashed Password to the Database using Laravel 5.8

I need to store Password as hashed to the database, I was able to has the password but when I submit my form the password stores as un-hashed,

Here's my controller Store Function

 public function store(Request $request)
{

    $hash = ['password' => Hash::make($request)];

    //dd($hash);
    // HASHED PASSWORD WAS DISPLAYED HERE 


    $user = User::create($this->validateRequest());

    dd('User Created');
}

Here's my Validate Function

private function validateRequest()
{

    return request()->validate([
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
        'phone' => 'required',
    ]);
}

I tried to do this in my Store Function (But it didn't work !!)

public function store(Request $request)
    {

        $hash = ['password' => Hash::make($request)];

        $user = User::create($this->validateRequest($hash));
        dd('User Created');
   }

Is there a way where I can store the hashed password to the DB by this way ?

Or else do I need to stick to this way ;( ?

$user = User::create([
            'name' => $request['name'],
            'phone' => $request['phone'],
            'email' => $request['email'],
            'password' => Hash::make($request['password']),
        ]);

I just wanted my controllers to be clean with few lines of code.

Can someone please help me out.

Thanks



via Chebli Mohamed

In Laravel ,After registration app redirects to '/home' even after changing $redirectTo variable to '/

I was following the laravel 5.6 documentation and according to them changing $redirectTo variable inside Register Controllers should redirect user to desired location but I always get redirected to '/home'.

RegisterController

protected $redirectTo = '/home';
protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'username' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }

web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');


via Chebli Mohamed

What should be good process to upgrade from laravel 5.8 to laravel 8? [closed]

I read the documentation of laravel they mentioned that it should take 15 minutes to upgrade but I doubt that . Because our project is huge. it is using multiple packages which may be depcrecated. Moreover laravel documentation is not in detail can anyone share trustable platform for upgradation ?



via Chebli Mohamed

What should be good process to upgrade from laravel 5.8 to laravel 8? [closed]

I read the documentation of laravel they mentioned that it should take 15 minutes to upgrade but I doubt that . Because our project is huge. it is using multiple packages which may be depcrecated. Moreover laravel documentation is not in detail can anyone share trustable platform for upgradation ?



via Chebli Mohamed

I want to use here map for task [closed]

my task is to use here and get a map like this https://dawa.center/islamic_centers but I tried to use here cluster it does not make the same job like this example. I can not handle click event to zoom if click on cluster there is any suggestion to solve this problem.



via Chebli Mohamed

How to use FTP in laravel

below query is working in mysql

SELECT cl.Title, p.Title as ParentTitle,cd.Trainer, day(cd.StartingDate) as day, day(cd.EndingDate) as day_end, MONTH(cd.StartingDate) as month, year(cd.EndingDate) as year, cd.StartingDate, cd.EndingDate, cd.Duration,cd.Type, cd.Fee, cd.Venue, count(s.Id) as total_registartion from CourseListNew cl left join CourseListNew p on p.Id=cl.ParentId join CourseDetailsNew cd on cl.Id = cd.CourseId left outer join Student s on cl.Id = s.CourseId where cl.Id != 0 group by cd.CourseId order by total_registartion desc

But in sql server throwing below error

Column 'CourseListNew.Title' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

if i somehow adjust one column in aggregate function or group by the error just keeps forwarding to next parameter. I have tried everything but still not able to find any resolution to the problem. please help.



via Chebli Mohamed

Export PDF with images in Laravel?

I exported the table data into pdf. I have an image column in the table.

After exporting this column appears as blank column instead of holding images.

My controller:

  //upload document
        $product_details['image'] = $this->productUtil->uploadFile($request, 'image',  
      ('constants.product_img_path'), 'image');
        $imgData = base64_encode($product_details['image']);

And this is my script code.

 var pdf_btn = {
    extend: 'pdfHtml5',
    orientation: 'landscape',
    text: '<i class="fa fa-file-pdf" aria-hidden="true"></i> ' + LANG.export_to_pdf,
    className: 'btn-sm',
    
    exportOptions: {

        columns: ':visible',
    },
    footer: true,

Please some body help....



via Chebli Mohamed

How to add custom options to Form Builder

I'm working with Jquery Form Builder (https://formbuilder.online/) and I got to the task: add more options field.(You already have one options file. I know But i want to add another one. So that you have 2 options field with both add options.)

I want to do it without change the core of this jquery plugin.

THX,



via Chebli Mohamed

Laravel package not merfing second last file

I am using laravel package to merge files . it is working fine on localhost but on server it missed second last file to merge what could be the issue?

if ($this->last) {
            $pdfMerger = new  PdfMerger();

            $bulk_pdf = public_path('bulk-pdf-consignment/manifest' . $this->manifest_id . '_.pdf');
            $allFilesPath = public_path('bulk-pdf-consignment/manifest_' . $this->manifest_id);

            // if (File::exists($bulk_pdf)) {
            //     $pdfMerger->addPDF($bulk_pdf, 'all');
            // }
            $filesInFolder = collect(File::files($allFilesPath))->sortBy(function($file) {
                return $file->getCTime();
              });
         
           $arr = [];
            foreach ($filesInFolder as $path) {
                $file = pathinfo($path);
                $finalPath = $file['dirname'] . '/' . $file['basename'];

                $added =  $pdfMerger->addPDF($finalPath, 'all');
                // if ($added) {
                //     array_push($arr, $finalPath);
                // }
            }

            $merged =  $pdfMerger->merge("file", $bulk_pdf);



via Chebli Mohamed

How to show errors in Laravel Website instead of 500 page

In a Laravel website, whenever PHP error occurs I see a customized screen of 500 Error instead of the error message. I tried to write error_reporting but still error cannot show.

How to fix this?



via Chebli Mohamed

dimanche 27 septembre 2020

How to fetch files on bases of created_at in laravel?

I have multiple files in folders and I am getting files to merge them . Now I want them to fetch these files in ascending order on the base of created date? Which file is created first should come in loop iteration first.

 $bulk_pdf = public_path('bulk-pdf-consignment/manifest' . $this->manifest_id . '_.pdf');
 $allFilesPath = public_path('bulk-pdf-consignment/manifest_' . $this->manifest_id);
 $filesInFolder = File::files($allFilesPath);
 foreach ($filesInFolder as $path) {
                $file = pathinfo($path);
                $finalPath = $file['dirname'] . '/' . $file['basename'];
                $pdfMerger->addPDF($finalPath, 'all');
              
            }



via Chebli Mohamed

Redirect url in laravel

My website Was run with laravel But its address is displayed in Google in this way👇👇

https://ift.tt/3cxlC1G

How i can delete (public) from my url?

This is my .htaccess codes:👇

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
   RewriteRule ^(.*) http://%1/$1 [R=301,NE,L]
   RewriteRule ^(.*)$ public/$1 [L]
   
</IfModule>

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php73” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php73 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit


via Chebli Mohamed

Laravel Email in Job Queue not working except sync

I am using Laravel 5.8, I configured an email containing the invoice sent to user after they place an order. Email is delivered when set QUEUE_DRIVER=sync but when I set it to redis/database and I run the php artisan queue:work redis --tries=5 it shows the queue is processed

Processing: Modules\Checkout\Mail\Invoice
Processed: Modules\Checkout\Mail\Invoice

succesfully and no entry in the failed_jobs either.

CODE: Modules\Checkout\Jobs\SendInvoiceEmail.php

    class SendInvoiceEmail implements ShouldQueue
    {
      use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

      public $order;
      public function __construct(Order $order)
      {
        $this->order = $order;
      }

      public function handle()
      {
        Mail::to($this->order->customer_email)
              ->send(new Invoice($this->order));
      }
    }

And this is the Modules\Checkout\Mail\Invoice.php

class Invoice extends Mailable
{
    use Queueable, SerializesModels;

    public $order;

    public function __construct($order)
    {
        $this->order = $order;
    }

    public function build()
    {
        return $this->subject('New order: ', ['id' => $this->order->id]))
            ->view("emails.invoice");
    }

}

Then I am dispatching it in the Controller after Order created
SendInvoiceEmail::dispatch($order);

Can anyone point out if I've missed anything and what I am doing wrong?

I've done the php artisan config:cache and clear:cache restarted the server.

This works just as expected if I set QUEUE_DRIVER=sync in .env instead of QUEUE_DRIVER=redis or database



via Chebli Mohamed

Vuetify Nuxt.js : how to add Routing link in Carousels icon

js and Vuetifiy i want to add Routing link in Carousels icon. if i press icon it should open Routing link. i tried but its not responding my link its not working below code i tried but note worked

          {
            images: [
              { src: "/image1.png", caption: "Shopping-Page", to:"/ShoppingPage"},
              { src: "/image2.png", caption: "Cart-Page", to:"/CartPage" },
              { src: "/image3.png", caption: "main-Page", to:"/mainPage" }
              
            ]
          },

My router links this below router links i want to add

 to="/ShoppingPage" 

 to="/CartPage" 

 to="/mainPage"

my page view locking like this

enter image description here

my code

<template>
  <v-layout style="width: auto;" class="ma-auto">
    <v-carousel cycle light height="309" hide-delimiter-background show-arrows-on-hover>
      <v-carousel-item v-for="(slide, i) in slides" :key="i">
        <v-row>
          <v-col cols="3" v-for="(images, j) in slide.images" :key="j">
            <div class="d-flex flex-column justify-center align-center">
              <v-img :src="images.src" width="30"/>
              <span class="mx-auto text-center caption"></span>
            </div>
          </v-col>
        </v-row>
      </v-carousel-item>
    </v-carousel>
  </v-layout>
</template>

<script>
export default {
  name: "playground",
  data: () => ({
    slides: [
      {
        images: [
          { src: "/image1.png", caption: "Shopping-Page"},
          { src: "/image2.png", caption: "Cart-Page" },
          { src: "/image3.png", caption: "main-Page" }
          
        ]
      },


via Chebli Mohamed

Get/Sort a category of post from a location and its sub-locations Laravel

So I have a relationship between models; category, location, and post model. In the location table, there is a column called parent_id which stores the id of any location in that table, chosen to be the parent.

For Example: I can store a country as location and store a state to be under it, and also store a city under that state too;

United States
- New York
  - Buffalo, New York

But I want to be able to find a category in not just the location but also its sub-locations or the locations under it.

This code only gets me the category from one location, and not its sub-locations too

return $category->post()->where('status', '=', 'PUBLISHED')->where('location_id', '=', $location->id)->get();

I want to be able to check the category in its sub-locations too

Please help. Thanks in advance.



via Chebli Mohamed

samedi 26 septembre 2020

Laravel 5.5.50 - Session doesn't persist for api. Interestingly it works with postman but not with our Shopify store that sends the API request

Our Shopify store talks to our laravel app by sending an API call. I need to cache a value on the server to improve the loading speed for the next API request. I have tried almost all solutions mentioned in stackoverflow and other places, but non of the worked for me!

Interestingly, when I test it using postman it works fine (in both my local and staging) and the session persists, but when Shopify sends the API request, the session doesn't persists and returns null! (when the client enters a postcode in a form in Shopify, and submits it, the request is sent to the laravel app). I also cleared the cache but didn't work (php artisan cache:clear, config:clear, config:cache, route:clear)

I have no idea whether I am missing something or it is bug for laravel. Please see my code bellow. I highly appreciate your help. Also please let me know about any other alternative way?

app/Services/abc.php

Use Illuminate\Support\Facades\Session;
...

    public function resolve(Address $shippingAddress, Collection $lineItems) : Collection
    {
        ...
        Session::put($sessionShippingAddress, $shippingAddress);
        Session::save();
        ...
    }
...

Kernel.php

    protected $middleware = [
        ...
        \Illuminate\Session\Middleware\StartSession::class
    ];

Routes/api.php

...
Route::post('abc', 'abcController@calculateSimple');
...

session.php

...
    'lifetime' => env('SESSION_LIFETIME', 5),
    'expire_on_close' => false,
...


via Chebli Mohamed

Laravel - Can I add a route with .php extension in laravel project?

I am a beginner to laravel and I am facing a scenario where I need to add a .php extension file to get some data from another website and redirect it to another route. I tried using .php file and .php route i.e Route::get('/postback.php' , 'UserController@offerwalls_postback')->name('postback_offerwalls'); but it is not working. The route I want to access is www.domain_name.com/postback.php?data. I have tried numerous ways to do it but can't make it work. Is there anything that can be done? Any help would be appreciated. Thanks



via Chebli Mohamed

Set select for Jquery select in Laravel (blade file)

I know I can set selected attribute for a select tag with old put filed:

<select name="country" id="state" onChange="loadlist(this.value);" >
    <option value="usa" >USA</option>
    <option value="grm" >Germany</option>
    <option value="eng" >England</option>
</select>

But in that form, I have another select tag that use from a Jquery file for load options:

<select name="state" id="state" class="form-control arrow-black">
    <option value="">Select country</option>
</select>

the Jquery codes:

function loadlist(country){
with(document.getElementById('state')) 
    {
        options.length = 0;

    if(country == ''){
        options[0] = new Option('Select country' , '');
    }
    if (country == 'usa') {
        options[0] = new Option('Select' , '');
        options[1] = new Option('NewYork' , 'NewYork');
        options[2] = new Option('Florida' , 'Florida');
        options[3] = new Option('California' , 'California');
    }
    if (country == 'grm') {
        options[0] = new Option('Select' , '');
        options[1] = new Option('Bayern' , 'Bayern');
        options[2] = new Option('Hamburg‎' , 'Hamburg‎');
        options[3] = new Option('Berlin' , 'Berlin');
    }
    if (country == 'eng') {
        options[0] = new Option('Select' , '');
        options[1] = new Option('Buckingham' , 'Buckingham');
        options[2] = new Option('Cambridge‎' , 'Cambridge‎');
        options[3] = new Option('London' , 'London');
    }
}
}

how can I set for the 2nd select tag?



via Chebli Mohamed

How to use old() helper in input fields of Laravel blade

In my Laravel-5.8 project I am working on a leave application that will iterate with employee_type. The fields in the view blade are array elements. The code is as shown below:

@foreach ($employeetypes as $key=> $employeetype)
<tr>
  <td width="5%">
    
  </td>                             
  <td width="30%">  
    <span></span> 
  </td>
  <td width="20%"><input type="number" name="no_of_days[]" placeholder="Enter leave days here" class="form-control no_of_days" max="120">
  </td>
  <td width="15%">                    
  <select class="form-control select2bs4" data-placeholder="Select Applicable Gender" tabindex="1" name="leave_applicable_gender[]">
   <option value="0" selected="true" disabled="true">Select Applicable Gender</option>                                                          
      @foreach(AppHelper::LEAVE_APPLICABLE_GENDER as $key1 => $value)
   <option value="" >
       
    </option>
      @endforeach                                       
   </select>                                 
   </td>                                                                  
  <td width="10%"><input type="checkbox" name="weekend_inclusive"  class="form-control" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES">
   </td>
 @endforeach

Everything submits to the database successfully. Since all are array fields, how do I add old() helper to each of the input fields (number, dropdown and checkbox)?

Thank you



via Chebli Mohamed

How to fix query builder error sql injection in laravel 5.5.*

I am using laravel 5.5. * And I'm testing with vega scanner and getting SQL injection error. How to fix this problem.?

this is the complete error specification



via Chebli Mohamed

Laravel - Avoid duplicate controller code when using @include directive from within another view

I have a controller function that renders a view called Dashboard and other function with duplicate code for updating sub view.

public function dashboard(Request $request) {
        
    // GET ALL THE VARIABLES AND PASS THEM TO THE VIEW
   
    return view('pages.dashboard.dashboard', compact('variables'));
}
public function dashboardIndicators(Request $request) {
        
    // GET ALL THE VARIABLES AND PASS THEM TO THE SUB VIEW
    return view('pages.dashboard.dashboardindicators', compact('variables'));
    }

Dashboard view includes the subview for displaying some data of the entire page:

<div id="dashboardindicators">
        @include('pages/dashboard/dashboardindicators')
</div>

I update the subview data with AJAX when user changes a dropdown and is working correct:

<script>
    $(document).ready(function () {
    
    $('.dropdown_get').on("change", function(){

        KTApp.block("#dashboardindicators", {
                overlayColor: "#000000",
                type: "v2",
                state: "success",
                message: "Procesando..."
            }),
        
        $.ajax({
        url: "/dashboard/indicators",
        method: 'GET',
        data: {
            market_center_id: $("#kt_market_center_dropdown option:selected").val(),
            mega_agent_id: $("#kt_mega_agent_dropdown option:selected").val(),
            team_id: $("#kt_team_dropdown option:selected").val(),
        },
        success: function (data) {
            $("#dashboardindicators").html(data)
           setTimeout(function () {
                KTApp.unblock("#kt_blockui_1_content")
            })
        }
        });
    
    });
});
</script>

My problem is that the controller function that renders Dashboard view has the same code as the function that returns the data for subview when AJAX is called although the only difference is the view that both are ruturning.

Is there any way I can avoid duplicating code and render Dashboard view correctly and don't break subview AJAX data update?

Regards



via Chebli Mohamed

Laravel-5.8 file is not updating

I changed some code in public/js/app.js file, it works fine on local server but when i do the same changes on live server it did not work. even I removed all codes from app.js file but still it does have any effect on it.

please someone help me.



via Chebli Mohamed

Laravel Redirect to home page

I am using Language switch to switch between English and Arabic.It is working fine in all the links except Home page.

1)If I have not authenticated it is working fine it is redirecting to http://domain.name/en/login

2)If I have auntenticated or logged in and try to access the url http://domain.name/ it is redirecting to http://domain.name/home instead of a http://domain.name/en/home

I have changed in all the Auth files by adding a function

public function redirectTo(){
    return app()->getLocale().'/home';
}


via Chebli Mohamed

why OrderBy is not working in my query Laravel

I am trying to use orderBy in my query, but its not working , $price contain 'asc' and 'desc' value after submitting form, but same value is showing in my blade. After click price (high to low) I want to show Product with high to low prices. Thanks Advance

values coming from blade

    return Listing_property::latest()
        ->when($city, function ($query, $city) {
            return $query->where('city', '=', $city);
        })
        ->when($type, function ($query, $type) {
            return $query->where('property_type', '=', $type);
        })
        ->when($purpose, function ($query, $purpose) {
            return $query->where('purpose_type', '=', $purpose);
        })
        ->when($bedroom, function ($query, $bedroom) {
            return $query->where('bed_room', '=', $bedroom);
        })
        ->when($bathroom, function ($query, $bathroom) {
            return $query->where('bathroom', '=', $bathroom);
        })
        ->when($minprice, function ($query, $minprice) {
            return $query->where('price', '>=', $minprice);
        })
        ->when($maxprice, function ($query, $maxprice) {
            return $query->where('price', '<=', $maxprice);
        })
        ->when($property_size, function ($query, $property_size) {
            return $query->where('property_size', '>=', $property_size);
        })
        ->when($property_area_type, function ($query, $property_area_type) {
            return $query->where('property_area_type', '<=', $property_area_type);
        })
        ->when($price, function ($query, $price) {
            return $query->orderBy('price',$price);
        })
        ->where('add_type', $types)
        ->paginate(3);

}


via Chebli Mohamed

vendredi 25 septembre 2020

Laravel Blade, compile all @includes before checking for variables or pass foreach variable without error

This question is similar to my previous question (Laravel Blade, Pass a function through @include without checking if it exists in main view), but the solution there doesn't work this time.

I am compiling multiple similar views using @includes to reuse code. Sometimes the @includes are within foreach loops, sometimes they are not. When they are in loops, I need to pass variables that access the variable as defined in the foreach loop.

recipes.blade

...
@include('text'
 [
    'value' => $recipe->title
 ])
@include('nested'
[
    'value' => $recipe->directions
 ])
...

container.blade

<ul>
  @foreach ($value as $instance)
       <li>
       @yield('contents')
       </li>
  @endforeach
</ul>

nested.blade

@extends('container')

@section('contents')
  @include('text'
    [
        'value' => $instance->description
     ])
  @include('text'
    [
        'value' => $instance->content
     ])
@endsection

Text.blade

<p></p>

I need to pass $instance as part of the variable. I also tried checking in the text.blade file if a loop is in progress - if I could determine that I could add an if/else statement to handle the issue. Both create an error, as Laravel sees that neither $instance nor $loop are defined.

I would prefer a way to force Laravel to compile the entire file, before checking if variables exist (right now it seems to be checking in each partial file before compiling). If it would check in the context of the entire file it wouldn't load text.blade until it has opened the loop, making $instance available. A way to pass the $instance variable without an error AND allowing it to be used in the view would be another way around the issue.

How can I use the same partial inside and outside loops?



via Chebli Mohamed

Laravel logging "Class 'Arr' not found in Command line code:1"

The error below is the stack trace which is being logged to the laravel storage log every minute.

[2020-09-25 19:51:40] local.ERROR: Uncaught Error: Class 'Arr' not found in Command line code:1
Stack trace:
#0 {main}
  thrown {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalErrorException(code: 1): Uncaught Error: Class 'Arr' not found in Command line code:1
Stack trace:
#0 {main}
  thrown at Command line code:1)
[stacktrace]
#0 {main}
"} 

I haven't used this anywhere in my controllers or blade templates.

Any help is appreciated.



via Chebli Mohamed

Merging File using all server resouces in laravel

I have created job which is responsible for merging files. On localhost it is working fine. On server for almost hundred pdfs it work fine but as the number of pdfs increases it starts using all servers resources. And in result Server Got hanged for hours .I believe something is wrong with my algorithm But can't find out. It is for almost 1500 pdfs. Here is the code this job is receiving pdf one by one

<?php

namespace App\Jobs\Consignment;

use App\Helpers\Notification_Helper;
use App\Models\Admin\Contact;
use App\Models\Admin\Manifest;
use App\Models\Admin\Staff;
use CodeItNow\BarcodeBundle\Utils\BarcodeGenerator;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Barryvdh\DomPDF\Facade as PDF;
use DirectoryIterator;
use PDFMerger;
use File;
use Illuminate\Support\Facades\Storage;

class BulkPdfPrintLabel implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $consignments;
    protected $last;
    protected $manifest_id;
    protected $user_id;
    protected $user_type;
    protected $filepath;
    public $timeout = 3600;

    public function __construct($consignments, $last, $manifest_id, $user_id, $user_type,$filepath)
    {
        $this->consignments = $consignments;
        $this->last = $last;
        $this->manifest_id = $manifest_id;
        $this->user_id = $user_id;
        $this->user_type = $user_type;
        $this->filepath =$filepath;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $directory_path = public_path() . '/bulk-pdf-consignment/manifest_'.$this->manifest_id;
        if (!File::exists($directory_path)) {
            File::makeDirectory($directory_path, $mode = 0777, true, true);
        }

        $allDataConsignments = array();
    
        foreach ($this->consignments  as $key => $consignment) {
            // "printnum" => "1"

            // $consignment = $allConsignment::with('customers', 'pickup_addresses');

            $barcode = new BarcodeGenerator();
            $barcode->setText($consignment->barcode);
            $barcode->setType(BarcodeGenerator::Code128);
            $barcode->setScale(2);
            $barcode->setThickness(30);
            $barcode->setFontSize(10);
            $code = $barcode->generate();

            // This  $data array will be passed to our PDF blade
            $data = [
                'consignment' => $consignment,
                'barcode' => $code
            ];

           
            array_push($allDataConsignments, $data);
        }

        $customPaper = array(0, 0, 430.00, 283.80);
        $title = 'Consignment Bulk PDF';
        $pdf = PDF::loadView(
            'web.admin.partials.transports.consignments.consignment_bulk_pdf',
            compact('allDataConsignments', 'title')
        )->setPaper($customPaper, 'landscape');
       
         $pdf->save($this->filepath); 
    }
}


via Chebli Mohamed

Laravel 419 Page Expired while submitting a form

While submitting a form on a pop-up modal the page gets expired on laravel, I am sending a post request. Can someone please help? i have added a csrf token too..

View Blade

<div id="reviewModal-" class="modal fade" role="dialog">
   <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
         <div class="modal-header" >
         </div>
         <div class="modal-body">
            <form id="ecgreviewform" class="ecgreview" action="" method="POST">
               @csrf 
               <div class="col-md-6">
                  <div class="form-group">
                     <input type="text" class="form-control" placeholder="tesdt" id="exampleInputEmail1" aria-describedby="emailHelp" value="">
                  </div>
               </div>
   <div class="modal-footer">                                                        
   <div class="row">
   <div class="col-md-6">
   <button type="button" style = "width:50%;" class="btn btn-primary btn-outline-blue btn-close-modal" data-dismiss="modal">Cancel</button>                                                
   </div>
   <input type="hidden" name="participant_id" value="">
   <div class="col-md-6">
   </div>
   </div>    
   <button type="submit" form="ecgreviewform" style = "width:50%;" name="submit" value="submit" class="btn btn-primary">Save</button>  
   </form>
   </div>
</div>
</form>
</div>
</div>

Route page

Route::get('ecg/pendingreview', 'EcgReviewController@index')->name('ecg.pendingreview');
Route::post('ecg/pendingreview', 'EcgReviewController@store')->name('ecg.reviewstore');

is there any reason



via Chebli Mohamed

Laravel Reset Password - non unique email with additional condition

I am wrecking my brain over this. So I have non unique emails because we have different events that registers guests and one guest can register to more than one event with same email. Registeration isnt hard the problem is with forget password. I have added a new column in password_reset table with name event_id. I overrided the default sendResetLinkEmail with the following code. So that lets me update the event id with the token that is stored. what it looks like

    /**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function sendResetLinkEmail(Request $request)
    {
        $this->validateEmail($request);
        $event_id = Event::where('event_url',session('slug'))->first()->id;
        $userData = $this->credentials($request);
        $userData['event_id'] = $event_id;
        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $userData
        );
        
        DB::table('guest_password_resets')->where('email', $request->email)->update(['event_id' => $event_id]);
        return $response == Password::RESET_LINK_SENT
                    ? $this->sendResetLinkResponse($request, $response)
                    : $this->sendResetLinkFailedResponse($request, $response);
    }

The problem is, if I want to reset password of event A and not the event B whose token is also present in password_reset, it will replace the token and update the event_id of the event B rather than create a new token for the event A for the same email.

All I want it to do is create new entries based on event_id and not email. Is there any custom way for this?



via Chebli Mohamed

How to attach middleware to an existing named route from a package in laravel 5?

I'm trying to extend an existing application without modifying its source code. The application has a named route called wizard-add. Is there a way to register \MyPackage\MyMiddleware with the existing route? I tried attaching it via Route::getRoutes()->getByName('wizard-add')->middleware(\MyPackage\MyMiddleware::class); but since packages are registered before the routes are read, Route::getRoutes() returns an empty collection.

Thank you!



via Chebli Mohamed

Laravel Localization Language Switcher using currentRouteName pass argument

I am having an issue with language switcher, when trying to execute a route with more than one parameter

I get following error message

    Missing required parameters for [Route: client.edit] [URI: {language}/client/{id}/edit].

in the header having an switcher code Route::currentRouteName()

          <ul class="dropdown-menu" role="menu">
            <li><a href="">EN</a></li>
            <li class="divider"></li>
            <li><a href="">AR</a></li>
          </ul>

I tried below code, it is not working

            <?php if(isset(request()->id)) { ?>
                <li><a href="">EN</a></li>
                <li class="divider"></li>
                <li><a href="">AR</a></li>             
            <?php } else {  ?>
            <li><a href="">EN</a></li>
            <li class="divider"></li>
            <li><a href="">AR</a></li>
            <?php } ?>


via Chebli Mohamed

Whoops, looks like something went wrong in LARAVEL

I try to save a form in laravel

<form action="" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="card card-info">
                            <div class="card-header">
                                <h3 class="card-title">Détails</h3>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label class=" form-control-label">Description</label>
                                            <textarea name="description" class="textarea" name="description"></textarea>
                                            @if ($errors->get('description'))
                                                @foreach ($errors->get('description') as $error)
                                                    <div class="invalid-feedback">  </div>
                                                @endforeach
                                            @endif
                                        </div>
                                    </div>
                                </div>`

And in the textarea, i use the plugin summernote, like in the picture enter image description here

whene i try to save in i get the message error enter image description here

The controller action enter image description here

The route enter image description here

No error in log file and i make true to the debug



via Chebli Mohamed

jeudi 24 septembre 2020

combine and merge array in laravel

while merging array i got many isseus. i used array_merge and array_combine in laravl but no success

array:4 [▼
  "resident_id" => array:19 [▼
    2 => "2"
    1841 => "1841"
    
  ]
  "community_id" => array:19 [▼
    2 => "25"
    1841 => "25"
    1843 => "25"
    
  ]
  "out_of_community" => array:5 [▼
    2 => 
      "2020-09-25"
                                      
    
    1841 =>
      "2020-09-25"
                                      
      "
  ]



 i want 

  resident_id   community_id  out_of_community
    2             25            2020-09-25
    1841           25            2020-09-25

please help me to solve it.

i did

$arr = $request->all(); $a = array_merge($arr);



via Chebli Mohamed

PDF merger is not working on live server laravel

I am using laravel package for merging pdf . This is handle function of Job which is merging in on existing file on directory but on server it skip sometimes for example it will merge 300 out of 500 files.

I think there is some thing wrong with my logic

if (File::exists($this->filepath)) {
            $pdfMerger =new  PdfMerger();
            $pdfMerger->addPDF($this->filepath, 'all');
            $bulk_pdf = public_path('bulk-pdf-consignment/manifest' . $this->manifest_id . '_.pdf');
            if (File::exists($bulk_pdf )) {
                $pdfMerger->addPDF($bulk_pdf , 'all');
            }
      
            
            $merged =   $pdfMerger->merge("file",$bulk_pdf);

Here is the exceptions it gives sometimes

Exception: Unable to find object (3, 0) at expected location. in /var/www/html/coldxlogistics/vendor/rguedes/pdfmerger/Classes/fpdi/pdf_parser.php:675


via Chebli Mohamed

Virtual hist with port number not working

I'm using ec2 linux Instance for hosting a laravel app. I'm using apache 2.4.i'm trying to setup 2 app with different domain on the same instance. I have tried almost everyting but it doesn't seem to be working

I created hosts.conf file under /etc/httpd/conf.d/

If I use this as content :

DocumentRoot "/var/www/html/site1/public/"
<Directory "/var/www/html/site1/public">
        AllowOverride All
        Require all granted
</Directory>

It works perfectly

but if I change it to

<VirtualHost *:80>
    ServerName site1.com
    ServerAlias www.site1.com *.site1.com
    DocumentRoot "/var/www/html/site1/public"
    DirectoryIndex index.php
        <Directory "/var/www/html/site1/public">
            AllowOverride All
            Require all granted
        </Directory>
</VirtualHost>

It starts to display the folderenter image description here view of the /var/www/html/ directory



via Chebli Mohamed

Deloying Laravel Mix with Docker Compose

I'm trying to deploy and old Laravel(5.8) app using docker compose. I've been searching the web but all I can see is deploying laravel with docker-compose but can't find any article discussing how to deploy with laravel mix.

Thanks in advance guys.



via Chebli Mohamed

how to handle sort by with products laravel

I am trying to sort my product through click on this buttons, but above check is not working enter image description here



via Chebli Mohamed

Configure Laravel and VueJs on a domain

I have the following 2 projects

  • Project1) /var/www/html/laravel58/public
  • Project2) /var/www/html/vue2/dist

Project1 (Laravel) is currently configured on my domain http//www.domain.com

How to configure VueJs Project2 (VueJs) as http//https://ift.tt/2GabNKL

The current apache config is as under

<VirtualHost *:80>
    ServerName domain.com
    ServerAdmin admin@domain.com
    DocumentRoot /var/www/html/laravel58/public

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <Directory /var/www/html/laravel58/public/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>


via Chebli Mohamed

lynx39/lara-pdf-merger not working on live ubuntu server Laravel

I am using this package https://packagist.org/packages/lynx39/lara-pdf-merger for merging pdfs. This package is working fine on localhost but not working on live server .

Giving this error

Exception
Symfony\Component\Debug\Exception\FatalThrowableError: Class 'TCPDI' not found in /var/www/html/coldxlogistics/vendor/daltcore/lara-pdf-merger/src/LynX39/LaraPdfMerger/PdfManage.php:19

What could be the reason?



via Chebli Mohamed

Get the details but ignore user if exist another higher level

I have a table looks like

id  user_id  level

1     1        1
2     1        2
3     2        1
4     3        1

Here user id 1 exist in level 1 and level 2 Now when we count group by level then in counting we want ignore user_id 1 from level 1 cause it exist another group. we want to consider only one group existing and higher group.

I have done only group count but cant understand how ignore counting.

My current query is

UserCertificate::with('user')->where('level','1')->distinct('level')->orderBy('id','ASC')->get();

My Query return counting

id  user_id  level

1     1        1
3     2        1
4     3        1

But I want looks like

id  user_id  level

3     2        1
4     3        1

User Id 1 will be ignored cause it exist in level 2



via Chebli Mohamed

mercredi 23 septembre 2020

Destroy session on closing tab or window in laravel

I want to destroy session when tab/window close in laravel . I also changed

'expire_on_close' => true, //config/session.php

but still not working. I also executed necessary commands. like config:cache, config:clear , composer dump-autoload . Not working . Thanks in advance



via Chebli Mohamed

Laravel blade Variable issues -> undefined index

I am facing some issues when passing a variable to my view with an image path.

When I trying to use this to get the image path

@foreach ($data as $dat)
<img class="img-responsive" src="" alt="">
@endforeach

I get this error

Undefined index: wp:featuredmedia (View: /Users/sam/Documents/development/shop/resources/views/landing-page.blade.php)

When I use only I get the correct path to the image without an error.

How can I fix this ?

Thanks



via Chebli Mohamed

Laravel/homestead - No input file specified

I'm new to Laravel, trying to set up very first website, but getting "No input file specified" when trying to open my website "belekas.test" I believe that my yaml and hosts files are correct, but will include pictures of it.

Things I have tried:

vagrant halt

vagrant up

vagrant ssh

vagrant reload --provision

serve homestead.app public

sudo service nginx restart

yaml:

ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox


folders:
    - map: ~/Laravel
      to: /home/vagrant/Laravel

sites:
    - map: belekas.test
      to: /home/vagrant/Laravel/belekas/public

databases:
    - homestead

hosts: 192.168.10.10 belekas.test

that's how my terminal looks like:

enter image description here

Update: After running vagrant up --provision and vagrant reload --provision few times, my page load into another Class 'Illuminate\Session\Store' not found error

enter image description here



via Chebli Mohamed

Summernote and Laravel add select on wysiwyg

wysiwyg editor

Is it possible to add select function in the wysiwyg editor? Instead of typing <select></select>in the code view.



via Chebli Mohamed

Add point datatype field in laravel 5.8 migration

I have to add point datatype for a postgres database field in laravel 5.8. I am using below code -

$table->point('coordinates')

It is adding geography datatype.

The same question has been put here as well.

How can I add point datatype.



via Chebli Mohamed

Laravel DOMPDF failed to open stream: No such file or directory

I am using barryvdh/laravel-dompdf and trying to save a pdf file . it gives me a error

 file_put_contents(core/storage/app/pdf/pdffile50.pdf): failed to open stream: No such file or directory

File is not created

    $pdf = PDF::loadView('invoice::pdf_generate', $data)->setOptions(['dpi' => 115, 'defaultMediaType' 
    => 'media', 'defaultFont' => 'sans-serif', 'isRemoteEnabled' => true])
     ->save('core/storage/app/pdf/pdffile'.$invoice->id.'.pdf');

Does any one why am I getting this error?

This error occurs while task scheduling with a command php artisan recurring:invoice



via Chebli Mohamed

Timezone is not changing in laravel

I want to change timezone but it is not working

I have changed timezone in config/app.php

My previous timezone was 

'timezone' => 'Asia/Kolkata',

and i changed it to 

'timezone' => 'UTC',

But it is not working, please help me.



via Chebli Mohamed

mardi 22 septembre 2020

How release versions of laravel product?

We have laravel product. Now it has become a huge product. Till now we were uploading our daily updates on the live server. But now we are going to release Beta Version and from now we want to upload on the server with proper process. I mean we should have a record of the version of the product and another documentation process.

Is there anything which laravel can provide us for this purpose?



via Chebli Mohamed

Laravel Multiple Select Old Value

i'm added multiple select box using bootstrap-select in create form everything goes very well but I've a problem in edit form .

I tried many way to get the old selected value but nothing works

Blade:

                                        <select class="selectpicker" name="students[]" data-style="select-with-transition" data-live-search="true" multiple title="Choose City" data-size="7">
                                        <option disabled> Multiple Options</option>
                                        @foreach($students as $student)
                                            <option value="" > </option>
                                        @endforeach
                                    </select>

Edit function:

 public function edit(Course $course)
{
    $students=Student::all();
    return view('course.edit',compact('course','students'));
}

Store Function:

public function store(Request $request)
{
    $request->validate([
        'name' => 'required',
    ]);
    $course = new Course;
    $course->name = $request->name;
    $course->teacher_id = $request->teacher_id;

    $course->save();
    $course->students()->sync($request->students);

    return redirect()->route('courses.index')
        ->with('success','Course created successfully.');
}

any idea to do this ??



via Chebli Mohamed

Missing required parameters for [Route: claim_card] [URI: admin/claim_card/{giftcard_id}/{layout_id}/{user_id}/{color_id}]. - Laravel

I am new to laravel and when created a route, this error is displayed. I am passing complete parameters and can't locate the error.

Here's the route:

Route::get('/admin/claim_card/{giftcard_id}/{layout_id}/{user_id}/{color_id}' , 'UserController@claim_card')->name('claim_card');

Here's the function:

public function claim_card($giftcard_id , $layout_id , $user_id , $color_id)
{
    $card = giftcard_codes::where([['is_active', '=' , 1], ['giftcard_id', '=' ,$giftcard_id], ['layout_id', '=' ,$layout_id]])->first();
    if ($card) {
        $user = User::where('id', $user_id)->first();
        $lay = point_prizes::where('id', $layout_id)->first();
        if ($user->points >= $lay->points) {
            $us['points'] = $user->points - $lay->points;
            $c['is_active'] = 0;
            $co['color_id'] = $color_id;
            $co['is_pending'] = 2;

            cliaim_prizes_transactions::where([['user_id' , $user_id] , ['giftcard_id' , $giftcard_id] , ['layout_id' , $layout_id]])->first()->update($co);

                    $al = new user_alerts();
                    $al->user_id = $user_id;
                    $al->alert = 'Successfully Claimed Giftcard';
                    $al->alert_main = $card->code;
                    $al->save();

                    redeem__requests::where([['giftcard_id' , $giftcard_id] , ['layout' , $layout_id] , ['user_id' , $user_id] , ['is_active' , 1]])->first()->update($c);
                    giftcard_codes::where([['is_active', 1], ['giftcard_id', $giftcard_id], ['layout_id', $layout_id]])->orderby('id', 'DESC')->first()->update($c);
                    return view('admin.redeem_requests' , ['data' => redeem__requests::where('is_active' , 1)->get() , 'alert' => 'Giftcard Given Successfully']);
        }
    }
    else {
        return view('admin.redeem_requests' , ['data' => redeem__requests::where('is_active' , 1)->get() , 'alert' => 'No Code Exists']);
    }
}

Here's the view(where I am passing these):

<a href="">

Any help would be appreciated.



via Chebli Mohamed

Searching for UTF-8 channels without UTF-8 letters in query

What is the best way to get non-utf8 results when slug contains UTF8 letters? (For example: When I type the slug "Zaidimai", select all from the database where like "Žaidimai" and "Zaidimai").

Current code:

$results = DB::table('channels') -> where([['name', 'like', '%' . $slug . '%'], ['status', '=', 'OK']]) -> orWhere([['slug', 'like', '%' . $slug . '%'], ['status', '=', 'OK']]) -> limit(3) -> get();

It works fine, but when I try to search for a channel by entering "Zaidimai" in the search bar, it doesn't show the channel I want (Žaidimai).



via Chebli Mohamed

lundi 21 septembre 2020

get correct data from array

i am trying to decode array. this is my array

array:4 [▼
  "_token" => "tgPAddbrf3hI5tBIQIGyFYe9Y5RpwCj3rpZG5uVf"
  "resident_id" => array:4 [▼
    117 => "117"
    114 => "114"
    116 => "116"
    118 => "118"
  ]
  "available" => array:1 [▼
    116 => "2020-09-22"
  ]
  "out_of_community" => array:1 [▼
    118 => "2020-09-22"
  ]
]

i am using foeach to get answer like

resident_id  available    out_of_community
116         "2020-09-22"  null
118           null        "2020-09-22"

is it possible from foreach. my code for it

foreach ($data as $key => $value) {
            $data['resident_id'] = $key;
            
            # code...
        }


via Chebli Mohamed

Laravel 5.7.5 API Request Json

I am using laravel API Authentication it is authenticating with api_token successfully as form-data. When I pass a data as Content_Type application/json. I am not receiving the Json data it shows empty array. How do I receive a JSON Request in the API? enter image description here

    public function create_invoice(Request $request) {       
    
    $data = $request->json()->all();
    }


via Chebli Mohamed

Laravel DB:raw with Union

I have the following querys which I need to unoin them but I'm getting the following error:

"message": "Method Illuminate\Support\Collection::getBindings does not exist."

The idea is that first query returns records grouped by month and the last query to union to first one, has the total values for each column grouped per month.

This is my expected output which is working correct the query in mysql:

enter image description here

SELECT USERS.ID AS ID, PROPERTIES.PROP_TYPE AS TIPO
,SUM(IF(MONTH(PROPERTIES.created_at) = 1, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as ENE
,SUM(IF(month(PROPERTIES.created_at) = 2, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS FEB
,SUM(IF(month(PROPERTIES.created_at) = 3, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as MAR
,SUM(IF(month(PROPERTIES.created_at) = 4, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS ABR
,SUM(IF(month(PROPERTIES.created_at) = 5, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS MAY
,SUM(IF(month(PROPERTIES.created_at) = 6, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUN
,SUM(IF(month(PROPERTIES.created_at) = 7, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUL
,SUM(IF(month(PROPERTIES.created_at) = 8, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS AGO
,SUM(IF(month(PROPERTIES.created_at) = 9, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as SEP
,SUM(IF(month(PROPERTIES.created_at) = 10, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as OCT
,SUM(IF(month(PROPERTIES.created_at) = 11, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as NOV
,SUM(IF(month(PROPERTIES.created_at) = 12, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as DIC
FROM PROPERTIES
LEFT JOIN USERS ON PROPERTIES.PROP_CAPPER_EMAIL = USERS.EMAIL_LOCAL_CRM
WHERE   USERS.ID = 755
GROUP BY PROPERTIES.PROP_TYPE, USERS.ID
UNION
SELECT USERS.ID AS ID, 'Total'
,SUM(IF(MONTH(PROPERTIES.created_at) = 1, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as ENE
,SUM(IF(month(PROPERTIES.created_at) = 2, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS FEB
,SUM(IF(month(PROPERTIES.created_at) = 3, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as MAR
,SUM(IF(month(PROPERTIES.created_at) = 4, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS ABR
,SUM(IF(month(PROPERTIES.created_at) = 5, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS MAY
,SUM(IF(month(PROPERTIES.created_at) = 6, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUN
,SUM(IF(month(PROPERTIES.created_at) = 7, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUL
,SUM(IF(month(PROPERTIES.created_at) = 8, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS AGO
,SUM(IF(month(PROPERTIES.created_at) = 9, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as SEP
,SUM(IF(month(PROPERTIES.created_at) = 10, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as OCT
,SUM(IF(month(PROPERTIES.created_at) = 11, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as NOV
,SUM(IF(month(PROPERTIES.created_at) = 12, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as DIC
FROM PROPERTIES
LEFT JOIN USERS ON PROPERTIES.PROP_CAPPER_EMAIL = USERS.EMAIL_LOCAL_CRM
WHERE   USERS.ID = 755
GROUP BY USERS.ID

This is the code:

public function exclusive_details (Request $request) {
        $exclusive_details = DB::table('properties')
                            ->leftjoin('users', 'properties.prop_capper_email', '=', 'users.email_local_crm')
                            ->select(DB::raw("users.id
                            ,properties.prop_type
                            ,SUM(IF(MONTH(properties.created_at) = 1, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as ENE
                            ,SUM(IF(month(properties.created_at) = 2, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) AS FEB
                            ,SUM(IF(month(properties.created_at) = 3, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as MAR
                            ,SUM(IF(month(properties.created_at) = 4, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) AS ABR
                            ,SUM(IF(month(properties.created_at) = 5, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) AS MAY
                            ,SUM(IF(month(properties.created_at) = 6, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUN
                            ,SUM(IF(month(properties.created_at) = 7, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUL
                            ,SUM(IF(month(properties.created_at) = 8, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) AS AGO
                            ,SUM(IF(month(properties.created_at) = 9, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as SEP
                            ,SUM(IF(month(properties.created_at) = 10, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as OCT
                            ,SUM(IF(month(properties.created_at) = 11, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as NOV
                            ,SUM(IF(month(properties.created_at) = 12, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as DIC
                            "))
                            ->where('users.id', $request['query']['id'])
                            ->groupBy('properties.prop_type', 'users.id')
                            ->orderBy('properties.prop_type', 'asc');

        $exclusive_details_total = DB::table('properties')
                            ->leftjoin('users', 'properties.prop_capper_email', '=', 'users.email_local_crm')
                            ->select(DB::raw("users.id
                            ,'TOTAL'
                            ,SUM(IF(MONTH(properties.created_at) = 1, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as ENE
                            ,SUM(IF(month(properties.created_at) = 2, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) AS FEB
                            ,SUM(IF(month(properties.created_at) = 3, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as MAR
                            ,SUM(IF(month(properties.created_at) = 4, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) AS ABR
                            ,SUM(IF(month(properties.created_at) = 5, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) AS MAY
                            ,SUM(IF(month(properties.created_at) = 6, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUN
                            ,SUM(IF(month(properties.created_at) = 7, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUL
                            ,SUM(IF(month(properties.created_at) = 8, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) AS AGO
                            ,SUM(IF(month(properties.created_at) = 9, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as SEP
                            ,SUM(IF(month(properties.created_at) = 10, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as OCT
                            ,SUM(IF(month(properties.created_at) = 11, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as NOV
                            ,SUM(IF(month(properties.created_at) = 12, properties.PROP_EXCLUSIVE = 'Exclusiva',0)) as DIC
                            "))
                            ->where('users.id', $request['query']['id'])
                            ->union($exclusive_details)
                            ->groupBy('users.id')
                            ->get();
        dump($exclusive_details);
        return response()->json($exclusive_details);
    }

How can I fix the union issue?

Regards



via Chebli Mohamed