eddy1992

eddy1992

Web developer intern at Experia Media

Hire Me

Member Since 3 Years Ago

Experience Points 21,730
Experience
Level
Lessons Completed 89
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

22 Oct
1 month ago

eddy1992 left a reply on Using Full TEXT Indexing For Text Field With %like%

Thank you so much @lostdreamer_nl for your time and response.

eddy1992 started a new conversation Using Full TEXT Indexing For Text Field With %like%

Hi, I have a table which has a text column for product names. Now the issue is that I was thinking to add indexing. So I was curious to know if I add FULL-TEXT indexing to that column then in such case, can I use %Like% and will that indexing help? Or do I have to use Match Function to see the benefit of the Full-Text indexing?

eddy1992 left a reply on Avoid Duplicate Entries While Using Insert Method

Thank you so much @tykus @lostdreamer_nl for your precious time and effort and teaching us every day. You guys are the best.

eddy1992 left a reply on Change Primary Key

@Snapey Thanks for your response. I wanted to make sure my primary key is product_id.

eddy1992 started a new conversation Avoid Duplicate Entries While Using Insert Method

Hi, I have a script which is selecting products from one table and will insert in a new table.

            $timeparts = explode(" ",microtime());
            $carbon = Carbon::now()->subMonths(2);
            $newdates = bcadd(($timeparts[0]*1000), bcmul($carbon->timestamp, 1000));
            
           
            
            DB::table('products1')
                ->orderBy('product_id')
                ->where('startdate', '>', $newdates)
                ->where('sticky', 0)
                ->chunk(100, function ($products) use ($bar) {
                    $array = json_decode( json_encode($products), true);
                   
                    DB::table('advertise')->insert($array);
                });

Now the problem is that this script stops with an error

Integrity constraint violation: 1062 Duplicate entry  for key 'PRIMARY'

How can I modify this script so that only unique products get added? Please assist.

eddy1992 started a new conversation Change Primary Key

Hi, I have a table named advertisements and its filled with data. I have an issue I want to change the primary key. Right now id is the primary key which is auto increment. I want the product_id to be the primary key.

id  int(10) unsigned Auto Increment  
product_id  int(11) NULL     

Please assist. How can I do this from migration?

18 Oct
1 month ago

eddy1992 left a reply on Optimizing Query Using Chunk

@D9705996 @MikeMacDowell @Borisu Thank you so much guys for your time and reply. You guys are the best :).

17 Oct
1 month ago

eddy1992 started a new conversation Optimizing Query Using Chunk

Hi, I have a snippet code which will take records from one table and add it to a new table. The problem with it is that it will use a lot of memory and it won't work as we have a lot of records.

The code snippet looks like this

        $timeparts = explode(" ",microtime());
    $carbon = Carbon::now()->subMonths(2);
    $newdates = bcadd(($timeparts[0]*1000), bcmul($carbon->timestamp, 1000));

    $products = DB::table('products1')->where('startdate', '>', $newdates)->get();
    
    $data = collect($products)->map(function($item){ 
        unset($item->multi_new);
        unset($item->subCategoryId);
        return (array) $item; 
    })->toArray(); 

    $add = DB::table('advertisements')->insert($data);

How can I improve this code by using chunks method? Please assist. Thank you.

12 Sep
3 months ago

eddy1992 started a new conversation Optimizing A Table For Faster Queries.

Hi I have a table named products and it has the following schema -:


