madsynn

Experience

5,910

0 Best Reply Awards

  • Member Since 2 Years Ago
  • 55 Lessons Completed
  • 1 Favorite

21st November, 2017

madsynn left a reply on Need Help With Pulling Data. • 9 hours ago

@drfraker

Normally i would but in this instance i do not know enough about googles library to build my own version of the services needing to be pulled in.

madsynn left a reply on Relationship Help • 9 hours ago

@robrogers3

The clinics can have many zip codes which are comprised of all the zip codes of the area they cover.

Locations will only have 1 zip code because locations are physical addresses for service from that clinic.

CLINIC 1
Covers: Zipcodes 1-20
With 3 locations:
    Location 1
        has a physical address and Zipcode 1 
    Location 2
            has a physical address and Zipcode2
    Location 3
            has a physical address and ZipCode3
    
CLINIC 2
Covers: Zipcodes 20-50
With 3 locations:
    Location 22 
            has a physical address and Zipcode 22
    Location 23
            has a physical address and Zipcode 23
    Location 24
            has a physical address and  Zipcode 24

view schema screenshot here: https://s.nimbus.everhelper.me/share/1260032/79noieuxsn6hzbehh11p

So far my relationships are as follows.

clinic hasMany zipcodes clinic hasMany locations location belongsTo clinic location hasOne zipcode zipcodes belongToMany clinics zipcode belongsTo location

Please let me know your thoughts.

Thank you

20th November, 2017

madsynn started a new conversation Need Help With Pulling Data. • 1 day ago

I have a package that uses info entered into the config file but i need to have it pull from a table record instead.

