johnef_sh

johnef_sh

Member Since 2 Years Ago

Experience Points 6,900
Experience Level 2

3,100 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 47
Lessons
Completed
Best Reply Awards 0
Best Reply
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.

12 May
2 weeks ago

johnef_sh left a reply on Chack For Input Array If It's Empty Or Not

@FTIERSCH - Thanks this function filled is L5.5 I am using L5.4 so it's has thanks a lot.

johnef_sh started a new conversation Chack For Input Array If It's Empty Or Not

I have an input looks like this.

[inventory] => Array ( [0] => Array ( [amount] => 66 [expiry_date] => 2019/05/20 ) )

I am trying to check if the amount and the expiry_date are not null

if ( $input['inventory[0][amount]'] and $input['inventory[0][expiry_date]'] != null )

but I got

Undefined index: inventory[0][amount]

06 May
2 weeks ago

johnef_sh left a reply on Laravel-5.4: Validation Array Field Don't Recognize (*)

@ROBOROBOK - I need this arrays it can't be changed

02 May
3 weeks ago

johnef_sh started a new conversation Laravel-5.4: Validation Array Field Don't Recognize (*)

I am trying to validates fields like this

{!! Form::text('packages[0][price]', null, ['class'=>'form-control', 'placeholder' => trans('interface.price')]) !!}
{!! Form::text('packages[0][unit_count]', null, ['class'=>'form-control', 'placeholder' => trans('interface.unitCount')]) !!}

when I try to make the validation like this

'packages.0.price' => 'required|regex:/^[\d.,]+$/', it works fine

but with (*)

'packages.*.price' => 'required|regex:/^[\d.,]+$/',

it don't work, any ideas please.

01 May
3 weeks ago

johnef_sh left a reply on The Right Way Formatimg The JS Code

@SERGIU17 - will review it thanks

johnef_sh left a reply on The Right Way Formatimg The JS Code

@MVD - Yes this worked fine with me, thanks a lot dear MVD

johnef_sh started a new conversation The Right Way Formatimg The JS Code

Hi guys good day for you all, I'd like o understand how to format this code

<script>
        let counter = 1;
        let limit = 10;

        function addInput(divName) {
            if (counter === limit) {
                alert("You have reached the limit of adding " + counter + " inputs");
            } else {
                let newdiv = document.createElement('div');
                newdiv.innerHTML = '<div class="col-md-12 col-md-pull-1"><div class="col-md-6">{!! Form::text("measurements[' + (counter + 1) + '][width]", null, ["class"=>"form-control", "placeholder" => trans("interface.width")]) !!}</div>';
                document.getElementById(divName).appendChild(newdiv);
                counter++;
            }
        }
    </script>