product_id  int(11) unsigned Auto Increment  
product_name    varchar(60)  
product_price   int(35)  
product_Description mediumtext   
productNameArabic   mediumtext   
productNameEnglish  mediumtext   
productDescriptionArabic    mediumtext   
productDescriptionEnglish   mediumtext   
categories_category_id  int(11)  
subcat  int(11)  
oksubcat    enum('0','1') [0]    
lastupdatetime  varchar(60)  
countries_country_id    varchar(11)  
users_user_id   int(11)  
mainImage   varchar(60) [nopic.png]  
imagsticky  varchar(60) [0]  
imagthemb   varchar(60) [0]  
adthemb varchar(60) [0]  
adsimag varchar(60)  
startdate   varchar(60)  
likes   int(11) unsigned [0]     
comment int(11) unsigned [0]     
points  int(10) unsigned [0]     
lang    varchar(10) [aren]   
oklang  enum('0','1') [0]    
active  enum('0','1') [0]    
reasonOfReject  int(11) NULL     
rejected_at datetime NULL    
approved_at datetime NULL    
rejected_by varchar(255) NULL    
approved_by varchar(255) NULL    
status  enum('1','2','3') [1]    
action  enum('0','1') [0]    
hideadv enum('0','1') [0]    
sticky  enum('0','1') [0]    
msg enum('0','1','2','3','4','5','6','7','8','9','10','11') [0]  
deletes enum('0','1','2','3') [0]    
productAdvertiseUrl varchar(150)     
productAdvertisepoint   int(10) [0]  
isAd    enum('0','1') [1]    
isShowAddCommentAndLIkes    enum('0','1') [0]    
pointsads   int(10) [0]  
iSchowcat   enum('0','1','2','3') [0]    
subsubCategoryId    varchar(10)  
categoryAdvertiseTypeId varchar(5) [0]   
cityId  varchar(4)   
regionId    varchar(4)   
manfactureYear  varchar(4)   
km  varchar(10)  
furnishedTypeId varchar(10)  
numberOfRooms   int(11) NULL     
userDeviceLanguage  varchar(2)   
userDeviceModel varchar(10)  
userDeviceType  varchar(10)  
userIpAddress   varchar(30)  
userMacAddress  varchar(60)  
useradmin   int(11) [0]  
stopnot enum('0','1') [0]    
datesticky  date     
datedelete  date     
ip  varchar(20)  
ipedit  varchar(20)  
isorder int(11)  
newdate datetime     
report  varchar(2) [0]   
ad_delete_sticky    int(11)  
ad_active_sticky    int(11)  
clickType   enum('0','1','2','3','4','5','6','7','8','9','10','11') [0]  
sticky_all  enum('0','1') [0]    
companies   enum('0','1') [1]    
date_end_sticky date     
productMainImageNewSize varchar(60) [nopic.png]  
isMainVideo int(2) [0]   
isVideoMainImage    varchar(60) [0]  
testHintCar varchar(255)     
longitude   decimal(10,7)    
latitude    decimal(10,7)    
location    varchar(255)     
in_review   tinyint(1) [0]   
condition   varchar(255)     
cam_wifi    varchar(255)     
camera_wifi varchar(255)     
camears_mega    varchar(255)     
camera_zoom varchar(255)     
camera_guarantee    varchar(255)     
mobile_condition    varchar(255)     
mobile_storage  varchar(255)     
mobile_resolution   varchar(255)     
mobile_sim  varchar(255)     
mobile_guarantee    varchar(255)     
smarts_condition    varchar(255)     
smarts_wheels   varchar(255)     
smarts_remote   varchar(255)     
smarts_bluetooth    varchar(255)     
smarts_charging varchar(255)     
smarts_lights   varchar(255)     
smarts_water    varchar(255)     
smarts_guarantee    varchar(255)     
lands_facades   varchar(255)     
lands-area  int(255) [0]     
lands_maps  varchar(255)     
lands_foot  int(255) [0]     
lands_sorting   varchar(255)     
car_plate_type  varchar(255)     
car_plate_condition varchar(255)     
camera_bluetooth    varchar(255)     
lands_payment   varchar(255)     
motorcycles_condition   varchar(255)     
motorcycles_gear    varchar(255)     
motorcycles_engine_size varchar(255)     
motorcycles_engine_power    varchar(255)     
manfactureYearId    varchar(255)     
animals_age varchar(255)     
air_conditioner_condition   varchar(255)     
air_conditioner_type    varchar(255)     
air_conditioner_size    varchar(255)     
air_conditioner_guarantee   varchar(255)     
animal_age  varchar(255)     
animal_count    varchar(255)     
animal_weight   varchar(255)     
other_animal_age    varchar(255)     
other_animal_count  varchar(255)     
other_animal_weight varchar(255)     
heavy_condition varchar(255)     
car_condition   varchar(255)     
cars_guarantee  varchar(255)     
electronics_condition   varchar(255)     
electronics_guarantee   varchar(255)     
furniture_condition varchar(255)     
trips_condition varchar(255)     
offshore_condition  varchar(255)     
spare_condition varchar(255)     
spare_quality   varchar(255)     
foods_delivery  varchar(255)     
foods_time  varchar(255)     
birds_count varchar(255)     
birds_age   varchar(255)     
birds_sex   varchar(255)     
sports_condition    varchar(255)     
jobs_sex    varchar(255)     
jobs_experience varchar(255)     
jobs_qualification  varchar(255)     
jobs_salary varchar(255)     
jobs_nationality    varchar(255)

Now this table is very slow as it has many products imagine products from the year 2013 till present. Now to improve performance I thought why not move to a new table having the same schema or shall I distribute to a different table having a different status of products like right now we have approved, rejected, requested, deleted. At the moment we are saving all the status in this table only.

Now I wanted to know if I move to different tables for different status ie ( approved, rejected, requested, deleted ) will it improve performance when I get the products in an api? Does this abstraction make sense?

24 Jun
5 months ago

eddy1992 started a new conversation How To Decode JWT Tokens ?

Hi I am planning to user AWS api gateway and aws user pool , I want to know if we have any package related to decode JWT tokens in laravel 5.2? Please give suggestions. Thank you.

25 May
6 months ago

eddy1992 started a new conversation Git Status Show Bad Object Head.

I did git status and I am seeing this error. How can I solve this please assist if anyone has faced this issue before?

    git status
    fatal: bad object HEAD
    git fsck --full
    
    error: HEAD: invalid sha1 pointer 7b7cee7ecd496aa6a38d641a2a83480e4f68983d
    error: refs/heads/master: invalid sha1 pointer 7b7cee7ecd496aa6a38d641a2a83480e4f68983d
    
    error: HEAD: invalid reflog entry 7b7cee7ecd496aa6a38d641a2a83480e4f68983d
    error: refs/heads/master: invalid reflog entry 7b7cee7ecd496aa6a38d641a2a83480e4f68983d
    dangling blob f00de448e9864e419727a17ea2438514e1d10b1f
    dangling blob c221f6bb2006ff58d8207e41527a1f3cd0bdf485
    dangling blob e665c10c7fc97661dd3bd980b11ebeeab1649409
    dangling blob 716af2645775c1594629e84463947c413e8b60c0
    dangling commit dfaefd2f623dc3e2ecdfefe881f56cf4b3bc75c4
    dangling blob aabb3d2087f289f1d1c01f13fbf897fb2436d0a7
    dangling blob 3ad27c5164f7c03814cfdcce4a451be6926c4e5a
    dangling commit f5d9fd4d24a3509fc5a53ca426d10541c94f8b79
    dangling blob 4ef15c7ebb44c156dc01b881d8899a6f360464de

11 May
7 months ago

eddy1992 started a new conversation Secure The Apis From Hackers.

Hi, guys I have some restful API's which are connected to two apps the ios and android. I have no security on them. I want to secure the API's now. The API's are build on Laravel 5.2. I want to know what options do I have? Please assist.

13 Apr
8 months ago

eddy1992 started a new conversation Sql Injection

Hi, I have a project which is running an old version of PHP and MySQL. I am using queries like this

mysql_query("select * from user_favorites1 where users_id='$user_phone' AND products_id='$products_id' LIMIT 0,1");
$count=mysql_num_rows($ip_sql);

$sql_in = "insert into user_favorites1 (users_id,products_id,user_country_code,lastupdatetime,isAd) values ('$user_phone','$products_id','$user_country_code','$mss','$isAd')";
mysql_query($sql_in);
$result = array("status" => 0);
echo json_encode($result);

What will be the way to prevent SQL injection in the current code base rather than upgrading the whole code. Please assist.

07 Mar
9 months ago

