bigweld86

bigweld86

Member Since 1 Year Ago

Experience Points 6,760
Experience Level 2

3,240 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 58
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.

03 Feb
3 months ago

bigweld86 left a reply on Return Inserted Row From Model

@JLRDW - @jlrdw that's the point. What I wanna do is returned the one I just inserted, I mean, not the last inserted one but particularly the one the I just inserted. Haven't tried outputting what comes back from

self::create($data)

but I hope @staudenmeir is right.

02 Feb
3 months ago

bigweld86 started a new conversation Return Inserted Row From Model

Hi.

Let's say I just created a row from within my model in certain method:

self::create($data);

is there a way to return the object (row) upon creation without having to perform a new get query? I simply want an insert and return.

Thanks

12 Dec
5 months ago

bigweld86 left a reply on Php 7.1 Return Type-hint Failing In Laravel 5.7

@SERGIU17 - Yes sir! That made the trick! Thanks a lot

11 Dec
5 months ago

bigweld86 left a reply on Php 7.1 Return Type-hint Failing In Laravel 5.7

@SERGIU17 - Nope, that's not going to work, I tried it already and I got the same error:

Return value of App\Http\Controllers\ProductsController::index() must be an instance of App\Http\Controllers\View, instance of Illuminate\View\View returned

bigweld86 left a reply on Php 7.1 Return Type-hint Failing In Laravel 5.7

@SERGIU17 - When I run:

gettype(view('products.index', ['products' => $products])) 

i get back 'object'. You're right, view() returns an instance of view which is basically an object. But ok, how do I enforce the return type to be an 'instance of View'? Again, this was working before, not sure why changed so it's breaking now :(

bigweld86 started a new conversation Php 7.1 Return Type-hint Failing In Laravel 5.7

I just cloned a repository for a project I was working on. Don't quite remember the specifics of the previous machine it was running on but on this one it's using php 7.1 and I upgraded to Laravel 5.7. The issue is that in my previous machine, this piece of code was working:

class ProductsController extends Controller
{
    public function index() : Object
    {
        $products = Product::all();
        return view('products.index', ['products' => $products]);
    }
}

Notice the Object return type.

After running migrations and everything else, when accessing index I'm getting the following error in the new machine:

Return value of App\Http\Controllers\ProductsController::index() must be an instance of App\Http\Controllers\Object, instance of Illuminate\View\View returned

which is related to the return type hint being Object. How do I know that? Because if I remove it everything works like charm.

Why is that happening?

18 Sep
8 months ago

bigweld86 started a new conversation Validating A Number Greater Than Zero Is Failing

I gotta validate a price field which needs to be greater than zero (0.01 is valid) so I have the following validation:

$request->validate([
            'product_price' => 'required|numeric|gt:0',
        ]);

The problem is that when I enter a string in the 'product_price' field I'm getting an error:

InvalidArgumentException The values under comparison must be of the same type

why is that? I mean, I'm checking that it should be numeric before even checking that it's > 0

03 Sep
8 months ago

bigweld86 left a reply on Database Tables Deleted After Running Phpunit Test

@Tray2 tried what you mentioned but didn't work. How can I specify which phpunit.xml phpunit should use? Thanks

bigweld86 left a reply on Database Tables Deleted After Running Phpunit Test

Indeed I had it, but after commenting it out I'm still getting the same outcome

bigweld86 started a new conversation Database Tables Deleted After Running Phpunit Test

Hi. Every time I run a test all my database tables (except for the migrations table) are being deleted and I have to run the migrations again. For instance, if I have the following tables:

migrations users tableA tableB

after running:

phpunit --filter user_can_view_a_record ViewRecordTest tests/Feature/ViewRecordTest.php

my tables are deleted and I end up with just the migrations table.

I'm using MySQL as database and according to the configuration I have set up the tests are being running in memory:

database.php

'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            //'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'database' => ':memory:',
            'prefix' => '',
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
            'sticky' => true
        ],
]

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="DB_CONNECTION" value="sqlite" />
        <env name="DB_DATABASE" value=":memory:" />
    </php>
</phpunit>

Thanks

02 Sep
8 months ago

bigweld86 started a new conversation Polymorphic Relationships For Online Store

I’ve got a master table called Product with the following columns:

id
product_id
product_type
name
price
in_stock
upc