config file

 'oauth' => [
            'client_id' => env('GOOGLE_CLIENT_ID'),
            'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        ],
 
        'oauth_json' => [
            'auth_config' => env('GOOGLE_AUTH_CONFIG'),
        ],
 
        'service_account' => [
            'application_credentials' => env('GOOGLE_APPLICATION_CREDENTIALS'),
        ],

but instead i need it to pull the same data that is entered into a table for each company logging in.

not user how to tell the package to pull from the table instead of the config file what would be the easiest way to do this.

Any help would be appreciated.

madsynn left a reply on Relationship Help • 1 day ago

@robrogers3 you still around?

16th November, 2017

madsynn left a reply on Relationship Help • 5 days ago

@robrogers3

You almost guessed it right sorry for not being clear enough. The part that is a little off is this line: "A Zipcode belongsTo (Clinic) <-- this means only one ZipCode can be associated with a clinic. (attached to)"

A Zipcode belongsTo clinic but is attached to one Location.

As for the schema, I have not created them yet because I'm trying to determine the best way to structure them.

Here is a better example:

The owner Steve has a business called steves family health clinic. So the clinic is Steves family health clinic. Now The business = clinic services 20 zip codes in that area before he goes into someone else's territory. The Clinic has 3 location in 3/20 zipcodes.

so id a person searching for service in their own zip code searches for a clinic in one of the 20 zip codes it will pull up the clinics 3 locations even if it's not in the zip codes with no location attached.

Hope this clears it up a little.

What I have built so far you can check out here.

http://www.laravelsd.com/share/OMviLu

Thanks

14th November, 2017

madsynn started a new conversation Relationship Help • 1 week ago

I'm using L5 and I'm trying to figure out how to do the relationships for the following tables any help would be appreciated.

clinics locations zipcodes

clinics are over a list of zip codes

locations are attached to some of the zip codes assigned to the clinic but not all.

clinic 1 has 10 zip codes assigned to it. clinic 1 has 3 locations 1 locations are attached to 3 of the zipcodes attached to the clinic zip codes 3 out of 10 assigned zip codes.

Thanks in advance for your help.

27th October, 2017

madsynn started a new conversation Possible Site Concept • 3 weeks ago

I am looking for any advice on how to create the following with laravel. Any ideas are welcome and appreciated.

I have one main site that is the main site for other sites but im not sure how i can structure this and im looking for your guys help. Let me start with concept layout.

portal.com (this is the manager and main part of the whole thing.)

→ site1.com (site created and managed by portal) → site2.com (site created and managed by portal) → site3.com (site created and managed by portal)

The portal site would create all content and pages and select wich one it would publish to in the creation. the problem i am seeing is how do i get the routes to work if they are a different domain then portal.com

17th April, 2017

madsynn left a reply on Blade Conditional Help • 7 months ago

@aivis That worked thank you!!

madsynn left a reply on Blade Conditional Help • 7 months ago

@aivis thank you in advance.

Ok i tried the following but still nothing.

@if(Request::is('/en/resources/blog/*'))
     @include('frontend.article.partials.temp')
      @else
    // duh not working
@endif 

madsynn started a new conversation Blade Conditional Help • 7 months ago

Can anyone tell me why these will not work? I have tried them all and to no avail. I am trying to only show code if the view is part of the blog.

@if(Request::is() === '/en/resources/blog/')
<h1>this is a blog article</h1>
 @else
    // duh not working
@endif

@if(Request::is() === '/en/resources/blog/')
     @include('frontend.article.partials.temp')
      @else
    // duh not working
@endif


@if(Request::path() == '/en/resources/blog/')
    <h1>article for the blog</h1>
     @else
    // duh not working
@endif

@if(Request::path() === '/en/resources/blog/home-use')
    // code
    @else
    // duh not working
@endif 

24th March, 2017

madsynn started a new conversation Can Someone Point Me In The Right Direction? • 7 months ago

I need to create a function that will inventory all images and all sizes and versions of it are created on upload and if one is missing in any of the different sizes grab the original image and add it again so all version and sizes are in inventory.

I am not sure how to go about this. Can any of you tell me your thoughts on what to use for each step, i would love to hear them.

This is an example of my upload function with the different sizes being created. I would need this function to check each directory for the file and if missing regenerate it from the original image that is in the $dest.

$dest = 'uploads/products';

$Path = public_path() . $this->imgDir;
$ThumbPath = public_path() . $this->thumbDir;
$LoopPath = public_path() . $this->loopDir;
$ShopLoopPath = public_path() . $this->shopLoopDir;
$FitPath = public_path() . $this->shopLoopDir . "fit/";

File::exists($Path) or File::makeDirectory($Path);
File::exists($ThumbPath) or File::makeDirectory($ThumbPath);
File::exists($LoopPath) or File::makeDirectory($LoopPath);
File::exists($ShopLoopPath) or File::makeDirectory($ShopLoopPath);
File::exists($FitPath) or File::makeDirectory($FitPath);

$name = $request->file('thumbnail')->getClientOriginalName();
$from = $request->file('thumbnail');
Image::make($from)->resize($this->width, $this->height)->save($Path . $name);
Image::make($from)->resize($this->thumbWidth, $this->thumbHeight, function ($constraint) {$constraint->upsize(); })->save($ThumbPath . $name);
Image::make($from)->resize($this->loopWidth, $this->loopHeight, function ($constraint) {$constraint->upsize(); })->save($LoopPath . $name);
Image::make($from)->fit($this->shopLoopWidth, $this->shopLoopHeight, function ($constraint) {$constraint->upsize(); })->save($ShopLoopPath . $name);
Image::make($from)->resize($this->shopLoopWidth, $this->shopLoopHeight, function ($constraint) {$constraint->upsize(); })->save($FitPath . $name);

$request->file('thumbnail')->move($Path, $name);

$product = $request->all();
$product['thumbnail'] = $name;

12th October, 2016

madsynn left a reply on Help Converting Auth::user To Sentinel::getUser • 1 year ago

@jlrdw the facedes in config/app.php

        'Activation'          => Cartalyst\Sentinel\Laravel\Facades\Activation::class,
        'Reminder'            => Cartalyst\Sentinel\Laravel\Facades\Reminder::class,
        'Sentinel'            => Cartalyst\Sentinel\Laravel\Facades\Sentinel::class,

facedes in app/Http/Kernel.php

 protected $routeMiddleware = [
        'before' => \App\Http\Middleware\BeforeMiddleware::class,
        'sentinel.auth' => \App\Http\Middleware\SentinelAuth::class,
        'sentinel.permission' => \App\Http\Middleware\SentinelPermission::class,
        'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
        'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
        'isAdmin' => \App\Http\Middleware\isAdmin::class,
        'clearcache' => \App\Http\Middleware\ClearCache::class,
    ];

Do you mean these ones?

11th October, 2016

madsynn started a new conversation Help Converting Auth::user To Sentinel::getUser • 1 year ago

I have been trying to make my working cart use Sentinel instead of Auth but i cannot get it to work can any of you help me?

old file

new file i am having trouble with

madsynn left a reply on Blade @include Help • 1 year ago

@wolle404 Thanks,

Can you show me an example of share of view?

10th October, 2016

madsynn started a new conversation Sentinel Help • 1 year ago

Can you guys look at my implementations for Sentinel and tell me why they are not working please.

1

  public static function getPageInfo(&$cart,&$total)
    {
        if (Sentinel::check()) {
            $cart = Sentinel::getUser()->cart;
        }
}

2

if (Sentinel::check()) {
            $exists = 0;
            if (Session::has('cart')) {
                foreach (Session::get('cart') as $key => $cart) {
                    if ($cart['product_id'] == $product_id) {
                        $cart['quantity'] += $request->quantity;
                        if ($cart['quantity'] <= 0) {
                            $cart['quantity'] = 1;
                        }

3

$userCart = Sentinel::getUser()->cart;

madsynn started a new conversation Blade @include Help • 1 year ago

Hi everyone, i was wondering if you guys might be able to help me understand the @include in blade.

I have a blade page i am trying to organize and break into smaller chunks of with the @include in a laravel 5.1 site and keep running into problems.

If i use this according to the laravel docs it should get all the same data available in the parent.

Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:

Problem is it is not working. If i use @inject('model', 'App\Model') some of the data seems to work but on other parts it does not.

I also have a header with a menu item that has to always be present and i cannot get that to keep it looping through the data because on some pages it tells me the variable is not valid and its an incorrect for each.

layout.blade.php
│   └── INCLUDES header.blade.php
│       └── INCLUDES menu-cart.blade.php  (this part needs to show the cart products  and is not working)
└── EXTENDS
    └── index.blade.php
        ├── INCLUDES product-details.blade.php
        ├── INCLUDES product-sidebar.blade.php
        ├── INCLUDES product-features.blade.php
        ├── INCLUDES product-options.blade.php
        └── INCLUDES product-additional.blade.php

The menu-cart.blade.php is the component i need to loop through the current user or guests car at all times.

All the includes inside the index.blade.php are wrapped in a foreach on the index.blade.php but when i try and get data back using something like this {!!$product->name !!} i get a invalid foreach loop variable products is not valid.

Please tell me what you think please.

madsynn left a reply on Sentinel:: Help • 1 year ago

Anyone?

7th October, 2016

madsynn started a new conversation Retrieve Multiple Fields From Another Model As Select • 1 year ago

Can anyone tell me how i would go about creating the relationship that would allow me to pull multiple fields from one model to another almost like a mirror copy but in a different area of the site.

Explination example:

ProductsModel table fields:

  • name
  • upc
  • price
  • sku
  • barcode

Warehouse Model table fields:

  • name = name from products
  • upc = upc from products
  • price = price from products
  • barcode = barcode from products

madsynn left a reply on Where Are You All From? • 1 year ago

Salt Lake City UT Here!!

6th October, 2016

madsynn left a reply on Sentinel:: Help • 1 year ago

@wallyjaw Thanks for your reply but not quite what i need. I will post my whole function for you to see. Maybe you can see my error.


    public static function getPageInfo(&$cart,&$total)
    {
        if (Sentinel::check()) {
            $cart = Sentinel::getUser()->cart;
        } else {
            $cart = new Collection;
            if (Session::has('cart')) {
                foreach (Session::get('cart') as $item) {
                    $elem = new Cart;
                    $elem->product_id = $item['product_id'];
                    $elem->amount = $item['quantity'];
                    if (isset($item['options'])) {
                        $elem->options = $item['options'];
                    }
                    $cart->add($elem);
                }
            }
        }
        $total = 0;
        foreach ($cart as $item) {
            $total += $item->product->price*$item->amount;
        }
    }

madsynn started a new conversation Sentinel Help • 1 year ago

How can i get the user email using sentinel?

Sentinel::getUser()->email

madsynn left a reply on Sentinal And Helper File Issue • 1 year ago

The file;

<?php namespace Ecommerce;

use App\Models\Section;
use App\Models\Cart;

use Sentinel;
use Session;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection;

class helperFunctions
{
    public static function getPageInfo(&$sections,&$cart,&$total)
    {
        $sections = Section::all();
        if (Sentinel::getUser()) {
            $cart =  Sentinel::getUser()->cart;
        } else {
            $cart = new Collection;
            if (Session::has('cart')) {
                foreach (Session::get('cart') as $item) {
                    $elem = new Cart;
                    $elem->product_id = $item['product_id'];
                    $elem->amount = $item['quantity'];
                    if (isset($item['options'])) {
                        $elem->options = $item['options'];
                    }
                    $cart->add($elem);
                }
            }
        }
        $total = 0;
        foreach ($cart as $item) {
            $total += $item->product->price*$item->amount;
        }
    }
}

madsynn left a reply on Sentinal And Helper File Issue • 1 year ago

@Snapey

Can you see what my problem is i keep getting this error on the helperFunctions.php

ErrorExceptionapp/Ecommerce/helperFunctions.php in handleError

Thanks

5th October, 2016

madsynn left a reply on Sentinal And Helper File Issue • 1 year ago

Can any one help ?

3rd October, 2016

madsynn started a new conversation Sentinal And Helper File Issue • 1 year ago

Hope someone can see what i am missing.

I keep getting an error when trying to use helper functions on my index and view pages. It is the mechanism that shows my cart and contents in the head menu on all the pages. I am using Sentinel and i think that might be part of my problem I keep getting this error.

ErrorException in helperFunctions.php line 34:  Invalid argument supplied for foreach()

my helper file:

use App\Models\Section;
use App\Models\Cart;
use App\Models\Option;
use App\Models\Price;

use Sentinel;
use Session;
use \Illuminate\Database\Eloquent\Collection;

class helperFunctions
{
    public static function getPageInfo(&$sections,&$cart,&$total)
    {
        $sections = Section::all();
        if ( Sentinel::getUser()) {
            $cart =  Sentinel::getUser()->cart;
        } else {
            $cart = new Collection;
            if (Session::has('cart')) {
                foreach (Session::get('cart') as $item) {
                    $elem = new Cart;
                    $elem->product_id = $item['product_id'];
                    $elem->amount = $item['qty'];
                    if (isset($item['options'])) {
                        $elem->options = $item['options'];
                    }
                    $cart->add($elem);
                }
            }
        }
        $total = 0;
        foreach ($cart as $item) {
            $total += $item->product->price*$item->amount;
        }
    }
}

index function in my productscontroller.php

namespace app\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
 
use App\Models\Category;
use App\Models\Product;
use App\Models\CategoryProduct;
use App\Models\AlbumPhoto;
use App\Models\Section;
use App\Models\Cart;
use App\Models\Option;
use App\Models\OptionValue;
use App\Models\ProductFeature;
use App\Models\ProductVariant;
use App\Models\OrderProduct;
use File;
use Sentinel;
use App;
use Session;
use \Illuminate\Database\Eloquent\Collection;
use App \Ecommerce\helperFunctions;

class ProductController extends Controller
{
    public function index()
    {
       $new_products = Product::orderBy('created_at', 'desc')->take(12)->get();
        helperFunctions::getPageInfo($sections,$cart,$total);
        return view('frontend.shop.index', compact('new_products','sections', 'cart', 'total'));

    }

the models:


// CART 
class Cart extends Model
{
    protected $table = "cart";
    protected $fillable = ['product_id','amount'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }
}

// PRODUCT
lass Product extends Model
{
    protected $table = "products";

    protected $fillable = ['name' , 'manufacturer' , 'price' , 'details' , 'quantity' , 'category_id' , 'thumbnail'];

    public function categories()
    {
        return $this->belongsToMany('App\Category', 'category_product');
    }

    public function orders()
    {
        return $this->belongsToMany('App\Order');
    }

    public function carts()
    {
        return $this->belongsToMany('App\Cart');
    }

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

    public function options(){
        return $this->hasMany('App\Option');
    }
}
// SECTION
class Section extends Model
{
    protected $table = "sections";
    protected $fillable = ['name'];

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

If anyone can see what im missing it would be very helpful.

28th September, 2016

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey you still around?

27th September, 2016

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey

I have been trying this for almost 2 weeks now can you show me an example of how to use the create like you are talking about please. thank you for your patience.

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey

Question in your profile it says hire me. How much do you charge. I might have you finish getting our cart working but need to know your pricing. You can email me at pmadsen2013 at gmail.com

26th September, 2016

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey Sorry about that i thought i clarified it already. I am creating new product with multiple prices. The update stuff you helped me with will probably work great if i can get them created.

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey Thank you for your response.

instead of the product listing only once it is listing the product for each new product.

What i mean here is in my admin when i got to products.blade.php where i get a list of all the products, when i create a new product with multiple prices it saves as the same product the same number of the alternate prices. Instead of one product.

Don't use the existing price id, and just assign a counter to each row in the table, irrespective if its a new price or not. In the save method, first delete all the old product prices (bear in mind if there is a fault in saving you could lose all the rows), and then create all new prices.

So you are telling me not to use a counter here because it might overwrite the products that are already listed in those rows. correct? how would i add new prices. The product->price has not been created yet so i cannot get the priceID what can i use for this part. i see you use prices[{{ $price->id }}][quantity] with $price->id but until i save the product the price does not have an id correct?

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey " //needs more thought about handling new prices. This just copes with editing existing ones"

Not sure what you mean here. wouldn't this be handled in the store method. this is the part im having troubles with. the $product = new Product::create(); is the part that will not work for me.

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey

Thank you for your help i will try them in the morning. I have another question about the saving also. When i does save it saves all new prices but ties them to the product id. which is what its supposed to do. but in my products view in the admin instead of the product listing only once it is listing the product for each new product. Do you know why its doing this. that would be the product.blade.php in the backend/ecom/products/ part of the views.

23rd September, 2016

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey

I tried what you recommended but to no avail. can you please take a look at my files and see if you can find why i cannot get the prices to save to the database. I have worked on this for a week now and am really frustrated. Do you by chance freelance?

my files are added to this.

https://github.com/madsynn/laravelEcom.git

Thank you for taking the time to help me.

19th September, 2016

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey Thank you for the great info. I am going to try it now. Sorry i forgot the form. Here is the form for my pricing.

JS

$("#addRow").click(function (e) {
            $i++;
            console.log("Insert Data For New Product Price");
             e.preventDefault();
              $("#addRow").click(function() {
                   var row = $("<tr>" + "<td><input type='text' class='text-center form-control' name='price[$i]['title']' /></td><td><input type='text' class='text-center form-control' name='price[$i]['model']' /></td>" +
                   "<td><input type='text' class='text-center form-control  currency' name='price[$i]['price']' placeholder='$0.00' data-affixes-stay='false' data-prefix='$ ' data-thousands=',' data-decimal='.' /></td>" +
                   "<td><input type='text' class='text-center form-control' name='price[$i]['quantity']' /></td>" +
                   "<td><input type='text' class='text-center form-control' name='price[$i]['sku']' /></td>" +
                   "<td><input type='text' class='text-center form-control' name='price[$i]['upc']' value='636343' /></td>" +
                   "</tr>" + "<tr class='alt'><td colspan='1' class='text-center labelTextarea'><label ><strong>Product Variation Details:</strong></label></td>" +
                   "<td colspan='4'><textarea rows='3' class='form-control details-input' name='price[$i]['alt_details']' placeholder='add the details or difference here:'></textarea></td>" +
                   "</tr>");
                   $("table#product-pricing-table tbody").append(row);
                   $('table#product-pricing-table input.currency').maskMoney();
               });
               $(function() {
                   $('table#product-pricing-table input.currency').maskMoney();
               });

HTML

 <table class="table table-striped table-hover table-bordered" id="product-pricing-table">
                        <thead>
                            <tr>
                                <th>Title:</th>
                                <th>Model:</th>
                                <th>Price:</th>
                                <th>Quantity:</th>
                                <th>SKU:</th>
                                <th>UPC:</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if(isset($product) && $product->prices->count()<0)
                                @foreach($product->prices as $price)
                                    <tr class="alt">
                                        <td><input type="text" class="form-control" name="price[i]['title']" value="{!! $price->model !!}" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[i]['model']" value="{!! $price->model !!}" /></td>
                                        <td><input type="text" class="text-center form-control currency" name="price[i]['price']" value="{!! $price->price !!}" data-affixes-stay="false" data-prefix="$ " data-thousands="," data-decimal="." /> </td>
                                        <td><input type="text" class="text-center form-control" name="price[i]['quantity']" maxlength="4" value="{!! $price->quantity !!}" /></td>
                                        <td><input type="text" class="text-center form-control" name="prices[sku]" value="{!! $price->sku !!}" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[i]['upc']" maxlength="12" value="{!! $price->upc !!}" /></td>
                                   
                                    </tr>
                                    <tr class="alt">
                                        <td colspan="1" class="labelTextarea"><label>  <strong>Product Variation Details:</strong></label></td>
                                        <td colspan="5"> <textarea rows="3" class="form-control details-input" name="price[i]['alt_details']" value="{!! $price->alt_details !!}"></textarea></td>
                                    </tr>
                                    <tr class="spacer invis"><td colspan="5"></td></tr>
                                @endforeach
                            @else
                                    <tr class="alt">
                                        <td><input type="text" class="form-control" name="price[i]['title']" value="" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[i]['model']" value="" /></td>
                                        <td><input type="text" class="text-center form-control currency" name="price[i]['price']" placeholder="$0.00" data-affixes-stay="false" data-prefix="$ " data-thousands="," data-decimal="." /></td>
                                        <td><input type="text" class="text-center form-control" name="price[i]['quantity']" maxlength="4" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[i]['sku']" value="" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[i]['upc']" maxlength="12" value="636343" /></td>
                               
                                    </tr>

                                    <tr class="alt">
                                        <td colspan="1" class="labelTextarea"><label><strong>Product Variation Details:</strong></label></td>
                                        <td colspan="5"><textarea rows="3" class="form-control details-input" name="price[$i]['alt_details']" placeholder="add the details or difference here:"></textarea></td>
                                    </tr>
                                    <tr class="spacer invis"><td colspan="5"></td></tr>
                            @endif
                        </tbody>
                    </table>

16th September, 2016

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey

i added my files to a temporary repo if you need more of the code then i have put on this thread.

https://github.com/madsynn/laravelEcom.git

i have everything working but the pricing and the additional fields on the album photos. any help is greatly welcome.

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@ctomasz @Snapey

Thanks for the info but I am looking for an example of how to submit the requested form data into sub tables in my product store method.

something along the lines of this:

 if(!empty($productPricing)){
             foreach ($productPricing as $productPrice)
             {
                 Price::create([
                     'title' => $productPrice->title,
                     'price' => $productPrice->price,
                     'model' => $productPrice->model,
                     'sku' => $productPrice->sku,
                     'upc' => $productPrice->upc,
                     'quantity' => $productPrice->quantity,
                     'alt_details' => $productPrice->alt_details
                 ]);
             }
         }

The data is submitted form the create product form and needs to be submitted into a seperate database with id corresponding to the product itself.

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey Thank you for helping me understand that.

So if the only values i can put in the create method how do i add the values that are in arrays?

array:39 [▼
  "status" => "Available"                           // this one
  "manufacturer" => "The Company"                           // this one
  "office_status" => "Draft"
  "is_published" => "1"                         // this one
  "ispromo" => "0"                          // this one
  "name" => "name"                          // this one
  "subtitle" => "subtitle"                          // this one
  "categories" => array:1 [▶]                //inArray How do I add it to the db:table 
  "features_heading" => "features_heading"
  "details" => "details"                            // this one                         // this one
  "feature_name" => array:1 [▶]                //inArray How do I add it to the db:table 
  "useicon" => "1"
  "icon" => "icon-caret-right"
  "description" => "description"                            // this one
  "video_url" => "video_url"
  "slug" => "slug"                          // this one
  "caption" => array:1 [▶]                //inArray How do I add it to the db:table 
  "alt" => array:1 [▶]                //inArray How do I add it to the db:table 
  "photoinfo" => array:1 [▶]                //inArray How do I add it to the db:table 
  "use_main" => array:1 [▶]                //inArray How do I add it to the db:table 
  "use_thumb" => array:1 [▶]                //inArray How do I add it to the db:table 
  "use_gallery" => array:1 [▶]                //inArray How do I add it to the db:table 
  "model" => array:1 [▶]                //inArray How do I add it to the db:table 
  "price" => array:1 [▶]                //inArray How do I add it to the db:table 
  "quantity" => array:1 [▶]                //inArray How do I add it to the db:table 
  "sku" => array:1 [▶]                //inArray How do I add it to the db:table 
  "upc" => array:1 [▶]                //inArray How do I add it to the db:table 
  "alt_details" => array:1 [▶]
  "meta_title" => "meta_title"
  "meta_keywords" => "meta_keywords"
  "meta_description" => "meta_description"
  "facebook_title" => "facebook_title"
  "google_plus_title" => "google_plus_title"
  "twitter_title" => "twitter_title"
  "attribute_name" => array:1 [▶]                 //inArray How do I add it to the db:table 
  "product_attribute_value" => array:1 [▶]                //inArray How do I add it to the db:table 
  "tracking" => "tracking"
  "datalayer" => "datalayer"
  "_token" => "8RyZcfEXXkAd2iq3Hl0sU193jQ3HtlEeLXQXUiiB"
]

15th September, 2016

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey

Ok to clarify each product has a main price but can have prices added for different versions of the product. The different versions have different data. So each product can have many different prices depending on the version or variation.

Here is the pricing table to show what i mean.

<table class="table table-striped table-hover table-bordered" id="product-pricing-table">
                        <thead>
                            <tr>
                                <th>Title:</th>
                                <th>Model:</th>
                                <th>Price:</th>
                                <th>Quantity:</th>
                                <th>SKU:</th>
                                <th>UPC:</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if(isset($product) && $product->prices->count()<0)
                                @foreach($product->prices as $price)
                                    <tr class="alt">
                                        <td><input type="text" class="form-control" name="price[price_title]" value="{!! $price->model !!}" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[model]" value="{!! $price->model !!}" /></td>
                                        <td><input type="text" class="text-center form-control currency" name="price[price]" value="{!! $price->price !!}" data-affixes-stay="false" data-prefix="$ " data-thousands="," data-decimal="." /> </td>
                                        <td><input type="text" class="text-center form-control" name="price[quantity]" maxlength="4" value="{!! $price->quantity !!}" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[sku]" value="{!! $price->sku !!}" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[upc]" maxlength="12" value="{!! $price->upc !!}" /></td>
                                    </tr>
                                    <tr class="alt">
                                        <td colspan="1" class="labelTextarea"><label>  <strong>Product Variation Details:</strong></label></td>
                                        <td colspan="5"> <textarea rows="3" class="form-control details-input" name="price[alt_details]" value="{!! $price->alt_details !!}"></textarea></td>
                                    </tr>
                                    <tr class="spacer invis"><td colspan="5"></td></tr>
                                @endforeach
                            @else
                                    <tr class="alt">
                                        <td><input type="text" class="form-control" name="price[price_title]" value="" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[model]" value="" /></td>
                                        <td><input type="text" class="text-center form-control currency" name="price[price]" placeholder="$0.00" data-affixes-stay="false" data-prefix="$ " data-thousands="," data-decimal="." /></td>
                                        <td><input type="text" class="text-center form-control" name="price[quantity]" maxlength="4" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[sku]" value="" /></td>
                                        <td><input type="text" class="text-center form-control" name="price[upc]" maxlength="12" value="636343" /></td>
                                    </tr>
                                    <tr class="alt">
                                        <td colspan="1" class="labelTextarea"><label><strong>Product Variation Details:</strong></label></td>
                                        <td colspan="5"><textarea rows="3" class="form-control details-input" name="price[alt_details]" placeholder="add the details or difference here:"></textarea></td>
                                    </tr>
                                    <tr class="spacer invis"><td colspan="5"></td></tr>
                            @endif
                        </tbody>
                    </table>

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey

dd($request->price)

array:1 [▼
  0 => "2865575"
]

dd($request->prices)

null

dd($request->all())

array:39 [▼
  "status" => "Available"
  "manufacturer" => "The Grace Company"
  "office_status" => "Draft"
  "is_published" => "1"
  "ispromo" => "0"
  "name" => "name"
  "subtitle" => "subtitle"
  "categories" => array:1 [▶]
  "features_heading" => "features_heading"
  "details" => "details"
  "feature_name" => array:1 [▶]
  "useicon" => "1"
  "icon" => "icon-caret-right"
  "description" => "description"
  "video_url" => "video_url"
  "slug" => "slug"
  "caption" => array:1 [▶]
  "alt" => array:1 [▶]
  "photoinfo" => array:1 [▶]
  "use_main" => array:1 [▶]
  "use_thumb" => array:1 [▶]
  "use_gallery" => array:1 [▶]
  "model" => array:1 [▶]
  "price" => array:1 [▶]
  "quantity" => array:1 [▶]
  "sku" => array:1 [▶]
  "upc" => array:1 [▶]
  "alt_details" => array:1 [▶]
  "meta_title" => "meta_title"
  "meta_keywords" => "meta_keywords"
  "meta_description" => "meta_description"
  "facebook_title" => "facebook_title"
  "google_plus_title" => "google_plus_title"
  "twitter_title" => "twitter_title"
  "attribute_name" => array:1 [▶]
  "product_attribute_value" => array:1 [▶]
  "tracking" => "tracking"
  "datalayer" => "datalayer"
  "_token" => "8RyZcfEXXkAd2iq3Hl0sU193jQ3HtlEeLXQXUiiB"
]

Ok I am not getting how to get the price array returned or stored.

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey

You need to do this if you have duplicate field names in product and price, otherwise the model just takes the fields that are $fillable and ignores everything else

by fillable do you mean the fillable on all the models that are processing through the controller or just the main primary model. Does it look at them all the same or as all complete.

Example

├── models    ├── Product - $fillable = ['id', 'slug', 'ispromo', 'is_published', 'name', 'subtitle', 'details', 'description', 'status', 'thumbnail', 'photo_album', 'pubished_at', 'manufacturer', 'category_id'];    ├── Price - $fillable = ['product_id', 'price', 'model', 'sku', 'upc', 'quantity', 'alt_details', 'deleted_at'];    ├── ProductFeature - $fillable = ['feature_name', 'useicon', 'icon', 'created_at', 'updated_at'];    ├── ProductFeature - $fillable = ['attribute_name', 'attribute_value'];    └── ProductController = Combined $fillable from all above models?

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

ok that has a typo i didnt see it should have been

if(!empty($request->price)){
            foreach($request->prices as $productPrice){

                $price = new Price();
                $price->product_id = $product->id;
                $price->price =  $productPrice;
                $price->upc =  $productPrice;
                $price->model =  $productPrice;
                $price->quantity =  $productPrice;
                $price->sku =  $productPrice;
                $price->alt_details =  $productPrice;
                $product->prices()->save($price);
                //dd($price);
            }
        }

But im not sure if that is correct. The foreach($request->prices as $productPrice){ in the part (->prices) is refering to my relationship in my product model. Am i doing this right?

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

@Snapey @primordial Ok here is my complete store method, I am having trouble with 2 areas any help would be appreciated.

  1. pricing stores the same data in all fields
  2. album is not storing fields only the file
public function store(CreateProductRequest $request)
    {


//      /**
//       * Validate the submitted Data
//       */
        $this->validate($request, [
            'name' => 'required',
//          'manufacturer' => 'required',
//          'price' => 'required',
//          'details' => 'required',
//          'quantity' => 'required',
//          'categories' => 'required',
//          'thumbnail' => 'required|image',
//      ]);


        if($request->hasFile('album')){
            foreach($request->album as $photo){
                if($photo && strpos($photo->getMimeType(), 'image') === false){
                    return \Redirect()->back();
                }
            }
        }


        /**
         * Upload a new thumbnail and thumbnail2
         */
        $dest  = 'uploads/products/today/';
        $name  = str_random(11) . '_' . $request->file('thumbnail')->getClientOriginalName();
        $request->file('thumbnail')->move($dest, $name);

        $name2 = str_random(11) . '_' . $request->file('thumbnail2')->getClientOriginalName();
        $request->file('thumbnail2')->move($dest, $name2);
        //$product = $request->all();
        $input = $request->all();

         //dd($input);

        $input['thumbnail'] = '/' . $dest . $name;

        $input['thumbnail2'] = '/' . $dest . $name2;




        $product = Product::create($input, $request->except(
            'attribute_name',
            'product_attribute_value',
            'price',
            'sku',
            'quantity',
            'model',
            'upc',
            'alt_details',
            'feature_name',
            'use_icon',
            'icon',
            'photo_src',
            'alt',
            'caption',
            'photoinfo',
            'linkto',
            'use_main',
            'use_thumb',
            'use_gallery'
        ));





        if(!empty($request->price)){
            foreach($request->price as $productPrice){

                $price = new Price();
                $price->product_id = $product->id;
                $price->price =  $productPrice;
                $price->upc =  $productPrice;
                $price->model =  $productPrice;
                $price->quantity =  $productPrice;
                $price->sku =  $productPrice;
                $price->alt_details =  $productPrice;
                $product->prices()->save($price);
                //dd($price);
            }
        }

//      if($request->has('productPrices')){
//          foreach($request->productPrices as $price){
//              if(!empty($price['price'])){
//                  $product->prices()->create($price);
//              }
//          }
//      }


        /**
         * Upload Album Photos
         */
        if($request->hasFile('album')){
            foreach($request->album as $photo){
                if($photo){
                    $name = str_random(11) . "_" . $photo->getClientOriginalName();
                    $photo->move($dest, $name);

                    AlbumPhoto::create([
                        'product_id' => $product->id,
                        'photo_src' => "/" . $dest . $name,
                        'alt' => $photo->alt,
                        'caption' => $photo->caption,
                        'photoinfo' => $photo->photoinfo,
                        'linkto' => $photo->linkto,
                        'use_main' => $photo->use_main,
                        'use_thumb' => $photo->use_thumb,
                        'use_gallery' => $photo->use_gallery
                    ]);
                }
            }
        }


        /**
         * Linking the categories to the product
         */

        foreach($request->categories as $category_id){
            CategoryProduct::create(['category_id' => $category_id, 'product_id' => $product->id]);
        }

        /**
         * Linking the options to the product
         */

        if($request->has('options')){
            foreach($request->options as $option_details){
                if(!empty($option_details['name']) && !empty($option_details['values'][0])){
                    $option = Option::create([
                        'name' => $option_details['name'],
                        'product_id' => $product->id
                    ]);
                    foreach($option_details['values'] as $value){
                        OptionValue::create([
                            'value' => $value,
                            'option_id' => $option->id
                        ]);
                    }
                }
            }
        }

        if(!empty($request->attribute_name)){
            foreach($request->attribute_name as $key => $item){
                $productVariant = new ProductVariant();
                $productVariant->attribute_name = $item;
                $productVariant->product_attribute_value = $request->product_attribute_value[$key];
                $product->productVariants()->save($productVariant);
            }
        }

        if(!empty($request->feature_name)){
            foreach($request->feature_name as $feature){
                $productFeature = new ProductFeature();
                $productFeature->feature_name = $feature;
                $product->productFeatures()->save($productFeature);

            }
        }

        FlashAlert()->success('Success!', 'The Product Was Successfully Added');
        return \Redirect(getLang() . '/admin/products');
    }

I added except the product create command for all the fields that belong to other tables but not really sure what the function of this is for but thought it was worth a try.

madsynn left a reply on Help Understanding Validation • 1 year ago

@Snapey Thank you

But to make sure i am understanding what you are saying is to use the productcontroller to validate all of the product data?

this would as an example include the product, pricing, album, variations, options, and anything else correct.

So i would validate through the productcontroller but in the models i would clarify the fillable and casts for each correct?

I am testing this out and have a basic implementation so far but i am having issues using the pricing table data maybe you can take a look and see if you can see my error. https://laracasts.com/discuss/channels/laravel/relationship-not-returning-fields

madsynn started a new conversation Help Understanding Validation • 1 year ago

Can someone please help me with my understanding of validation. I have tried to find the answer for this question but have not been able to as of yet and I am hoping all of you might have my answer.

Lets say i have two models with two tables.

  1. Product::model

  2. Price::model

  3. products::table

  4. prices::table

I have fields from both that are used in my crud for products in my eCommerce build. My forms run through my Product involving the following:

PRODUCT FIELDS: name manufacturer details description

PRICE FIELDS: price model sku upc quantity alt_details

My question is do i put the validation to use in my ProductController like this:

 $this->validate($request, [
            'name' => 'required',
            'manufacturer' => 'required',
            'price' => 'required',
            'details' => 'required',
            'quantity' => 'required'
        ]);

or do i need to split them up and put them in a combined request like CreateProductRequest or put them in their corresponding models?

Does the flow of data make then look like one combined model / controller determined by the relationships or are they separate and need to be addressed that way.

Any help understanding this would be helpful and thank you in advance.

14th September, 2016

madsynn left a reply on Relationship Not Returning Fields • 1 year ago

ok I was able to get it to start saving but the same data is getting saved in all the fields.

        if(!empty($request->price)){
            foreach($request->price as $productPrice){

                $price = new Price();
                $price->product_id = $product->id;
                $price->price =  $productPrice;
                $price->upc =  $productPrice;
                $price->model =  $productPrice;
                $price->quantity =  $productPrice;
                $price->sku =  $productPrice;
                $price->alt_details =  $productPrice;
                $product->prices()->save($price);
                //dd($price);
            }
        }

madsynn started a new conversation Relationship Not Returning Fields • 1 year ago

Hello everyone, Hope you can help me.

Windows 10 / Homestead Laravel 5.1

I have a ecommerce project i am building and here is my problem.

I have the following tables:

  1. products
 Schema::create('products', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('status')->nullable();
            $table->string('availability')->default('Available');
            $table->string('slug')->nullable();
            $table->string('name')->nullable();
            $table->string('subtitle')->nullable();
            $table->string('manufacturer')->default('The Grace Company');
            $table->longText('details');
            $table->longText('description');

            $table->string('thumbnail')->nullable();
            $table->string('photo_album')->nullable();
            $table->dateTime('pubished_at')->index();
            $table->string('lang', 255);
            $table->timestamps();
            $table->softDeletes();
        });
  1. prices
    Schema::create('prices', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('product_id')->unsigned()->index();
            $table->decimal('price', 11, 2)->default('0.00');
            $table->string('model', 12)->nullable();
            $table->string('sku', 12)->default('000000');
            $table->string('upc', 13)->default('000000');
            $table->bigInteger('quantity')->default('99');
            $table->string('alt_details');
            $table->timestamps();
            $table->softDeletes();
            $table->engine = 'InnoDB';
            $table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');

        });

I have the following relationships product.php

    public function productPrice() {      return $this->hasMany(Price::class);    }

price.php

 public function product()    {        return $this->BelongsToMany(Product::class);    }

My problem is i cannot get my pricing to store to the alternate table pricing here is my controller store function.

public function store(Request $request) {
$this->validate($request, [
'name' => 'required',
]);
$dest = 'testing/';
$name  = str_random(4) . '_' . $request->file('thumbnail')->getClientOriginalName();
$request->file('thumbnail')->move($dest, $name);
$product = $request->all();
$product['thumbnail'] = '/' . $dest . $name;
$product = Product::create($product);

if ($request->has('productPrices')) {
foreach ($request->productPrices as $price){
if (!empty($price['price'])){
$price = Price::create($request->all());
}
}
}

foreach ($request->categories as $category_id)
        {
            CategoryProduct::create(['category_id' => $category_id, 'product_id' => $product->id]);
        }

FlashAlert()->success('Success!', 'The Product Was Successfully Added');

        return \Redirect(getLang() . '/admin/products');
}

I can store the product just fine but i cannot get it to store the product pricing table data.

any help would be greatly appreciated.

8th September, 2016

madsynn left a reply on Help Figuring Out My Elequent Relationships • 1 year ago

Here is the pricing form i am using to submit it.

<div class="row">
    <div class="col-md-12">
        <div class="adv-table editable-table ">
            <div class="clearfix">
                <div class="space15"></div>
                <table class="table table-striped table-hover table-bordered" id="product-pricing-table">
                    <thead>
                    <tr>
                        <th>Price:</th>
                        <th>Quantity:</th>
                        <th>Model:</th>
                        <th>SKU:</th>
                        <th>UPC:</th>

                    </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="text" class="text-center form-control currency" name="prices[0][price]" value="" data-affixes-stay="true" data-prefix="$ " data-thousands="," data-decimal="." /> </td>
                            <td><input type="text" class="text-center form-control" name="prices[0][quantity]" maxlength="4" value="" /></td>
                            <td><input type="text" class="text-center form-control" name="prices[0][model]" value="" /></td>
                            <td><input type="text" class="text-center form-control" name="prices[0][sku]" value="" /></td>
                            <td><input type="text" class="text-center form-control" name="prices[0][upc]" maxlength="12" value="636343" /></td>

                        </tr>
                    </tbody>
                </table>

                <button type="button" id="addRow" class="btn default">
                    Add New <i class="icon-plus"></i>
                </button>
            </div>
        </div>
    </div>
</div>

I also tried this one.

<div class="row">
    <div class="col-md-12">
        <div class="adv-table editable-table ">
            <div class="clearfix">
                <div class="space15"></div>
                <table class="table table-striped table-hover table-bordered" id="product-pricing-table">
                    <thead>
                    <tr>
                        <th>Price:</th>
                        <th>Quantity:</th>
                        <th>Model:</th>
                        <th>SKU:</th>
                        <th>UPC:</th>

                    </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="text" class="text-center form-control currency" name="price[]" value="" data-affixes-stay="true" data-prefix="$ " data-thousands="," data-decimal="." /> </td>
                            <td><input type="text" class="text-center form-control" name="quantity[]" maxlength="4" value="" /></td>
                            <td><input type="text" class="text-center form-control" name="model[]" value="" /></td>
                            <td><input type="text" class="text-center form-control" name="sku[]" value="" /></td>
                            <td><input type="text" class="text-center form-control" name="upc[]" maxlength="12" value="636343" /></td>

                        </tr>
                    </tbody>
                </table>

                <button type="button" id="addRow" class="btn default">
                    Add New <i class="icon-plus"></i>
                </button>
            </div>
        </div>
    </div>
</div>

The second one allowed me to save the price into the database but it saved the price into all fields not just price.

madsynn started a new conversation Help Figuring Out My Elequent Relationships • 1 year ago

Ok i have been working on trying to figure this out for a few weeks now so i thought i would ask for advice.

The problem I am having is in the store function in the controller and the retrieval of the prices for each product. I have all my others storing just fine but the pricing seems to be eluding me. I cannot get them to save to the database or pull the data in the view on the front-end.

Format I have tried using for retrieving prices on the single-product.blade.php is as follows. I have tried retrieval in a foreach loop and without. I have tried blade injecting the pricing also but I cannot seem to see the problem.

Any help would be greatly appreciated.

{!! $product->prices->price !!}
{!! $product->prices->quantity !!}
{!! $product->prices->model !!}
{!! $product->prices->sku !!}
{!! $product->prices->upc !!}
{!! $product->prices->details !!}


**I have 8 tables:**

1. products
2. product_features
3. product_variations
4. options
5. option_value
6. prices
7. combos
8. combo_product

So far I have them all working except prices and combos.

TABLES:

> prices, products, price_product, combos

```mysql
Schema::create('prices', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('product_id')->unsigned()->index();
            $table->decimal('price', 11, 2)->nullable();
            $table->string('model', 12)->nullable();
            $table->string('sku', 12);
            $table->string('upc', 13);
            $table->integer('quantity');
            $table->text('detials');
            $table->timestamps();
            $table->softDeletes();
            $table->engine = 'InnoDB';
            $table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');
        });

        Schema::create('products', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('status')->nullable();
            $table->string('office_status')->nullable();
            $table->string('availability')->default('Available');
            $table->string('slug')->nullable();
            $table->boolean('ispromo')->default(0);
            $table->boolean('is_published')->default(1);
            $table->string('name')->nullable();
            $table->string('subtitle')->nullable();
            $table->string('manufacturer');
            $table->longText('details');
            $table->longText('description');
            $table->string('thumb')->nullable();
            $table->string('photo_album')->nullable();
            $table->dateTime('pubished_at')->index();
        });

Schema::create('price_product', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('price_id');
            $table->unsignedInteger('product_id');

            $table->timestamps();
            $table->engine = 'InnoDB';
            $table->primary(['price_id', 'product_id']);
            $table->foreign('price_id')->references('id')->on('prices')->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');

        });

        Schema::create('combos', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('status')->nullable();
            $table->string('office_status')->nullable();
            $table->string('availability')->default('Available');
            $table->decimal('combo_price', 11, 2)->nullable();
            $table->integer('number_included_products')->nullable();
            $table->string('upc', 13)->nullable();
            $table->string('sku')->nullable();
            $table->string('name')->nullable();
            $table->string('subtitle')->nullable();
            $table->string('manufacturer');
            $table->longText('details');
            $table->longText('description');
            $table->string('slug')->nullable();
            $table->boolean('ispromo')->default(0);
            $table->boolean('is_published')->default(1);

            $table->timestamps();
            $table->softDeletes();
            $table->engine = 'InnoDB';
        });

        Schema::create('combo_product', function (Blueprint $table)
        {
            $table->increments('id');
            $table->decimal('price', 11, 2)->nullable();
            $table->string('sku');
            $table->string('upc', 13);
            $table->longText('details');
            $table->integer('product_id')->unsigned()->index();
            $table->integer('combo_id')->unsigned()->index();
            $table->timestamps();
            $table->engine = 'InnoDB';
            $table->primary(['combo_id', 'product_id']);
            $table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('combo_id')->references('id')->on('combos')->onUpdate('cascade')->onDelete('cascade');
        });

Model: price.php

    protected $guarded = ['id'];
    protected $table = 'prices';
    public $fillable = [
        'product_id',
        'price',
        'model',
        'sku',
        'upc',
        'quantity',
        'details',
        'created_at',
        'updated_at'
    ];
    protected $casts = [
        'product_id' => 'integer',
        'price'      => 'string',
        'model'      => 'string',
        'sku'        => 'string',
        'upc'        => 'string',
        'quantity'   => 'string',
        'details'   => 'string'
    ];
    public static $rules = ['price' => 'required'];
    public function getPriceAttribute($price) {return '$' . number_format($price, 2, '.', ''); }
    public function products() {return $this->belongsToMany(Product::class, 'price_product'); }
    public function product() {return $this->belongsTo(Product::class, 'price_product'); }

Model: product.php

    protected $table = 'products';
    protected $guarded = ['id'];
    protected $fillable = ['id', 'slug', 'ispromo', 'is_published', 'name', 'details',         'description', 'status', 'thumbnail', 'thumbnail2', 'photo_album', 'pubished_at', 'manufacturer', 'subtitle', 'office_status', 'availability'];
   protected $casts = [
       'slug'              => 'string',
       'ispromo'           => 'boolean',
       'is_published'      => 'boolean',
       'availability'      => 'string',
       'manufacturer'      => 'string',
       'status'            => 'string',
       'office_status'     => 'string',
       'name'              => 'string',
       'subtitle'          => 'string',
       'details'           => 'string',
       'description'       => 'string',
       'thumb'         => 'string',
       'photo_album'       => 'string'
   ];
    public function photos() {return $this->hasMany(AlbumPhoto::class); }
    public function options() {return $this->hasMany(Option::class); }
    public function price() {return $this->belongsToMany(Price::class, 'price_product'); }
    public function prices() {return $this->belongsToMany(Price::class, 'price_product'); }
    public function productVariants() {return $this->hasMany(ProductVariant::class); }
    public function productFeatures() {return $this->hasMany(ProductFeature::class); }
    public function combo() {return $this->belongsToMany(Combo::class, 'combo_product'); }

> ProductController.php
namespace App\Http\Controllers;
use App\Models\ComboProduct;
use App\Models\Combo;
use App\Models\PriceProduct;
use App\Repositories\Category\CategoryInterface;
use App\Repositories\Category\CategoryRepository;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\CategoryProduct;
use App\Models\AlbumPhoto;
use App\Models\Section;
use App\Models\Cart;
use App\Models\Option;
use App\Models\OptionValue;
use App\Models\ProductFeature;
use App\Models\ProductVariant;
use App\Models\OrderProduct;
use App\Models\Price;
use App\Models\Category;


class ProductController extends Controller
{
    protected $product;
    protected $category;
    protected $sections;
    protected $prices;

    public function __construct(Product $product, Section $sections, CategoryInterface $category, Price $prices)
    {
        $this->product = $product;
        $this->category = $category;
        $this->section = $sections;
        $this->price = $prices;
    }

    public function index()
    {

    }

    public function show($id, $slug = Null)
    {
    }

    protected function flatten($array) 
    {
        $result = [];
        foreach($array as $key=>$value) {
            if (is_array($value)) {
                $result = $result + $this->flatten($value, $key);
            } else {
                $result[$key] = $value;
            }
        }
        return $result;
    }

    public function store(Request $request)
    {

        $this->validate($request, [
            'name' => 'required',
            'manufacturer' => 'required',
            'price' => 'required',
            'details' => 'required',
            'quantity' => 'required',
            'categories' => 'required',
            'thumb' => 'required|image',
        ]);

         if ($request->hasFile('album')) {
            foreach ($request->album as $photo) {
                if ($photo && strpos($photo->getMimeType(), 'image') === false) {
                    return \Redirect()->back();
                }
            }
        }

        $dest = "content/images/";

        if (!empty($product['thumb'])) {
            $name = str_random(11)."_".$request->file('thumb')->getClientOriginalName();
            $request->file('thumb')->move($dest, $name);
            $product = $request->all();
            $product['thumb'] = "/" . $dest . $name;
        }

        $product = Product::create($product);

      /**
         * Upload Album Photos
         */
        if ($request->hasFile('album')) {
            foreach ($request->album as $photo) {
                if ($photo) {
                    $name = str_random(11) . "_" . $photo->getClientOriginalName();
                    $photo->move($dest, $name);
                    AlbumPhoto::create([
                        'product_id' => $product->id,
                        'photo_src' => "/" . $dest . $name
                    ]);
                }
            }
        }


        /**
         * Linking the categories to the product
         */
        foreach ($request->categories as $category_id) 
        {
            CategoryProduct::create(['category_id' => $category_id, 'product_id' => $product->id ]); 
        }

        if (!empty($request->price))
        {
           foreach ($request->prices as $price)
           {
               $productPrice = new Price();
               $productPrice->price = $price;
               $productPrice->quantity = $price;
               $productPrice->model = $price;
               $productPrice->sku = $price;
               $productPrice->upc = $price;
               $productPrice->product_id = $product->id;

 //$productPricing = $request->input('products.0.prices.0.price');
                    // $productPricing = $request->input('price');
                    // $productPricing = $request->input('quantity');
                    // $productPricing = $request->input('model');
                    // $productPricing = $request->input('sku');
                    // $productPricing = $request->input('upc');

               $product->prices()->save($productPrice);
           }
        }


        /**
         * Linking the options to the product
         */
        if ($request->has('options')) {
            foreach ($request->options as $option_details) {
                if (!empty($option_details['name']) && !empty($option_details['values'][0])) {
                    $option = Option::create([
                                'name' => $option_details['name'],
                                'product_id' => $product->id
                    ]);
                    foreach ($option_details['values'] as $value) {
                        OptionValue::create([
                            'value' => $value,
                            'option_id' => $option->id
                        ]);
                    }
                }
            }
        }

        if (!empty($request->attribute_name)) {
            foreach ($request->attribute_name as $key => $item) {
                $productVariant = new ProductVariant();
                $productVariant->attribute_name = $item;
                $productVariant->product_attribute_value = $request->product_attribute_value[$key];
                $product->productVariants()->save($productVariant);
            }
        }
 
        if (!empty($request->feature_name)) {
            foreach ($request->feature_name as $feature) {
                $productFeature = new ProductFeature();
                $productFeature->feature_name = $feature;
                $product->productFeatures()->save($productFeature);

            }
        }

        $product->save();


        FlashAlert()->success('Success!', 'The Product Was Successfully Added');

        return \Redirect(getLang().'/admin/products');
    }

    private function getProductVariants($variants = [])
    {
        if (isset($variants))
        {
            $variants = array_map(
                function ($v)
                {
                    return explode(':', $v);
                },
                explode(',', $variants)
            );
        }
        return $variants;
    }

    private function getProductFeatures($features = [])
    {
        if (isset($features)) {
            $features = array_map(
                function ($v) {
                    return explode(':', $v);
                },
                explode(',', $features)
            );
        }
        return $features;
    }

    private function getPrices($prices = [])
    {
        if (isset($prices)) {
            $prices = array_map(
                function ($v) {
                    return explode(':', $v);
                },
                explode(',', $prices)
            );
        }
        return $prices;
    }

19th July, 2016

madsynn left a reply on Uploader Help / Dropzone.js • 1 year ago

@snapey Thank you I finally got it working!!

15th July, 2016

madsynn left a reply on Uploader Help / Dropzone.js • 1 year ago

@Snapey so something along the lines of

Product::create($request->all());
    flash()->success('Success!', 'Your product has been created');
    return Redirect::route('product.edit', [$product->id]);
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.