Here in Form::text("measurements[' + (counter + 1) + '][width]" I try to put this ' + (counter + 1) + ' in the array index but seems it's not reading the code right.

so what should be the right format here.

thanks

30 Apr
3 weeks ago

johnef_sh left a reply on Insert Multiple Records Into Multiple Tables

@MICHALURVA - @MICHALURVA but what if I have more then one measurements?

Look the all idea is I have one product with multiple packages and each package has one measurement

johnef_sh left a reply on Insert Multiple Records Into Multiple Tables

Let's make it more simple

Here I made the HTML FORM like this

{!! Form::text('measurements[measurement][width]', null, ['class'=>'form-control', 'placeholder' => trans('interface.width')]) !!}
{!! Form::select('measurements[measurement][width_u]', $measurements, null, [ 'class'=>'form-control', 'placeholder' => trans('interface.justSelect') ]) !!}

to get the measurements in array and each array has the values and after that loop but still getting the array wrong

"measurements" => array:1 [▼
    "measurement" => array:10 [▼
      "width" => "7"
      "width_u" => "1"
      "length" => "1"
      "length_u" => "1"
      "height" => "4"
      "height_u" => "1"
      "weight" => "5"
      "weight_u" => "2"
      "volume" => "6"
      "volume_u" => "2"
    ]
  ]

if I have two measurements it should be

"measurements" => array:2 [▼
    "measurement" => array:10 [▼
      "width" => "7"
      "width_u" => "1"
      "length" => "1"
      "length_u" => "1"
      "height" => "4"
      "height_u" => "1"
      "weight" => "5"
      "weight_u" => "2"
      "volume" => "6"
      "volume_u" => "2"
    ]
"measurement" => array:10 [▼
      "width" => "5"
      "width_u" => "6"
      "length" => "1"
      "length_u" => "7"
      "height" => "4"
      "height_u" => "8"
      "weight" => "5"
      "weight_u" => "2"
      "volume" => "6"
      "volume_u" => "2"
    ]
  ]

any idea?

johnef_sh left a reply on Insert Multiple Records Into Multiple Tables

@AJITHLAL - Got Illegal string offset 'weight'

johnef_sh started a new conversation Insert Multiple Records Into Multiple Tables

I have 3 tables here

products, pck_measurements, packages

I need to insert the product details into products and multiple packages for this product into packages and multiple measurement pck_measurements depending on the packages_id.

Here is what I try (HTML Form)

{!! Form::select('product_category_id', $productsCategory, null, ['class'=>'form-control', 'placeholder' => trans('interface.pleaseSelect')]) !!}
{!! Form::select('tax_id', $taxes, null, ['class'=>'form-control', 'placeholder' => trans('interface.pleaseSelect')]) !!}
{!! Form::text('name_ar', null, ['class'=>'form-control', 'placeholder' => trans('interface.productNameAr')]) !!}
....
//Now comes the package information
{!! Form::text('packages[price]', null, ['class'=>'form-control', 'placeholder' => trans('interface.price')]) !!}
{!! Form::text('packages[unit_count]', null, ['class'=>'form-control', 'placeholder' => trans('interface.unitCount')]) !!}
...
//And here is the measurement
{!! Form::text('measurements[width]', null, ['class'=>'form-control', 'placeholder' => trans('interface.width')]) !!}
{!! Form::select('measurements[width_u]', $measurements, null, ['class'=>'form-control', 'placeholder' => trans('interface.justSelect')]) !!}
{!! Form::text('measurements[length]', null, ['class'=>'form-control', 'placeholder' => trans('interface.length')]) !!}
{!! Form::select('measurements[length_u]', $measurements, null, ['class'=>'form-control', 'placeholder' => trans('interface.justSelect')]) !!}
...

and here is the controller

public function store( ProductRequest $request ) {
        $input = $request->all();

        $input += [
            'ar' => [
                'name'    => $request->name_ar,
                'details' => $request->details_ar
            ],
            'en' => [
                'name'    => $request->name_en,
                'details' => $request->details_en
            ]
        ];


        $product    = ( new Product )->create( $input );
        $product_id = $product->id;


        foreach ( $input['measurements'] as $measurement ) {
            $addMeasurement = ( new PckMeasurement() )->create( [
                'weight'   => $measurement->weight,
                'weight_u' => $measurement->weight_u,
                'length'   => $measurement->length,
                'length_u' => $measurement->length_u,
                'height'   => $measurement->height,
                'height_u' => $measurement->height_u,
                'width'    => $measurement->width,
                'width_u'  => $measurement->width_u,
                'volume'   => $measurement->volume,
                'volume_u' => $measurement->volume_u
            ] );
            $measurements   = $addMeasurement->id;
        }

        foreach ( $input['packages'] as $package ) {
            ( new Package() )->create( [
                'price'              => $input['packages']['price'],
                'unit_count'         => $input['packages']['unit_count'],
                'product_id'         => $product_id,
                'pck_measurement_id' => $measurements
            ] );
        }

        return redirect()->route( 'product.create' )
                         ->with( 'success', 'Product added Successfully' );
    }

When I try to add the measurement like this

'weight' => $measurement->weight,

Got

trying to get property of non object

any help will be appreciated

18 Apr
1 month ago

johnef_sh left a reply on Easy Way To Convert Raw Mysql Query To Eloquent

@JLRDW - Thanks for replay, I try by the way to do this but stop on the with see I have here

->with( [
                'campaign' => function ( $q ) {
                    $q->select( [ 'id', 'product_id', 'price', 'purchasesLimits', 'stock' ] );
                    $q->where( 'stock', '>', 0 );
                    $q->where( 'expire', '>', Carbon::today()->toDateString() );
                }
            ] );

How to added with the DB facade

johnef_sh started a new conversation Easy Way To Convert Raw Mysql Query To Eloquent

How can I convert a row MySql query to Eloquent

I have a query like this

SELECT * FROM
( SELECT products.id, products.image, products.price, products.featured_item as featured, product_translations.name as name, product_translations.details as details FROM products LEFT JOIN product_translations on products.id=product_translations.product_id where products.quantity > 0 AND products.product_category_id IS NOT NULL AND products.soft_delete=0 AND product_translations.locale='ar' ) a LEFT JOIN ( SELECT *, COUNT(order_details.product_id)as count FROM order_details where order_details.created_at BETWEEN CURRENT_TIMESTAMP - INTERVAL 10 MONTH AND CURRENT_TIMESTAMP GROUP BY order_details.product_id ORDER BY count DESC limit 12 ) b ON b.product_id = a.id ORDER BY count DESC, featured DESC LIMIT 24

I try something like this with Eloquent but still not the same sorting

$query    = ( new Product() )
            ->where( 'quantity', '>', 0 )
            ->where( 'soft_delete', 0 )
            ->where( 'product_category_id', '!=', null )
            ->with( [
                'orderDetail' => function ( $query ) {
                    $query->whereBetween( 'created_at', [ Carbon::now()->subMonth( 10 ), Carbon::now() ] )
                          ->groupBy( 'product_id' )
                          ->take( 12 )->count();
                }
            ] )
            ->where( 'featured_item', 1 )
            ->orderByDesc( 'id' )
            ->where( 'product_category_id', '!=', null )
            ->where( 'soft_delete', 0 )
            ->with( [
                'campaign' => function ( $q ) {
                    $q->select( [ 'id', 'product_id', 'price', 'purchasesLimits', 'stock' ] );
                    $q->where( 'stock', '>', 0 );
                    $q->where( 'expire', '>', Carbon::today()->toDateString() );
                }
            ] );
        $products = $query
            ->select( 'products.*' )
            ->with( 'translations' )
            ->paginate( 16 );

        return response()->json( [
            $products
        ] );

Of course a have all the tables relations. in the models

27 Mar
1 month ago

johnef_sh started a new conversation Laravel 5.4: Loop Through Array And Minus Quantity From Each Object Until Quantity Reach 0 Stops

I need to loop through array and minus needed_quantity from each object

ex. needed_quantity = 22

and there is three objects in this array, each object quantity = 10

so it will be something like this.

take 10 pieces from expire_date = 2019-03-02 inventory will become 0 take 10 pieces from expire_date = 2019-03-10 inventory will become 0 take 2 pieces from expire_date = 2019-03-11 inventory will become 8

Here is the array

$orderProducts = OrderDetail::whereOrderListsId( $deliveryList->order_lists_id )->get();
foreach ( $orderProducts as $order_product ) {
//This the quantity in order details.
$orderQuantity = $order_product->quantity;

foreach ( $orderProducts as $order_product ) {
                    //This the quantity in order details.
                    $orderQuantity = $order_product->quantity;
    $currentInventors = Inventory::whereProductId( $order_product->product_id )->get()->sortBy( 'expire_date' );

    if ( $currentInventors != null ) {
        foreach ( $currentInventors as $currentInventory ) {
            $takeQuantity = $currentInventory->inventory - $orderQuantity; //10-15 = 5
            if ( $currentInventory->inventory >= $orderQuantity ) {
                Inventory::whereId( $currentInventory->id )->update( [ 'inventory' => $takeQuantity ] );
                break;
            } elseif ( $currentInventory->inventory < $orderQuantity ) {
                Inventory::whereId( $currentInventory->id )->update( [ 'inventory' => 0 ] );
                //$takeQuantity = $currentInventory->inventory - $orderQuantity; //10-15 = -5
                $newQuantity = $orderQuantity - $currentInventory->inventory; //15-10 = 5
                if ( $currentInventory->inventory >= $orderQuantity ) {
                    Inventory::whereId( $currentInventory->id )->update( [ 'inventory' => $newQuantity ] );
                    break;
                }
            }
        }
    }
 }
}
26 Mar
2 months ago

johnef_sh started a new conversation Loop Through Inventory And Minus Quantity Until Quantity Reach 0 Stops

First I was looking for while-loop to do this in laravel but I found out that laravel don't use while-loop often.

Describe the case: I have a inventories table which looks like this

|id |product_id | inventory|expire_date| created_at                 | updated_at               | 
|9  |856              |44             |2019-03-01 |2019-03-07 11:13:21|2019-03-25 16:58:51|
|10|857              |10             |2019-03-02 |2019-03-07 11:13:21|2019-03-25 16:04:12|
|11|858              |47             |2019-03-03 |2019-03-07 11:13:22|2019-03-25 16:58:51|
|13|857              |10             |2019-03-10 |2019-03-10 16:53:21|2019-03-25 15:25:19|
|16|857              |10             |2019-03-11 |2019-03-10 17:01:14|2019-03-13 11:01:13|

Now consider on product_id = 857 it has 3 records in the table (and of course it can be more). the difference between the three records is the expire_date

now here is the case clients purchase this product 857 took 22 pieces

I need to take from the oldest expire_date

  • take 10 pieces from expire_date = 2019-03-02 inventory will become 0
  • take 10 pieces from expire_date = 2019-03-10 inventory will become 0
  • take 2 pieces from expire_date = 2019-03-11 inventory will become 8

and so on if there is more..

Here is what I try

$orderProducts = OrderDetail::whereOrderListsId( $deliveryList->order_lists_id )->get();
/*
 * Second loop through this products, and get the quantity of each one
 * and minus this quantity from the same product in the inventory.
 */
    foreach ( $orderProducts as $order_product ) {
        //This the quantity in order details.
        $onQuantity = $order_product->quantity;
        //Here we selected the oldest expire date of the same product in the inventory.
        $currentInventoryFirst = Inventory::whereProductId( $order_product->product_id )
                               ->oldest( 'expire_date' )
                               ->first();

        $averageQuantity       = $currentInventoryFirst->inventory - $onQuantity;
        if ( $currentInventoryFirst != null ) {
        if ( $currentInventoryFirst->inventory >= $onQuantity ) {
            Inventory::whereId( $currentInventoryFirst->id )->update( [ 'inventory' => $averageQuantity ] );
        } else {
        $takeQuantity = $onQuantity - $currentInventoryFirst->inventory;
        Inventory::whereId( $currentInventoryFirst->id )->update( [ 'inventory' => 0 ] );
        }
    }

    $currentInventors = Inventory::whereProductId( $order_product->product_id )->get();

    if ( $currentInventors != null ) {
            foreach ( $currentInventors as $currentInventory ) {
                $currentInventorySecond = Inventory::whereProductId( $order_product->product_id )
                                         ->oldest( 'expire_date' )
                                         ->where( 'id', '!=', $currentInventoryFirst->id )
                                         ->first();
    }
    Inventory::whereId( $currentInventorySecond->id )->update( [ 'inventory' => $takeQuantity ] );
  }
}

in the second piece of the code

if ( $currentInventors != null ) {
                foreach ( $currentInventors as $currentInventory ) {
                    $currentInventorySecond = Inventory::whereProductId( $order_product->product_id )
                                             ->oldest( 'expire_date' )
                                             ->where( 'id', '!=', $currentInventoryFirst->id )
                                             ->first();
        }
        Inventory::whereId( $currentInventorySecond->id )->update( [ 'inventory' => $takeQuantity ] );
      }
    }