eddy1992 started a new conversation Saving Json In A Column And Searching Back.

Hi, I am using Laravel 5.2 and using Maria DB and I know I could create a column varchar and store JSON in it. Now I wanted to know if I could search them back also? Is that possible in Laravel 5.2. I found that in Laravel 5.3 and Mysql 5.7 we have JSON but I do not have that privilige. Please assist if there is a way.

10 Feb
10 months ago

eddy1992 started a new conversation WhereBetween Passing Value And Null

I have an eloquent query and I am passing a value and null in it. So for example if I have an area column and I have two variables $to and $from.

example $from = 10 $to= ""

    $from = 10;
    $to = "";  
    Product::whereBetween('area', [$from, $to])->get();

my question is that is this okay , will this work ? If no then what shall I do if I want to search from 10 to infinity ?

please assist. Thank you.

06 Feb
10 months ago

eddy1992 left a reply on WhereBetween Passing Array

@bobbybouwmann Okay thank you so much for your time and effort. :)

eddy1992 left a reply on WhereBetween Passing Array

@bobbybouwmann Thank you so much for your response and answer, I am curious to know is there a way we could achieve this without the foreach ?

eddy1992 started a new conversation WhereBetween Passing Array

Hi I have query where I want to pass an array to whereBetween query.

for example I have an array which looks like this

Array
(
    [product_id] => Array
        (
            [0] => 31337
            [1] => 31366
        )

    [lands] => Array
        (
            [0] => 12
            [1] => 23
        )

)

Now I want search those product_id which are between [0] => 31337 and [1] => 31366 and same goes to land I want to find the lands where Between [0] => 1 and [1] => 23

now say I have a variable $filters which has the this above array in it and I pass it like this to the query like below.

public function scopeDynamicInBetweenFilter($query, $filters)
    {
        if(!empty($filters)){
            return $query->whereBetween($filters);
        }
        return $query;
    }

It gives me an error

Type error: Too few arguments to function Illuminate\Database\Query\Builder::whereBetween(), 1 passed and at least 2 expected

it does like this at Builder->whereBetween(array('product_id' => array('31337', '31366'), 'lands' => array('12', '23')))

please tell me what could be done to achieve this. Please assist

23 Jan
10 months ago

eddy1992 started a new conversation Schema Has Returning Empty

Hi I am facing a weird issue where I added a new column named condition in table named products1. Now the issue is that I used to check if the column exist or not using

$filterId = "condition"
 Schema::hasColumn('products1', $filterId);

Now I added a new column named condition and its returning me false and I am 100% sure that the column exists.

Any idea why this would happen. Please assist. Thank you.

11 Jan
11 months ago

eddy1992 started a new conversation 'Illuminate\Database\QueryException SQLSTATE[42000]:

Hi I am checking on new relic and I see some errors coming and it shows like this

Exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'offset 0' at line 1 (SQL: select * from `products1` where `categories_category_id` = 198 and `subcat` = 231 and `categoryAdvertiseTypeId` = 0 and MATCH (product_name, productNameArabic, productNameEnglish, product_Description, productDescriptionArabic, productDescriptionEnglish) AGAINST ( تركيب خيم وعنن وبيوت الشعر IN NATURAL LANGUAGE MODE) and `startdate` > 1510401145890 and `active` = 0 order by `startdate` desc offset 0)' in /home/apimzad/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:729

any idea what I might be doing wrong

my query

public function searchAdsInProducts1($data)
    {
        $searchString = $data->get('searchStr');
        $categoryId = $data->get('productId');//categories_category_id ie. car, property etc.
        $subCategoryIds = $data->get('subCategoryId');//subcat
        $subSubCategoryIds = $data->get('subsubCategoryId');//subsubCategoryId
        $productsLanguage = $data->get('productsLang');//lang
        $numberPerPage = $data->get('numberperpage');

        $manfactureYearFrom = $data->get('manfactureYearFrom');
        $manfactureYearTo = $data->get('manfactureYearTo');
        $kmFrom = $data->get('kmFrom');
        $kmTo = $data->get('kmTo');
        $priceFrom = $data->get('priceFrom');
        $priceTo = $data->get('priceTo');
        $regionId = $data->get('regionId');
        $furnishedTypeId = $data->get('furnishedTypeId');
        $numberOfRoomsFrom = $data->get('numberOfRoomsFrom');
        $numberOfRoomsTo = $data->get('numberOfRoomsTo');
        $cityId = $data->get('cityId');
        $categoryAdvertiseTypeId = $data->get('categoryAdvertiseTypeId');
        $orderBy = $this->decideOrderBy($data);
        $time = $this->decideTime($data);

        $page = $data->get('page', 1);

        // Items per page (maybe put this in a config file?)
        // $perPage = $data->get('numberperpage');
        $perPage = $data->get('numberperpage');
        // Calculate the offset based on the current page.
        $offset = ($page * $perPage) - $perPage;


        if(($data->get('page') == 1)){

            $sticky = Product::with(['category', 'getCity', 'getRegion', 'getVideo'])
                    ->categoriesCategoryId($categoryId)
                    // ->where('companies', 1)
                    ->where('sticky', 1)
                    // ->subSubCategory($subSubCategoryIds)
                    // ->subCat($subCategoryIds)
                    ->categoryAdvertiseTypeId($categoryAdvertiseTypeId)
                    // ->regionId($regionId)
                    // ->furnishedTypeId($furnishedTypeId)
                    // ->cityId($cityId)
                    // ->searchString($searchString)
                    // ->km($kmFrom, $kmTo)
                    // ->price($priceFrom, $priceTo)
                    // ->numberOfRooms($numberOfRoomsFrom, $numberOfRoomsTo)
                    // ->manufactureYear($manfactureYearFrom, $manfactureYearTo)
                    // ->language($productsLanguage)
                    // ->orderBy('product_id', 'desc')
                    // ->active()//
                    // ->inReview()//for new advertisement flow.
                    ->lastOneMonth($categoryId)
                    ->orderByRaw('RAND()')
                    ->take(30)
                    ->get();
        }

        if(($data->get('page') == 1) AND ($categoryId != 0)){
            if(!$sticky->isEmpty()){
                $countOfStarAds = $sticky->count();

                $perPage = $data->get('numberperpage') - $countOfStarAds;
            }
        }


        $ads = Product::with(['category', 'getCity', 'getRegion', 'getVideo'])
                ->categoriesCategoryId($categoryId)
                ->subSubCategory($subSubCategoryIds)
                ->subCat($subCategoryIds)
                ->categoryAdvertiseTypeId($categoryAdvertiseTypeId)
                ->regionId($regionId)
                ->furnishedTypeId($furnishedTypeId)
                ->cityId($cityId)
                ->searchString($searchString, $categoryId)
                ->km($kmFrom, $kmTo)
                ->price($priceFrom, $priceTo)
                ->numberOfRooms($numberOfRoomsFrom, $numberOfRoomsTo)
                ->manufactureYear($manfactureYearFrom, $manfactureYearTo)
                ->lastTwoMonths($categoryId)
                ->time($time)
                ->language($productsLanguage)
                ->orderBy($orderBy, 'desc')
                ->active()//
                // ->inReview()////for new advertisement flow.
                ->skip($offset)//remove if not working
                ->take($perPage)//remove if not working
                // ->paginate(50, ['*'], 'page', $page);
                ->get();

        if($data->get('isAdsSupported') == 'true'){
            $paidAds = $this->getPaidAds($data);
        }

        if(($data->get('page') == 1) AND ($categoryId != 0)) {
            // $data = $ads;
            $data = $sticky->merge($ads);
        }else{
            $data = $ads;
        }

        return ['ads' => $data, 'paidAds' => $paidAds];
    }