Where ’id' and 'product_id' are unique (id is the PK)

I’ll have other tables for different kinds of products (types). All these other tables will have Product’s properties plus Other properties on their own depending on the type of product (I.e clothing, records, etc).

So I created a Product model using Polymorphic relationships as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Product extends Model
{
    protected $fillable = [
        'product_id',
        'product_type',
        'name',
        'price',
        'in_stock',
        'upc'
    ];

    public function categorizable()
    {
        return $this->morphTo();
    }
}

And, for instance, a records model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Record extends Model
{
    protected $fillable = [
        'artist_id',
        'title',
        'label',
        'code',
        'format',
        'number_of_discs',
        'image',
        'description'
    ];

    public function products()
    {
        return $this->morphMany('\App\Product', 'categorizable');
    }

    public function artist()
    {
        return $this->belongsTo(Artist::class);
    }

    public function track()
    {
        return $this->hasMany(Track::class);
    }

    public function getItemDetails(int $itemId): array {
        
    }

}

Whereas the columns for record are:

id
artist_id
product_id
title
label

This is the best way I could think of relating these tables.

My questions are:

  1. Is there a better approach to this specific problem?
  2. In this case (using polymorphic relationships), how would I insert a product?
  3. How could I query a product in order to return data from Both product table and record table? I mean, not a raw query Since that I can do, but how to perform this query using Eloquent?

Thanks

01 Sep
8 months ago

bigweld86 left a reply on Pass Argument To Factory And Call Different Factory File From A Factory

Hey, thanks! Just a couple things:

  1. Should I leave 'type' empty (or even define it) in the main factory closure since it'll be populated from the state closure depending on the passed type?

  2. Is it possible to invoke a different factory that lives in a different file from state? Let's say I passed:

['type' = 'clothing']

then after creating the Product_master record, can I invoke a 'clothing' factory (a different file) from the clothing state?

Thanks

bigweld86 started a new conversation Pass Argument To Factory And Call Different Factory File From A Factory

Hi.

I'm trying to do the following: I've got a Product master table with general info about certain products:

ProductMasterFactory:

<?php

use Faker\Generator as Faker;

$factory->define(App\Product_master::class, function (Faker $faker) {
    return [
        'id' => factory('App\Product_master')->create()->id,
        'product_id' => $faker->unique()->randomNumber($nbDigits=5),
        'type' => '',
        'name' => $faker->sentence($nbWords = 2, $variableNbWords = true),
        'price' => $faker->numberBetween($min=500, $max=2000),
        'in_stock' => $faker->randomElement($array=[true, false]),
        'upc' => $faker->isbn13,
    ];
});

There are multiple types of product, so what I want to do is to pass a parameter to the Factory indicating the product type which will be assigned to 'type', then create the product and with the returned id (and from ProductMasterFactory) call a different located in a different factory file depending on the type passed, is it possible to do?

Thanks

16 Aug
9 months ago

bigweld86 left a reply on Laravel Migration Not Working On Mac OS X With MySQL 8.0.11

Am not using Docker and MySQL Server is running. Thanks

15 Aug
9 months ago

bigweld86 started a new conversation Laravel Migration Not Working On Mac OS X With MySQL 8.0.11

I'm running

php artisan migrate:install

on MacOS X 10.13.6 with MySQL 8.0.11 and Laravel 5.5 and I'm getting the following:


In PDOConnection.php line 46: SQLSTATE[HY000] [2006] MySQL server has gone away

In PDOConnection.php line 46: PDO::__construct(): Unexpected server respose while doing caching_sha2 auth : 21

This is my .env section for the DB:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=store
DB_USERNAME=root
DB_PASSWORD=abcd1234

I have access to MySQL through the terminal using those credentials (root as username and abcd1234 as password). Not quite sure what's failing.

Thanks.

13 May
1 year ago

bigweld86 left a reply on OOP Design: Abstract Class Design Vs Regular Inheritance

@jlrdw I understand your point. I want to do it for the sake of code maintenance/readability. Records have a set of specific properties unique to them so I personally find more clear to have a separate table. Other products can share a single product table.

Furthermore, I'd like to get into good designing practices and figure out how to organize my code is part of that.

bigweld86 started a new conversation OOP Design: Abstract Class Design Vs Regular Inheritance