I need to loop through inventory and minus quantity until the required quantity reach 0

22 Mar
2 months ago

johnef_sh left a reply on How To Install Laravel 5.4

try this

composer create-project --prefer-dist laravel/laravel projectname "5.4.*"
05 Mar
2 months ago
04 Mar
2 months ago

johnef_sh left a reply on Mb_strpos() Expects Parameter 1 To Be String, Object Given

@DANIELSDEBOER - if I can vote you up 100 times I would do, thanks man you saved my ass :)

20 Feb
3 months ago

johnef_sh left a reply on Laravel 5.4: Return Response Json GroupBy Created_at With Static Key For Each Group

@SHAHRUKH4 - Thanks again dear @shahrukh4 my laravel is 5.4 and php 5.6 but dingo/api uses laravel 5.5+ and needs PHP ^7.0 any other way to do that?

johnef_sh left a reply on Laravel 5.4: Return Response Json GroupBy Created_at With Static Key For Each Group

@SHAHRUKH4 - Thanks for replay, but still I have the same issue I need the timestamp to be the value of key date as now it becomes

{
    "2019-02-18 1212:0202:3939": {
        "date": [
            {
                "id": 2,
                "supplier_id": 15,
                "product_id": 857,
                "product_name": "بن test",
                "product_image": "1547638933.png",
                "needed_quantity": 5,
                "unit_price": "200.0000",
                "total_price": "1000.0000",
                "barcode": 654564,
                "status": 0,
                "created_at": "2019-02-18 12:16:39",
                "updated_at": "2019-02-18 12:16:39"
            }
        ]
    },

I need the timestamp to be the value of the key date something like this

"date" : 2019-02-18 1212:0202:3939 [
   {
       "id": 2,
       "supplier_id": 15,
   }
]
19 Feb
3 months ago

johnef_sh started a new conversation Laravel 5.4: Return Response Json GroupBy Created_at With Static Key For Each Group

I have this controller which group the Collection by date

public function index() {
        $poLists = ( new PurchaseOrder() )
            ->where( 'needed_quantity', '>', 0 )
            ->where( 'supplier_id', $this->guard()->user()->id )
            ->get()->groupBy( function ( $item ) {
                return [ $item->created_at->format( 'Y-m-d HH:mm:ss' ) ];
            } );
dd($poLists);
        return response()->json( $poLists, 200 );
    }

working fine and this is the output

{
    "2019-02-18 1212:0202:3939": [
        {
            "id": 2,
            "created_at": "2019-02-18 12:16:39",
            "updated_at": "2019-02-18 12:16:39"
        }
    ],
    "2019-02-18 1515:0202:0202": [
        {
            "id": 4,
            "created_at": "2019-02-18 15:21:02",
            "updated_at": "2019-02-18 15:21:02"
        },
        {
            "id": 5,
            "created_at": "2019-02-18 15:21:02",
            "updated_at": "2019-02-18 15:21:02"
        }
    ],

is there is a way to add static key for each group like this

{
    date: "2019-02-18 1212:0202:3939" [
        {
            "id": 2,
            "created_at": "2019-02-18 12:16:39",
            "updated_at": "2019-02-18 12:16:39"
        }
    ],
    date: "2019-02-18 1515:0202:0202": [
        {
            "id": 3,
            "barcode": 33254,
            "status": 0,
            "created_at": "2019-02-18 15:21:02",
            "updated_at": "2019-02-18 15:21:02"
        },
        {
            "id": 5,
            "created_at": "2019-02-18 15:21:02",
            "updated_at": "2019-02-18 15:21:02"
        }
    ],

Here is date is the static key

17 Feb
3 months ago

johnef_sh left a reply on Laravel 5.4: Insert Each Item As Row From One Form

@SNAPEY - Thanks a lot this helped me a lot,,, have a great day and god bless you

johnef_sh left a reply on Laravel 5.4: Insert Each Item As Row From One Form

@SNAPEY - now it looks like

array:2 [▼
  "_token" => "muw3phvtnjnJnjBYNqbp0A5f6Pk5St1BkydKPGG7"
  "products" => array:3 [▼
    0 => array:3 [▼
      "product_id" => "856"
      "quantity" => "9"
      "inventory" => "2"
    ]
    1 => array:3 [▼
      "product_id" => "857"
      "quantity" => "8"
      "inventory" => "3"
    ]
    2 => array:3 [▼
      "product_id" => "858"
      "quantity" => "2"
      "inventory" => "4"
    ]
  ]
]

johnef_sh left a reply on Laravel 5.4: Insert Each Item As Row From One Form

Yes Now I got the array like that

array:2 [▼
  "_token" => "muw3phvtnjnJnjBYNqbp0A5f6Pk5St1BkydKPGG7"
  "products" => array:9 [▼
    0 => array:1 [▼
      "product_id" => "856"
    ]
    1 => array:1 [▼
      "quantity" => "9"
    ]
    2 => array:1 [▼
      "inventory" => "2"
    ]
    3 => array:1 [▼
      "product_id" => "857"
    ]
    4 => array:1 [▼
      "quantity" => "8"
    ]
    5 => array:1 [▼
      "inventory" => "3"
    ]
    6 => array:1 [▼
      "product_id" => "858"
    ]
    7 => array:1 [▼
      "quantity" => "2"
    ]
    8 => array:1 [▼
      "inventory" => "4"
    ]
  ]
]

still the very important step here how to insert each one in separate row in my table, I know it should have a loop in my controller but how

johnef_sh left a reply on Laravel 5.4: Insert Each Item As Row From One Form

@SNAPEY - Yes Here is what I done

@foreach($orderis as $orderi)
                                    {!! Form::hidden('products[]product_id', $orderi->productId->id) !!}
                                    {!! Form::hidden('products[]quantity', $orderi->quantity) !!}
                                    <tr>
                                        <td>{!! $sn++ !!}</td>
                                        <td width="5%">
                                            {!! Html::image('images/products/'. $orderi->productId->image, 'thumbs-'.$orderi->productId->name, ['height' => 70]) !!}
                                        </td>
                                        <td>{!! $orderi->product_name !!}</td>
                                        <td>{!! $orderi->quantity !!}</td>
                                        <td>
                                            <div class="col-md-5">
                                                <div class="form-group-inner">
                                                    {!! Form::text('products[]inventory', null, ['class'=>'form-control']) !!}
                                                </div>
                                            </div>
                                        </td>
                                        <td>{!! $orderi->productId->price !!}</td>
                                        <td>{!! $orderi->productId->price * $orderi->quantity !!}</td>
                                    </tr>
                                @endforeach

johnef_sh left a reply on Laravel 5.4: Insert Each Item As Row From One Form

@SNAPEY - it looks more cleaner now

array:2 [▼
  "_token" => "muw3phvtnjnJnjBYNqbp0A5f6Pk5St1BkydKPGG7"
  "products" => array:9 [▼
    0 => "856"
    1 => "9"
    2 => "3"
    3 => "857"
    4 => "8"
    5 => "2"
    6 => "858"
    7 => "2"
    8 => "4"
  ]
]

but should I contenu inserting the data as I did in my controller or it should be changed somehow. thanks a lot for your help

johnef_sh started a new conversation Laravel 5.4: Insert Each Item As Row From One Form

I have a form which contain a for-loop on multiple products here it's sample from my form

{!! Form::open(['route'=>'export-list.store']) !!}
        @foreach($orderis as $orderi)
           {!! Form::hidden('product_id[]', $orderi->productId->id) !!}
           {!! Form::hidden('quantity[]', $orderi->quantity) !!}
               <tr>
                  <td>{!! $sn++ !!}</td>
                  <td width="5%">
                  {!! Html::image('images/products/'. $orderi->productId->image, 'thumbs-'.$orderi->productId->name, ['height' => 70]) !!}
                  </td>
                  <td>{!! $orderi->product_name !!}</td>
                  <td>{!! $orderi->quantity !!}</td>
                  <td>
                     <div class="col-md-5">
                        <div class="form-group-inner">
                       {!! Form::text('inventory[]', null, ['class'=>'form-control']) !!}
                        </div>
                     </div>
                 </td>
                 <td>{!! $orderi->productId->price !!}</td>
                 <td>{!! $orderi->productId->price * $orderi->quantity !!}</td>
               </tr>
           @endforeach
               <tr>
                 <td colspan="9">{!! Form::submit('Submit', ['class'=>'btn btn-primary']) !!}</td>
               </tr>
{!! Form::close() !!}

The end results of this form in my controller looks like this.

array:4 [▼
  "_token" => "cpua1RzKKP4vvklB99HafAdMQ65TSxOWQVQ5r3ye"
  "product_id" => array:3 [▼
    0 => "856"
    1 => "857"
    2 => "858"
  ]
  "quantity" => array:3 [▼
    0 => "9"
    1 => "8"
    2 => "2"
  ]
  "inventory" => array:3 [▼
    0 => "8"
    1 => "2"
    2 => "6"
  ]
]

and here is my controller

public function store( Request $request ) {
        $input = $request->all();

        //Check for the needed quantity
        $quantity        = $input['quantity'];
        $inventory       = $input['inventory'];
        $needed_quantity = $quantity - $inventory;
        //Get the product information
        $productInfo = ( new Product() )->find( $input['product_id'] );
        $totalPrice  = $productInfo->price * $needed_quantity;


        ( new PurchaseOrder() )->create( [
            'product_id'      => $input['product_id'],
            'product_name'    => $productInfo->translate( 'ar' )->name,
            'product_image'   => $productInfo->image,
            'needed_quantity' => $needed_quantity,
            'unit_price'      => $productInfo->price,
            'total_price'     => $totalPrice,
            'barcode'         => $productInfo->barcode,
        ] );

        return redirect()->route( 'order-detail.index' )->with( 'status', 'Created successfully' );
    }

Now all I want to do here is to insert each item as row in purchase_orders considering the Check for the needed quantity.

16 Jan
4 months ago

johnef_sh left a reply on Laravel 5 Replicate() Handle Columns That Have Unique Attribute

Hi guys I am trying the same as you said but where is the replacement I need to replace the username and password of my user for example I did that

$supplierId = Auth::guard( 'supplier' )->id(); $currentSupplier = ( new Supplier )->find( $supplierId ); $newSupplier = $currentSupplier->replicate(); $newSupplier->email = $currentSupplier->email . '_' . $newSupplier->id; $newSupplier->password = $currentSupplier->password . '_' . $newSupplier->id; $newSupplier->save();

but still I am getting the same username and password.

26 Nov
6 months ago

johnef_sh left a reply on Laravel, Jquery, AJAX: How To Return View On A Get Request

@CONSIGLIERE - is this some kind of dubbing in ajax? please clear your answer

10 May
1 year ago

johnef_sh left a reply on GroupedBy Id And Count The Quantity Of Each Product

What I finished up with to close this question is making new query

$orderis = ( new OrderDetail() )
            ->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id )
            ->when( $dateFrom, function ( $query ) use ( $dateFrom ) {
                $query->whereDate( 'created_at', '>=', $dateFrom );
            } )
            ->when( $dateTo, function ( $query ) use ( $dateTo ) {
                $query->whereDate( 'created_at', '<=', $dateTo );
            } )
            ->when( $status, function ( $query ) use ( $status ) {
                $query->whereHas(
                    'orderId', function ( $query ) use ( $status ) {
                    $query->where( 'order_state_id', '=', $status );
                } );
            } )
            ->groupBy( 'product_id' )
            ->selectRaw( 'order_details.*, sum(quantity) as quantity, product_id' )
            ->get();

This time I was selecting from the OrderDetail it self and this line of code helped me a lot to finish this

->selectRaw( 'order_details.*, sum(quantity) as quantity, product_id' )

01 May
1 year ago

johnef_sh left a reply on GroupedBy Id And Count The Quantity Of Each Product

@lostdreamer_nl honestly I did that but no grouping made there. I even try this $order->orderDetail()->groupBy('product_id') because someone suggest that this

As you are returning an object of type OrderList rather than Collection then you will not have access to the groupBy() method.

yes of course I removed the debugging from every where. but still not working.

30 Apr
1 year ago

johnef_sh left a reply on GroupedBy Id And Count The Quantity Of Each Product

@lostdreamer_nl it should be but what I got is

| Product name | quantity | Product_id | | -------------------- | --------------------------- | | Coffey | 2 | 2 | | Coffey | 1 | 2 |

and the other products just the same no grouping

johnef_sh left a reply on GroupedBy Id And Count The Quantity Of Each Product

@lostdreamer_nl thanks for replay, what I need is to group all the products by it's ID and then count the total quantity of all these grouped products Ex: Here is a list of products

product name           quantity
-------------------------------
Tea                                  2
-------------------------------
Tea                                  3
-------------------------------
juice                                1
-------------------------------
juice                                2
-------------------------------

Now after we group them they has to be in form of.

product name           quantity
-------------------------------
Tea                                  5
-------------------------------
juice                               3
-------------------------------

johnef_sh started a new conversation GroupedBy Id And Count The Quantity Of Each Product

I have a filtration query looks like this.

public function index( Request $request ) {
        $dateFrom = $request->get( 'dateFrom' );
        $dateTo   = $request->get( 'dateTo' );
        $status   = $request->get( 'orderState' );

        $orders = ( new OrderList() )
            ->whereHas( 'orderDetail', function ( $query ) {
                $query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id );
            } )
            ->with( 'deliveryList' )
            ->with( 'orderDetail' )
            ->when( $dateFrom, function ( $query ) use ( $dateFrom, $dateTo ) {
                $query->whereBetween( 'created_at', [ $dateFrom, $dateTo ] );
            } )
            ->when( $status, function ( $query ) use ( $status ) {
                $query->where( 'order_state_id', $status )->get();
            } )->get();

        $productList = $orders->orderDetail;
        dd( $productList );
        //Order Status
        $orderStates = OrderState::listsTranslations( 'states' )->pluck( 'states', 'id' )->toArray();


        return view( 'supplierComponents.order_list', compact( 'orders', 'orderStates' ) );
    }

now this query will output a list of orders with the orders details. what I need is group the products in each order and get the quantity

the last view should be something like this

product name           quantity
-------------------------------
Tea                      5
-------------------------------
juice                    3
-------------------------------

My Models OrderLst

public function orderDetail() {
        return $this->hasMany( OrderDetail::class, 'order_id' );
    }

thought I will never get it the right way from controller and I didn't think about try to get it in the blade directly

so What I did is shifted to the blade trying to make it there.

Here what I did

@foreach($orders as $order)
    @foreach($order->orderDetail as $items)
       <tr>
         <td>{!! $items->quantity !!}</td>
         <td>{!! $items->product_name !!}</td>
       </tr>
    @endforeach
@endforeach

Now I am getting all the products listed as I need but try to Group them like that

@foreach($orders as $order)
      @foreach($order->orderDetail->groupBy('product_id') as $items)
          <tr>
            <td>{!! $items->quantity !!}</td>
            <td>{!! $items->product_name !!}</td>
          </tr>
      @endforeach
@endforeach

Got: Property [quantity] does not exist on this collection instance.

26 Apr
1 year ago

johnef_sh left a reply on Laravel 5.4 Nested @foreach

@Snapey Thanks for helping me I did what you said and it worked fine but one thing was problematic here is the groupBy see my new query

public function index( Request $request ) {
        $dateFrom = $request->get( 'dateFrom' );
        $dateTo   = $request->get( 'dateTo' );
        $status   = $request->get( 'orderState' );

        $orders = ( new OrderList() )
            ->whereHas( 'orderDetail', function ( $query ) {
                $query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id );
            } )
            ->when( $dateFrom, function ( $query ) use ( $dateFrom, $dateTo ) {
                $query->whereBetween( 'created_at', [ $dateFrom, $dateTo ] );
            } )
            ->when( $status, function ( $query ) use ( $status ) {
                $query->where( 'order_state_id', $status )->get();
            } )
            ->get();

        //dd( $orders );
        //Order Status
        $orderStates = OrderState::listsTranslations( 'states' )->pluck( 'states', 'id' )->toArray();


        return view( 'supplierComponents.order_list', compact( 'orders', 'orderStates' ) );
    } 