please tell me what I am doing

05 Jan
11 months ago

eddy1992 started a new conversation SSL Operation Failed

Hi guys I have code to which is supposed to send ios push messages but it is giving me an error do not know why ?

my code

$streamContextCreate = stream_context_create();
            
            stream_context_set_option($streamContextCreate, 'ssl', 'local_cert', '/home/devmzad/public_html/public/ios/MzadDevCertificates.pem');
            
            $fp = stream_socket_client(
                'ssl://gateway.push.apple.com:2195', $err,
                $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $streamContextCreate);
            echo "<pre>";
            print_r($fp); //gives error here.
            die;

the error

stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:14094438:SSL routines:SSL3_READ_BYTES:tlsv1 alert internal error

Guys would appreciate if someone could help me with please that why this is giving this weird error ?

22 Dec
11 months ago

eddy1992 started a new conversation My Api Is Slow And Facing 504 Error Sometimes.

Hi guys I have an api and that api purpose is it to fetch all the products. So this api is giving us some trouble as its slow on live and sometimes gets stuck and gives us 504 time out error. It has become complete nightmare why it happens and I am not able to figure that out, hopefully some one could just see and tell what might be the reason for the slowness.

so I have a controller GetCategoryDataApiController this has the method named getCategoryData this will get the post data and process further.


<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;

use DB;
use App\User;
use App\City;
use App\Product;
use App\Category;
use App\Http\Requests;
use App\Product_images1;
use App\Http\Controllers\Controller2;
use App\Http\Traits\ProductsOneTableLangTrait;
use App\Http\Traits\ProductOneImageUtilityTrait;
use App\Http\Traits\ProductOneUtilityTrait;
use App\Http\Traits\UtilitiesTrait;

class GetCategoryDataApiController extends Controller2
{   
    /**
     * This trait will handle all the 
     * data that will be filtered 
     * on the basis of language
     */
    use ProductsOneTableLangTrait, 
    ProductOneImageUtilityTrait, 
    ProductOneUtilityTrait,
    UtilitiesTrait;


    /**
     * the website url
     * @var string
     */
    protected $website;


    /**
     * device language the user pass
     * @var string
     */
    protected $deviceLanguage;


    /**
     * products Language the use pass
     * @var string
     */
    protected $prodLanguage;



    protected $lastupdatetime;


    protected $countOfRow;

    /**
     * get the category data  
     * @param  Request $request 
     * @return json we would get the ads from the products1 table.
     */
    public function getCategoryData(Request $request)
    {   
        
        $data = $request->json();
        $this->setLanguage($data);

        $adsFound = $this->searchAdsInProducts1($data); // this would get all the products.
        $ads = $this->createJsonFormatForGetCategoryData($adsFound['ads'], $this->deviceLanguage);
        return $this->mergePaidAdsWithNormalAds($ads, $adsFound['paidAds']);
    }   