I'm designing a simple system to store records (vinyl records) data and some other general items related to records (sleeves, record cleaners, etc).

Since 90% of the data is gonna be vinyl records and the other 10% other items, I thought about separating them into two classes: Records and Items. Bear in mind that although different at the end both are products with certain things in common like price, quantity, etc.

I have doubts about whether I should create an abstract class, say Item, and two classes extending Item: Records and NonMusicalProducts. Something like this:

abstract class Item extends Model {

    static function getItemPrice($itemId, $type='record'){
        $result = 0;
        // query record table if type is record, otherwise query nonmusicalproduct table
        return $result;
    }

    abstract function getItemDetails();
}

Whereas Record:

class Record extends Item {

   protected $fillable = [
        'artist_id',
        'title',
        'label',
        'price',
        'in_stock',
        'code',
        'format',
        'number_of_discs',
        'image',
        'description'
    ];

    public function artist()
    {
        return $this->belongsTo(Artist::class);
    }

    public function track()
    {
        return $this->hasMany(Track::class);
    }

    static function getItemDetails($id) {
        // query DB and return record details
    }
}

and NMProduct

class NMProduct extends Item {
    static function getItemDetails($id) {
        // query DB and return NMProduct details
    }
}

Would it be ok to define both methods in NMProduct and Record as static? I'm not always gonna access that method from an object.

The other option is to have only an Item class and a Record class that would inherit from item but I have come to a point where it doesn't seem right, especially when trying to get the details:

class Item extends Model { function getItemDetails($id, $type){ if ($type == 'record') { // query record table using id } if ($type == 'nmproduct'){ // query nmproduct table } }


It feels wrong because I think that it would be more appropriated to go to the record class to get record details since the columns would be different to those columns in nmproduct. Doing it in one parent class feels that defeat the purpose of OO.

Or the last option that I can think of, would be one single class Item:

class Item extends Model {

 function getItemPrice($id, $type) {
     // if type is record then query the record table
     // if type is nmproduct then query the nmproduct table
 }

 function getItemDetails($id, $type) {
     // if type is record then query the record table
     // if type is nmproduct then query the nmproduct table
 }

}


Again, this last option doesn't feel right since too many non-related things will be condensed in one single class. The record attributes (ie artist_id, number_of_discs, etc) are different than nmproduct.

Eventually I'll have a cart where products will be added. Cart items will have a type and an id. So far so good, but when retrieving the details for cart items I'll have to do something like a switch statement to retrieve items of a particular type:

switch($type) { case 'record': // create a record object and retrieve the data case 'nmproduct': // create a nmproduct obj and retrieve the data }


Don't feel like a good programing practice because the switch statement could get really big if decide to implement future items.

What would be the best approach to this issue?
09 Apr
1 year ago

bigweld86 left a reply on View Composer Not Working

@Snapey I just did it, then refreshed the page but the issue still persists

bigweld86 left a reply on View Composer Not Working

@Snapey I tried both, one in ComposerServiceProvider's booth method and other in CartComposer's both __construct and compose methods but didn't work

bigweld86 left a reply on View Composer Not Working

How can I know whether at least the service provider is being fired? I tried adding a dd() statement in booth() but didn't work

bigweld86 left a reply on View Composer Not Working

Here's the structure:

layouts.app.blade.php

@include('layouts.header')

<div class="ui container app-container">
    @yield('content')
</div>

@include('layouts.footer')

layouts.header.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta id="csrf_token" name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'TMP') }}</title>

    <!-- Styles -->
    <link href="{{ asset('semantic/semantic.min.css') }}" rel="stylesheet">
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>

@include('layouts.navbar')

layouts.navbar.blade.php

<nav class="ui borderless menu huge">
    <div class="ui container grid">

    <div class="right menu">
          <a href="" class="ui dropdown item">
            @include('layouts.cart')
          </a>
          @if (Auth::check())
            <div href="" class="ui dropdown item">
              @if (!empty(Auth::user()->preferred_name))
                {{ Auth::user()->preferred_name }}
              @else
                {{ Auth::user()->first_name }}
              @endif
              <i class="dropdown icon"></i>
              