Now here

$orders = ( new OrderList() )
            ->whereHas( 'orderDetail', function ( $query ) {
                $query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id );
            } )

I am selecting the supplier_id but how to groypBy the order_id?

any help here please.

24 Apr
1 year ago

johnef_sh left a reply on Laravel 5.4 Nested @foreach

@Cronix Hi let me clear the issue may you can help me.

I have all OrderList displayed and each OrderList has id now I am querying on OrderDetail which is belongsTo to OrderList by the order_id

when I run like this @foreach($orders as $items) I get all the products listed under each OrderList all I need here to list the products that's related to this OrderList

like order list 1 order details with order_id = 1 should be listed there

johnef_sh left a reply on Laravel 5.4 Nested @foreach

@bobbybouwmann Thanks for replay to me :)

but where items comes from do you mean orderId this is the related function in model but I already try this anddidn't work

johnef_sh started a new conversation Laravel 5.4 Nested @foreach

I got very confused with this nested @foreach

First I have two tables one is order_lists the second is order_details the two tables related to each others in the models.

Now here is my controller

public function index( Request $request ) {
        $dateFrom = $request->get( 'dateFrom' );
        $dateTo   = $request->get( 'dateTo' );
        $status   = $request->get( 'orderState' );

        $orders = ( new OrderDetail() )
            ->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id )
            ->when( $dateFrom, function ( $query ) use ( $dateFrom, $dateTo ) {
                $query->whereBetween( 'created_at', [ $dateFrom, $dateTo ] );
            } )
            ->when( $status, function ( $query ) use ( $status ) {
                $query->whereHas( 'orderId', function ( $query ) use ( $status ) {
                    $query->where( 'order_state_id', $status );
                } );
            } )
            ->groupBy( 'order_id' )
            ->get();

        //Order Status
        $orderStates = OrderState::listsTranslations( 'states' )->pluck( 'states', 'id' )->toArray();


        return view( 'supplierComponents.order_list', compact( 'orders', 'orderStates' ) );
    }