    /**
     * set language so we could refer it 
     * in the code whenever needed
     * @param $data this is the request param
     */
    public function setLanguage($data)
    {   
        $this->website = config('app.url');
        $this->deviceLanguage = $data->get('userDeviceLanguage');
        $this->prodLanguage = $data->get('productsLang');
        $this->countOfRow = $data->get('countOfRow');
        $this->lastupdatetime = ($data->get('lastupdatetime')) 
        ?  $data->get('lastupdatetime')
        :  $this->lastUpdateTime();
    }

    
    public function createJsonFormatForGetCategoryData($data, $lang)
    {
        if(!$data->isEmpty()){

            $index = 0;
            foreach($data as $key => $item) {

                $categoryName = $this->getCategoryNameOnBasisOfLang($item->categories_category_id, $lang);
                $subCategoryName = $this->getCategoryNameOnBasisOfLang($item->subcat, $lang);
                $subsubCategoryName = $this->getCategoryNameOnBasisOfLang($item->subsubCategoryId, $lang);

                $cityName = $this->getCityNameDependLanguage($lang, $item);
                $advertiseName = Category::getAdvertiseType($item->categoryAdvertiseTypeId, $lang);
                $furnishedTypeName = $this->getFurnishedNameDependLanguage($lang, $item);
                // $properties = $this->addPropertiesArray($categoryName,$subCategoryName,$advertiseName,$item->manfactureYear,$furnishedTypeName,$lang,$item);
                $manfactureYearId = $this->getManufactureIdFromYear($item->manfactureYear);
                $properties = $this->addProperties($item,$advertiseName,$subsubCategoryName,$subCategoryName,$furnishedTypeName,$manfactureYearId,$lang);

                
                $mainImage = $this->getProductMainImage($item, $this->website);

                $products[] = [
                    'dateOfAdvertise'          => $item->startdate,
                    'isAd'                     => $item->isAd,
                    'isShowAddCommentAndLikes' => $item->isShowAddCommentAndLIkes,
                    'productId'               =>  "$item->product_id",
                    'categoryAdvertiseTypeId'  => $item->categoryAdvertiseTypeId,
                    'productName'              => $this->setProductNameUsingLang($item, $this->prodLanguage),
                    'productNameEnglish'       => $item->productNameEnglish,
                    'productNameArabic'        => $item->productNameArabic,
                    'productPrice'             => "$item->product_price",
                    'productDescription'       => $item->product_Description,
                    'productDescriptionEnglish'=> $item->productDescriptionEnglish,
                    'productDescriptionArabic' => $item->productDescriptionArabic,
                    'categoryId'               => "$item->categories_category_id",
                    'categoryName'             => $categoryName,
                    'subCategoryId'            => "$item->subcat",
                    'subCategoryName'          => $subCategoryName,
                    'subsubCategoryId'         => $item->subsubCategoryId,
                    'subsubCategoryName'       => $subsubCategoryName,
                    'categoryAdvertiseTypeName'=> $advertiseName,
                    'cityId'                   => $item->cityId,
                    'cityName'                 => $cityName,
                    'regionId'                 => $item->regionId,
                    'regionName'               => $this->getRegionNameDependLanguage($lang, $item),
                    'manfactureYear'           => $this->convertDateToTheLang($lang, $item->manfactureYear),
                    'km'                       => $item->km,
                    'furnishedTypeId'          => $item->furnishedTypeId,
                    'furnishedTypeName'        => $furnishedTypeName,
                    'numberOfRooms'            => $item->numberOfRooms,
                    'commentCount'             => "$item->comment",
                    'likeCount'                => $this->getUserLikes($data, $item),
                    'productAdvertiseUrl'      => $item->productAdvertiseUrl,
                    'isCompany'                => $item->companies,
                    'clickType'                => $item->clickType,
                    'productMainImage'         => $mainImage,
                    'userCountryCode'          => $item->countries_country_id,
                    'userNumber'               => "$item->users_user_id",
                    'userName'                 => User::findUserNameBasedOnNumber($item->users_user_id, $this->deviceLanguage),
                    'userEmail'                => User::findEmailBasedOnNumber($item->users_user_id),
                    'userPhoto'                => User::findUserPhotoBasedOnNumber($item->users_user_id),
                    'userSmallDescription'     => User::getUserInfo($item->users_user_id),
                    'userProfileLink'          => $this->profileLink($item, $this->website),
                    'productUrl'               => $this->productUrl($item, $this->website),
                    'productShareImage'        => $this->productShareImage($item, $this->website),
                    'advertiseTimeFormatted'   => $this->getAdvertiseTimeFormatted($item, $lang),
                    'numberOfViews'            => "$item->points",
                    'lang'                     => $item->lang,
                    'properties'               => $properties,
                    'productImages'            => $this->getProductImages($item, $this->website),
                    'productMainImageNewSize'  => $mainImage,
                    'productAttachments'       => $this->getProdAttachments($item, $this->website),
                    'isMainVideo'              => $this->setIsMainVideo($mainImage, $item),
                    'mainAttachment'           => $mainImage,
                    'manfactureYearId'         => $manfactureYearId,
                    'longitude'                => $item->longitude,
                    'latitude'                 => $item->latitude,
                    'location'                 => $item->location
                ];
            }
            $productInfo['lastupdatetime'] = "$this->lastupdatetime";
            $productInfo['products'] = $products;

            return $productInfo;
        }

        return [
            'lastupdatetime' => "$this->lastupdatetime",
            'products' => []
        ];
    }

    public function mergePaidAdsWithNormalAds($ads, $paidAds)
    {   
        $key = ($this->countOfRow * 4) - ((0 * ($this->countOfRow - 1)) + $this->countOfRow);
        $countOfAds = count($ads['products']);
        if($key < $countOfAds){
            $ads['products'][$key] = $paidAds;
            return $ads;
        }else{
            return $ads;
        }
    }
}



Now $adsFound = $this->searchAdsInProducts1($data); this would fetch the records from the table using eloquent. In this method we are just fetching using the query scope and merging two record sets.