               <div class="menu">
                <a href="#" class="item"><i class="user icon"></i> Settings</a>
                <a href="{{ route('logout') }}" class="item"><i class="sign out icon"></i> Logout</a>
              </div> 
            </div>
          @else
            <a href="{{ route('register') }}" class="item">Register</a>
            <a href="{{ route('login') }}" class="item">Login</a>
          @endif
        </div>
      </div>
   </div>
</div>

And the piece where I'm trying to inject data into:

layouts.cart.blade.php

<div class="cart-menu">
  <i class="black large cart icon"></i>
  @if (/*isset($cart->total_items) &&*/ $cart->total_items > 0)
  <div class="floating ui red label cart-items-badge">{{ $cart->total_items }}</div>
  @endif
</div>

bigweld86 left a reply on View Composer Not Working

@neilherbertuk yes I did. I forgot to mention it. I added to the providers array:

App\Providers\ComposerServiceProvider::class,

bigweld86 started a new conversation View Composer Not Working

Hello. I've created the following View Composer:

Http\Providers\ComposerServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(
            'layouts.cart',
            'App\Http\ViewComposers\CartComposer'
        );
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Http\ViewComposers\CartComposer

<?php

namespace App\Http\ViewComposers;

use Iluminate\View\View;
use App\Order;

class CartComposer
{
    public cartDetails = null;

    public function __construct()
    {
        //dd('here1');
        $orderToken = session('o_token');
        $this->cartDetails = Order::getOrderDetails($orderToken);
    }

    public function compose(View $view)
    {
        //dd('here2');
        $view->with('cart', ['total_items' => 7]);
    }
}

Just for the sake of testing, I'm returning a hardcoded array ['total_items' => 7]

And now my view which is @included in my header.blade.php:

views\layouts\cart.blade.php

<div class="cart-menu">
  <i class="black large cart icon"></i>
  @if (/*isset($cart->total_items) &&*/ $cart->total_items > 0)
  <div class="floating ui red label cart-items-badge">{{ $cart->total_items }}</div>
  @endif
</div>

When I access my page I'm getting a 'Page is Not Responding' error. I can't even see the Laravel error.

Any suggestion? Thanks

02 Apr
1 year ago

bigweld86 left a reply on Auth::user() Is Null When Trying To Get User Using $this->actingAs() Or $this->be()

@rin4ik you're right sir. I was printing out in the wrong place (must be fatigue). Anyway, thank you so much for pointing out the error!!

bigweld86 left a reply on Auth::user() Is Null When Trying To Get User Using $this->actingAs() Or $this->be()

Why? how would that affect the result? I cannot do it, this is the route that it needs to go to, [email protected] is already assigned to something else.

bigweld86 left a reply on Auth::user() Is Null When Trying To Get User Using $this->actingAs() Or $this->be()

Yes it does:

$test = factory(App\User::class)->create();
=> App\User {#790
     first_name: "Heber",
     last_name: "O'Keefe",
     preferred_name: "Bert",
     email: "[email protected]",
     receive_newsletter: false,
     updated_at: "2018-04-02 07:46:50",
     created_at: "2018-04-02 07:46:50",
     id: 2,
   }

bigweld86 started a new conversation Auth::user() Is Null When Trying To Get User Using $this->actingAs() Or $this->be()

Hello. I'm currently running a test which is supposed to retrieve some data from an ajax call.

The test looks something like:

/** @test **/
public function myTest()
{
   $user = factory(User::class)->create();
   $this->json('POST', "/orders/", [
            'item_id' => 32,
            ]);
   
   $response = $this->actingAs($user, 'web')
                         ->json('GET', "/orders/", ['X-Requested-With' => 'XMLHttpRequest']);

   // and then all the assertions
}

Route:

Route::get('/orders/', '[email protected]');

And before continuing with the rest I just decided to make sure that user was logged in by just printing its content in the controller:

public function store(Request $request)
{
        dd(auth()->user());
        dd(Auth::user());
}

but I'm getting null.

I also tried:

$this->actingAs($user);
$this->be($user);

In order to run my other tests without getting issues regarding the csrf token I added to the top of my code the following:

use WithoutMiddleware;

Don't know whether the problem might be related to that, but once again, cannot remove it since I'll get issues with the csrf token.

Any suggestions/help would be greatly appreciated.

25 Mar
1 year ago

bigweld86 started a new conversation Running An Update Statement Within A Model

If I'm running a update statement within a model do I have to get the instance of that model again? or can I simply do something like $this->update()?

Meaning:

class MyModel extends Model {