Now comes to the Blade which I have the problem in.

I need to list all the orders_list and under each order I need to display the items that is related to this order only

Here is my blade code

@foreach($orders as $order)
    **No problems here as a get all my orders listed fine**
    <td><strong># {!! $order->orderId->id !!}</strong></td>
    <td><strong>{!! $order->orderId->orderedUsers->name !!}</strong></td>
    <td>{!! $order->created_at !!}</td>
    **Here comes the problem where I need to list the products related to this order**
@foreach($order as $items)
    <td>{!! $items->product_name !!}</td>
    <td>{!! $items->price !!}</td>
    **Here I get all the products listed not only the ones that's related to this order**
@endforeach

@endforeach 

OrderDetail model

public function orderId() {
    return $this->belongsTo( OrderList::class, 'order_id' );
}

OrderList model

public function orderDetail() {
        return $this->hasMany( OrderDetail::class, 'order_id' );
}

How can I get the related products to this order only?

03 Apr
1 year ago

johnef_sh left a reply on How To Sort Users By Number Of Posts

The most quick and easy way to do that by

Use withCount() and then orderBy() to make it with single query.

please refer to this post https://stackoverflow.com/a/49627868/454012

25 Mar
1 year ago

johnef_sh left a reply on Need To Sort Prodcut By Price ASC And DESC