/**
     * we would search the products 1 table
     * with all the request params posted
     * we would query only when the request 
     * params are passed.
     * @param  object $data This is the request param
     * @return eloquent collection
     */
    public function searchAdsInProducts1($data)
    {   
        $searchString = $data->get('searchStr');
        $categoryId = $data->get('productId');//categories_category_id ie. car, property etc.
        $subCategoryIds = $data->get('subCategoryId');//subcat
        $subSubCategoryIds = $data->get('subsubCategoryId');//subsubCategoryId
        $productsLanguage = $data->get('productsLang');//lang
        $numberPerPage = $data->get('numberperpage');

        $manfactureYearFrom = $data->get('manfactureYearFrom');
        $manfactureYearTo = $data->get('manfactureYearTo');
        $kmFrom = $data->get('kmFrom');
        $kmTo = $data->get('kmTo');
        $priceFrom = $data->get('priceFrom');
        $priceTo = $data->get('priceTo');
        $regionId = $data->get('regionId');
        $furnishedTypeId = $data->get('furnishedTypeId');
        $numberOfRoomsFrom = $data->get('numberOfRoomsFrom');
        $numberOfRoomsTo = $data->get('numberOfRoomsTo');
        $cityId = $data->get('cityId');
        $categoryAdvertiseTypeId = $data->get('categoryAdvertiseTypeId');
        $orderBy = $this->decideOrderBy($data);
        $time = $this->decideTime($data);

        $page = $data->get('page', 1);

        // Items per page (maybe put this in a config file?)
        $perPage = 50; 

        // Calculate the offset based on the current page.
        $offset = ($page * $perPage) - $perPage;

        if(($data->get('page') == 1)){

            $sticky = Product::categoriesCategoryId($categoryId)
                    // ->where('companies', 1)
                    ->where('sticky', 1)
                    // ->subSubCategory($subSubCategoryIds)
                    // ->subCat($subCategoryIds)
                    ->categoryAdvertiseTypeId($categoryAdvertiseTypeId)
                    
                    ->orderBy('product_id', 'desc')
                    ->take(50)
                    ->get();
        }
        
        $ads = Product::categoriesCategoryId($categoryId)
                ->subSubCategory($subSubCategoryIds)
                ->subCat($subCategoryIds)
                ->categoryAdvertiseTypeId($categoryAdvertiseTypeId)
                ->regionId($regionId)
                ->furnishedTypeId($furnishedTypeId)
                ->cityId($cityId)
                ->searchString($searchString, $categoryId)
                ->km($kmFrom, $kmTo)
                ->price($priceFrom, $priceTo)
                ->numberOfRooms($numberOfRoomsFrom, $numberOfRoomsTo)
                ->manufactureYear($manfactureYearFrom, $manfactureYearTo)
                // ->lastTwoMonths($categoryId)
                ->time($time)
                ->language($productsLanguage)
                ->orderBy($orderBy, 'desc')
                ->skip($offset)//remove if not working
                ->take($perPage)//remove if not working
                // ->paginate(50, ['*'], 'page', $page);
                ->get();

        if($data->get('isAdsSupported') == 'true'){
            $paidAds = $this->getPaidAds($data);
        }

        if(($data->get('page') == 1) AND ($categoryId != 0)) {
            // $data = $ads;
            $data = $sticky->merge($ads);
        }else{
            $data = $ads;
        }

        return ['ads' => $data, 'paidAds' => $paidAds];
    }

This all what is happening. I would appreciate your views in how I could improve this and then improve performance , or if you feel there is something suspicious then please let me know. Thank you. Please assist.

eddy1992 left a reply on Pagination For Api.

Thank you so much @bobbybouwmann , I think the issue is somewhere else for the performance.

19 Dec
11 months ago

eddy1992 started a new conversation Search Columns Using % Like %

Hi guys I have a question , If I had to search multiple columns using eloquent query scope how will I do it . The below elquent query giving me less results when searching. Is this correct to search a string in columns in a table. Please assist.

/**
     * query scope for search string
     * @param  $query
     * @param  String $searchString 
     * @return 
     */
    public function scopeSearchString($query, $searchString)
    {   
        if(!empty($searchString)){
            return $query->where('product_name', 'like', '%'.$searchString.'%')
                    ->orWhere('product_Description', 'like', '%'.$searchString.'%')
                    ->orWhere('users_user_id', 'like', '%'.$searchString.'%')
                    ->orWhere('productNameArabic', 'like', '%'.$searchString.'%')
                    ->orWhere('productNameEnglish', 'like', '%'.$searchString.'%')
                    ->orWhere('productDescriptionArabic', 'like', '%'.$searchString.'%')
                    ->orWhere('productDescriptionEnglish', 'like', '%'.$searchString.'%');
        }
        return $query;
    }

17 Dec
11 months ago

eddy1992 left a reply on Pagination For Api.

Hi @bobbybouwmann wow thanks for that answer. It would be really helpful if you could provide me an example. I think the second options seems perfect for me. Thank you so much.

eddy1992 started a new conversation Pagination For Api.

Hi guys I have two queries that would fetch records for me but I am using laravel paginator and I feel its making it slow, I am doing this query for api

/**
     * we would search the products 1 table
     * with all the request params posted
     * we would query only when the request 
     * params are passed.
     * @param  object $data This is the request param
     * @return eloquent collection
     */
    public function searchAdsInProducts1($data)
    {   
        $searchString = $data->get('searchStr');
        $categoryId = $data->get('productId');//categories_category_id ie. car, property etc.
        $subCategoryIds = $data->get('subCategoryId');//subcat
        $subSubCategoryIds = $data->get('subsubCategoryId');//subsubCategoryId
        $productsLanguage = $data->get('productsLang');//lang
        $page = $data->get('page');
        $numberPerPage = $data->get('numberperpage');

        $manfactureYearFrom = $data->get('manfactureYearFrom');
        $manfactureYearTo = $data->get('manfactureYearTo');
        $kmFrom = $data->get('kmFrom');
        $kmTo = $data->get('kmTo');
        $priceFrom = $data->get('priceFrom');
        $priceTo = $data->get('priceTo');
        $regionId = $data->get('regionId');
        $furnishedTypeId = $data->get('furnishedTypeId');
        $numberOfRoomsFrom = $data->get('numberOfRoomsFrom');
        $numberOfRoomsTo = $data->get('numberOfRoomsTo');
        $cityId = $data->get('cityId');
        $categoryAdvertiseTypeId = $data->get('categoryAdvertiseTypeId');
        $orderBy = $this->decideOrderBy($data);
        $time = $this->decideTime($data);

        if(($data->get('page') == 1) AND ($categoryId != 0)){

            $sticky = Product::categoriesCategoryId($categoryId)
                    ->where('companies', 1)
                    ->where('sticky', 1)
                    // ->subSubCategory($subSubCategoryIds)
                    // ->subCat($subCategoryIds)
                    ->categoryAdvertiseTypeId($categoryAdvertiseTypeId)
                    ->regionId($regionId)
                    ->furnishedTypeId($furnishedTypeId)
                    ->cityId($cityId)
                    // ->searchString($searchString)
                    ->km($kmFrom, $kmTo)
                    ->price($priceFrom, $priceTo)
                    ->numberOfRooms($numberOfRoomsFrom, $numberOfRoomsTo)
                    ->manufactureYear($manfactureYearFrom, $manfactureYearTo)
                    // ->language($productsLanguage)
                    ->orderBy('product_id', 'desc')
                    ->take(50)
                    ->get();
        }

        $ads = Product::categoriesCategoryId($categoryId)
                ->subSubCategory($subSubCategoryIds)
                ->subCat($subCategoryIds)
                ->categoryAdvertiseTypeId($categoryAdvertiseTypeId)
                ->regionId($regionId)
                ->furnishedTypeId($furnishedTypeId)
                ->cityId($cityId)
                ->searchString($searchString)
                ->km($kmFrom, $kmTo)
                ->price($priceFrom, $priceTo)
                ->numberOfRooms($numberOfRoomsFrom, $numberOfRoomsTo)
                ->manufactureYear($manfactureYearFrom, $manfactureYearTo)
                ->lastTwoMonths($categoryId)
                ->time($time)
                ->language($productsLanguage)
                ->orderBy($orderBy, 'desc')
                ->paginate(50, ['*'], 'page', $page);

        if($data->get('isAdsSupported') == 'true'){
            $paidAds = $this->getPaidAds($data);
        }

        if(($data->get('page') == 1) AND ($categoryId != 0)) {
            // $data = $ads;
            $data = $sticky->merge($ads);
        }else{
            $data = $ads;
        }

        return ['ads' => $data, 'paidAds' => $paidAds];
    }