    public function test($id)
    {
        $obj = MyModel::find($id);
        $obj->update(['myField' => 'test']);
    }
}

or there is any 'simplified' way of doing it, since the method will be called from an existing instance of the object? ie:

class MyModel extends Model {

    public function test()
    {
        $this->update(['myField' => 'test']);
    }
}

Thanks

bigweld86 left a reply on Retrieving Elements Of Relationship Not Working

Never mind, I figure it out (although not sure it that would be the right way):

public function updateTotal(): void {
        var_dump(orderItem::get());
    }

Thanks.

bigweld86 started a new conversation Retrieving Elements Of Relationship Not Working

Hi. I've got the following Models:

Order

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\orderItem;

class Order extends Model
{
    protected $fillable = ['user_id'];

    public function orderItems()
    {
        return $this->hasMany(orderItem::class);
    }

    public function addOrderItem(array $item, int $orderId): void {
        orderItem::create($item);
        $this->updateTotal();
    }


    public function updateTotal(): void {
        var_dump($this->orderItems);
        
    }
}

orderItem

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class orderItem extends Model
{
    protected $fillable = [
        'order_id',
        'item_id',
        'type',
        'quantity',
        'price',
        'subtotal'
    ];

    public function order()
    {
        return $this->belongsTo(Order::class);
    }
}

If I create an instance of Order and add items to it, I'm able to perform the following in order to retrieve all the orderItems associated to an order:

    // Retrieve cart for that user
        $cart = Order::where('user_id', $user->id)->first();
        
        // Retrieve existing items in cart
        $cart_items = $cart->orderItems;

I'm trying to to the same thing (retrieve all orderItems associated to an order) within the Order model:

public function updateTotal(): void {
        var_dump($this->orderItems);
        
    }

Why is going on?

Thanks

16 Mar
1 year ago

bigweld86 left a reply on Model Access In Laravel > 5

@shez1983 neither $cart->orderItems()->get() nor $cart->orderItems worked

bigweld86 started a new conversation Model Access In Laravel > 5

First of all, I'm new to Laravel. I come from Codeigniter where you can have something similar to:

class Test_Model extends CI_Model {

public function test_method($a, $b){ return $a * $b; } }

class Test_Controller extends CI_Controller {

public function __construct(){ $this->load->model('Test'); }

public function method1() { $z = $this->Test->test_method(3,4); } } As you can see, the model was loaded and all it's methods were available. In my opinion it's pretty straightforward.

Now, I've got the following in Laravel:

namespace App;

use Illuminate\Database\Eloquent\Model;

// Order Model class Order extends Model { protected $fillable = ['user_id'];

public function orderItems()
{
    return $this->hasMany(orderItem::class);
}

}

// orderItem model namespace App; use Illuminate\Database\Eloquent\Model; class orderItem extends Model { protected $fillable = [ 'order_id', 'item_id', 'type', 'quantity', 'price', 'subtotal' ];

public function order()
{
    return $this->belongsTo(Order::class);
}

}

// Orders Controller namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Order; use App\orderItem; class OrdersController extends Controller { private $orderId;

public function store(Request $request)
{
    // check if there's already a cart [order] for this user, if not create one
    $this->orderId = Order::where('user_id', $request->json('user_id'))->get(['id']);
    $item = [
        'item_id' => $request->json('item_id'),
        'type' => $request->json('type'),
        'quantity' => $request->json('quantity'),
        'price' => $request->json('price'),
    ];

    if (!$this->orderId->count()){
        $this->orderId = Order::insertGetId([
            'user_id' => $request->json('user_id')
        ]);
    }

    $orderItem = new Order();
    $orderItem->addOrderItem($item, $this->orderId);
}

} Two questions I've got:

Is there a simpler or cleaner (not saying that creating a new obj is not clean) to access the Order model methods (such as done in Codeigniter)?

I've learnt a little bit about how to establish relationships between models in Laravel. I've got two other tables name Record and Artist respectively (a 1 to many relationship) and I can do the following:

$record = Record::findOrFail($id);
$record['artist_name'] = $record->artist->name;

but when I try to do the same with the Order and orderItem (also a 1 to many relationship) it doesn't work:

$cart = Order::where('user_id', $user->id)->get();

// Retrieve existing items in cart
$cart_items = $cart->orderItems();

Why is that?