@Snapey thanks but give us an example please

03 Jan
1 year ago

johnef_sh left a reply on Best Practice For Handling "active" Menu Item In L5

@bonifazzy I don't see where is app/Http/Helpers/ did you created this folder??

johnef_sh left a reply on What Is The Best Way To Highlight An Active Menu Item ?

@pmall can you please clear your answer more

say I have this menu item and I need to do active

<li>
       <a href="{!! URL::route('services.index') !!}"><i class="fa fa-plus"></i>{!! trans('interface.services') !!}</a>
</li>

and I need to add active as a class to it like

<li>
       <a class="active" href="{!! URL::route('services.index') !!}"><i class="fa fa-plus"></i>{!! trans('interface.services') !!}</a>
</li>

How to do that?? Thanks

28 Oct
1 year ago

johnef_sh started a new conversation Iterate Over An Array Using Foreach Loop

I have an array like this

$event->menu->add( 'MEDIA' );
$event->menu->add(
    [
        'text'       => 'About us',
        'icon_color' => 'green',
        'submenu'    => [
            [
                'text'       => 'About us',
                'icon_color' => "lime",
                'url'        => 'admin/about/1/edit',
            ],
        ],
    ] );

I need to loop using foreach into submenu

how this can be done?

Here is my foreach loop