When I see db log query it does SELECT count(*) as aggregate

Now I have million records and it would do count *, I feel this would make it slow, is there any other alternative to this for api ? Please suggest thank you.

16 Dec
1 year ago

eddy1992 left a reply on Search On The Last Two Months Records

@Snapey If I do recent() in the first then it would first search only in the scope of last month, and if do in the last then it would do something else right ?

eddy1992 left a reply on Search On The Last Two Months Records

@Snapey Thank you so much for your answer.

eddy1992 left a reply on Search On The Last Two Months Records

@Snapey thanks for you reply , so doing a simple where would do the trick ? so it would search from all the records when done with where date = 2 months before from now ?

eddy1992 started a new conversation Search On The Last Two Months Records

Hi I have a situation where I have millions of records in a table and I dont want to search the whole record set all times. Imagine I have a products table and I have 1 million products of last 5 years and to search something like finding product name I have to search the whole records, can I do something like search only the last two months records. So that the performance improves. If yes how will I do it using eloquent ?

please assist.

13 Nov
1 year ago

eddy1992 left a reply on Having Condition In A Laravel Eloquent Query.

@tykus Thank you so much for your reply but I wanted to know whether I could user sortBy() to achieve this ?

eddy1992 started a new conversation Having Condition In A Laravel Eloquent Query.

Hi I have an eloquent query and the table I am querying contains a column named active. So active could be 1 or 0. Now I am querying all the records from the table, that means I have all the records which may have active = 1 or active = 0. Now what I want to do is that I want to show or get the active = 1 records first then the those records which have active = 0.

//now Imagine we get all the records from this query so the $allRecords variable has 
//all the records which are active and not active.
$allRecords = Product::where('city', 'New York')->get();

//Now I want to sequence or reorder the collection where I want to show the active=1 first then active=0.

please assist.

25 Oct
1 year ago

eddy1992 started a new conversation Bind List Item Array Vue Data To Input Value In A Form

Hi I have a form and I have a input field in which I have a vue event which allows to take some values and add it to a data a object in the vue js, but I am not able to bind this vue data property to the input value so I would get back when the form is submitted.

My input

<div class="col-md-4">
   <ul>
      <li v-for="item in filterListValueEnArray">
         @{{ item }}
         <button @click.prevent="removeFilterEn(filterListValueEn)">remove</button>
      </li>
   </ul>
   <input type="text" v-model="filterListValueEn" @keydown.enter.prevent="addFilterValEn(filterListValueEn)" name="array" v-bind:value="filterListValueEnArray" class="form-control">
</div>

vue js code

        new Vue({
            el: '#advFilter',

            data: {
                selectFilterType: '',
                
                filterListValueEn: '',
                filterListValueEnArray: [],
                filterListValueAr: '',
                filterListValueArArray: [],
            },

            methods: {
                addFilterValEn: function(filterListValueEn) {
                    this.filterListValueEnArray.push(filterListValueEn);
                    this.filterListValueEn = '';

                },
                addFilterValAr: function(filterListValueAr) {
                    this.filterListValueArArray.push(filterListValueAr);
                    this.filterListValueAr = '';    
                },
                removeFilterAr: function(filterListValueAr) {
                    this.filterListValueArArray.pop(filterListValueAr)
                },
                removeFilterEn: function(filterListValueEn) {
                    this.filterListValueEnArray.pop(filterListValueEn)
                }
            }
        });

I want to bind the filterListValueEnArray in the value of the text field but I dont get back anything when I do

$request->all();

Please assist

29 Sep
1 year ago

eddy1992 left a reply on Laravel Db::raw Query For The Query Scope.

@36864 thank you for you response please check I have edited my question

eddy1992 started a new conversation Laravel Db::raw Query For The Query Scope.

Hi I have a query scope in laravel and I have a column named km which is varchar. Now I want to write a raw query scope for it. The problem is it wont search for the varchar. So need to cast km to unsigned.

    public function scopeKm($query, $kmFrom, $kmTo)
    {   
        $kmFrom = (int)$kmFrom;
        $kmFrom = (int)$kmTo;

        if((count($kmFrom) > 0) && count($kmTo) > 0){ 

            return $query->whereBetween('km', [$kmFrom, $kmTo]);   
        }
        return $query;
    }

I want to write the db raw query for the above in which I cast the km column to unsigned in the raw query.

eddy1992 left a reply on WhereBetween() Eloquent Returning Wrong Results

@ChristophHarms thank you for your reply. Even If I am trying to pass integer same issue.

eddy1992 started a new conversation WhereBetween() Eloquent Returning Wrong Results

Hi I have a eloquent query and I am using query scope. I have a km column in my table and I am passing kmFrom and KmTo values as post data. Now I am doing a eloquent whereBetween and its returning wrong results when I search for km.

For example if I pass kmFrom = 1000 and kmTo = 2000. Its giving me results which are not in between these two values.

Eloquent