$abouts = About::all();
foreach ( $abouts as $about ) {
        $event->menu->add(
                    [
                        'text'       => 'About us',
                        'icon_color' => "lime",
                        'url'        => 'admin/about/1/edit',
                    ]
                );
}
15 Oct
1 year ago

johnef_sh left a reply on Dimsav Call To A Member Function TranslateOrNew() On A Non-object

@Devon thanks but any way to takeout objects from $request->all();

johnef_sh started a new conversation Dimsav Call To A Member Function TranslateOrNew() On A Non-object

I am using Laravel 5.2 Package dimsav laravel-translatable 6.*

This is my worked controller

$about = new About();
        $about->link = $request->link;
        $about->save();

        $localization = $request['localization'];
        //dd($localization);
        // check if locales arabic and english only
        $locales = array_keys($localization);
        foreach ($locales as $locale) {
            if (!in_array($locale, array('en', 'ar'))) {
                Session::flash('message', 'Lang Error');
                return Redirect::back();
            }
        }

        foreach ($localization as $locale => $parameters) {
            $about->translateOrNew($locale)->title = $parameters['title'];
            $about->translateOrNew($locale)->details = $parameters['details'];
        }

        $about->save();

but when I try to use mass-assignment

$input = $request->all();

        $localization = $input['localization'];
        // check if locales arabic and english only
        $locales = array_keys( $localization );
        foreach ( $locales as $locale ) {
            if ( ! in_array( $locale, array( 'en', 'ar' ) ) ) {
                Session::flash( 'message', 'Lang Error' );

                return Redirect::back();
            }
        }


        foreach ( $localization as $locale => $parameters ) {
            $input->translateOrNew( $locale )->title   = $parameters['title'];
            $input->translateOrNew($locale)->details = $parameters['details'];
        }
dd($input);


        About::create( $input );

Got an error

    Call to a member function translateOrNew() on a non-object

any help please what I am doing wrong here.

Edit :

My about Model

    use Dimsav\Translatable\Translatable;
    use Illuminate\Database\Eloquent\Model;

    class About extends Model {
        use Translatable;


        public $translatedAttributes = [ 'title', 'details' ];
        protected $fillable = [ 'link' ];
    }

my abouttranslation model

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AboutTranslation extends Model
{
    public $timestamps = false;
    protected $fillable = ['title', 'details', 'about_id'];
}
26 Sep
1 year ago

johnef_sh left a reply on How To Limit String Data In View

@bashy yes nice but you don't have to write with $limit and $end

Str::limit($value, $limit = 100, $end = '...')

this will work too

str::limit($value, 100, '...')

short and sweet :)

21 Sep
1 year ago

johnef_sh left a reply on Upload Multiple Images To Server Using Image Intervention

@samalapsy how did you solve this problem I have done something like this but I got an issue I was able to upload and resize my images but Got duplicated images say I am uploading this three images 0.png, 1.png, 2.png

but this is how the images inserted in database

id=>1 -- 0.png
id=>2 -- 0.png
id=>3 -- 1.png

see my controller

if ( $request->hasFile( 'gImg' ) ) {
            $gImgs = $request->gImg;
            foreach ( $gImgs as $gImg ) {

                $filename = time() . '.' . $gImg->getClientOriginalExtension();
                Image::make( $gImg )->resize( 1890, 1358 )->save( 'images/decoration/' . $filename );
                Image::make( $gImg )->fit( 646, 250 )->save( 'images/decoration/thumbs-' . $filename );
                $dcoImg                = new DecorationGallery();
                $dcoImg->image         = $filename;
                $dcoImg->decoration_id = $insertedId;
                $dcoImg->save();
            }
        }

can you please help