Product::categoriesCategoryId($categoryId)
            ->km($kmFrom, $kmTo)->get();

Query Scope for the km -:

public function scopeKm($query, $kmFrom, $kmTo)
    {   
        if(($kmFrom) && ($kmTo)){
            return $query->whereBetween('km', ["$kmFrom", "$kmTo"]);   
        }
        return $query;
    }

Please assist

24 Sep
1 year ago

eddy1992 started a new conversation Laravel Not Returning Request

I am trying to post this json http://jsoneditoronline.org/?id=4d930c11daaf8cd8bb6df6edbc446a1e object with base 64 and its returning empty array when I do $request->all();

31 Aug
1 year ago

eddy1992 started a new conversation Undefined Index Http_accept_language Laravel

Hi I am facing an error when I trying to call a route on the remote server.

ErrorException in Controller.php line 25:
Undefined index: HTTP_ACCEPT_LANGUAGE
in Controller.php line 25
at HandleExceptions->handleError('8', 'Undefined index: HTTP_ACCEPT_LANGUAGE', '/home/devmzad/public_html/app/Http/Controllers/Controller.php', '25', array('request' => object(Request))) in Controller.php line 25
at Controller->__construct(object(Request))
at ReflectionClass->newInstanceArgs(array(object(Request))) in Container.php line 779
at Container->build('App\Http\Controllers\API\AdvFilterApiController', array()) in Container.php line 629
at Container->make('App\Http\Controllers\API\AdvFilterApiController', array()) in Application.php line 697
at Application->make('App\Http\Controllers\API\AdvFilterApiController') in ControllerDispatcher.php line 67
at ControllerDispatcher->makeController('App\Http\Controllers\API\AdvFilterApiController') in ControllerDispatcher.php line 52
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\API\AdvFilterApiController', 'getAddAdvFilters') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 724
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Checklang.php line 26
at Checklang->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Checklang), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 726
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54

Please any idea what is wrong with it. Please assist.

25 Aug
1 year ago

eddy1992 started a new conversation Error Facing When Creating Columns Dynamically In A Table

Hi I am creating columns dynamically in a table and facing a weird error. The page says

error GTO

error

when I am running the command to create a new column in the table.

The code where I am creating the columns -:

public function createColumn($column)
    {   
        DB::transaction(function () use ($column){
            $this->createColumnInProducts1($column);
            $this->createColumnInProducts4($column);
        });
    }


    public function createColumnInProducts1($column)
    {   
        Schema::table('products1', function ($table) use ($column) {
            $table->string($column);
        });
    }


    public function createColumnInProducts4($column)
    {
        Schema::table('products4', function ($table) use ($column){
            $table->string($column);
        });
    }

Please assist why its showing this error. On my local its working fine but on the server I am getting this error.

18 Aug
1 year ago

eddy1992 left a reply on Create Columns In A Table Dynamically

Thanks @Cronix you are awesome cheers.

eddy1992 left a reply on Create Columns In A Table Dynamically

@Dunsti No I want to add it dynamically through code.

eddy1992 started a new conversation Create Columns In A Table Dynamically

Hi I want to know whether its possible to create columns dynamically in a table. For example If I have table named car and I have two columns , car_name, car_year and later on some condition I want to add columns dynamically like car_tyre, car_insurance in the table. If this is possible please let me know. Thanks.

11 Aug
1 year ago

eddy1992 started a new conversation How To Take Json As Input And Display In Laravel

Hi I want to know whether I could take an array of json and store it in a table as a longText and retrieve it as json later on ? Is this the way to approach it ? if not then what will the ideal way to do it.

Right now in my database there is a table column named filterListValues which has a datatype longText.

I am coping the json ie is the value of the key filterListValues and pasting it in using an text area.

and later I am just getting the it as a string for this column.

"filterListValues": [
            {
              "filterListValuesId": "0",
              "filterListValuesNameEnglish": "All Types",
              "filterListValuesNameArabic": "All Types arabic",
              "filterListValuesImage": ""
            },
            {
              "filterListValuesId": "1",
              "filterListValuesNameEnglish": "Furnished",
              "filterListValuesNameArabic": "Furnished arabic",
              "filterListValuesImage": ""
            },
            {
              "filterListValuesId": "2",
              "filterListValuesNameEnglish": "Semi Furnished",
              "filterListValuesNameArabic": "Semi Furnished arabic",
              "filterListValuesImage": ""
            },
            {
              "filterListValuesId": "3",
              "filterListValuesNameEnglish": "Not Furnished",
              "filterListValuesNameArabic": "Not Furnished arabic",
              "filterListValuesImage": ""
            }
          ]

Please assist me on this. Thank you

09 Aug
1 year ago

eddy1992 left a reply on Base Table Or View Not Found: 1051 Unknown Table After Php Artisan Migrate:refresh

@tykus Thank you for your response, I am using laravel 5.2 and I tried the option to drop all tables and run migrations again but gave me the same error.

eddy1992 started a new conversation Base Table Or View Not Found: 1051 Unknown Table After Php Artisan Migrate:refresh

Hi I am facing an issue where I am trying to run php artisan migrate:refresh and every time I run my migration it gives me an error

[Illuminate\Database\QueryException]
  SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'mzad-web.adv_filter_categories' (SQL: drop table `adv_filter_categories`)
 [PDOException]
  SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'mzad-web.adv_filter_categories'

But when I go and check in the adminer I could see the tables have been dropped. After that If i run php artisan migrate it migrates the tables back again. The only issue is when I try to run php artisan migrate:refresh it gives me this error. Please assist

my migration files I have only two migration files -:

  1. This is the one which is shown in the error.
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAdvFilterCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('adv_filter_categories', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->string('category_name_english');
            $table->string('category_name_arabic');
            $table->boolean('active')->default(1);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('adv_filter_categories');
    }
}


Please assist I am stuck with it for such a long time and not able to understand why tis happening.

Thank you

12 Jul
1 year ago

eddy1992 left a reply on Selected Option Not Working When Using V-model

@tykus nope I do not have any errors in my browser.