bigweld86

bigweld86

Member Since 2 Years Ago

Experience Points
9,410
Total
Experience

590 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
70
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 2
9,410 XP
Jun
22
3 weeks ago
Jun
21
3 weeks ago
Activity icon

Replied to Laravel Accessor Is Returning The Whole Object Instead Of A Single Field

oh, my mistake. Any way around this? I mean, it's not hurting anything but doesn't look clean to me and I'd like to fix it

Activity icon

Replied to Laravel Accessor Is Returning The Whole Object Instead Of A Single Field

Hi Snapey. I performed the suggested changes but no difference at all, still getting the same result

Activity icon

Replied to Laravel Accessor Is Returning The Whole Object Instead Of A Single Field

Hi Michael. I performed the suggested changes but no difference at all, still getting the same result

Activity icon

Started a new Conversation Laravel Accessor Is Returning The Whole Object Instead Of A Single Field

I've got the following relationship between MenuItem and Category:

Menu Item Model

    public function category()
        {
            return $this->belongsTo('App\Models\Category');
        }
    
    public function getCategoryNameAttribute()
        {
            return $this->attributes['category_name'] = $this->category->name;
        }

Category Model

    public function menuItems()
        {
            return $this->hasMany('App\Models\MenuItem');
        }

Now, from my controller, when returning a list of all menu items I want to return category_name along with the results. As you noticed in the code above I created an accessor getCategoryNameAttribute to get the name.

The method that returns a list of all menu items in my controller is:

    public function index()
        {
            $menuItems = $this->menuItem->all();
    
            foreach ($menuItems as $menuItem) {
                $menuItem['category_name'] = $menuItem->category_name;
            }
    
            return $menuItems;
        }

If I do dd($menuItems); right after $menuItems = $this->menuItem->all(); I get:

    [
            "id" => 1
            "name" => "Hailee Ondricka"
            "category_id" => 1
            "side" => 0
            "side_only" => 0
            "description" => "Amet delectus exercitationem neque tenetur aliquam. Et repudiandae nam nam voluptates laboriosam autem. Natus quo quia ea. Explicabo reprehenderit consequatur quia aliquam incidunt."
            "image" => "https://lorempixel.com/640/480/?39201"
            "available" => 0
            "active" => 0
            "created_at" => "2020-06-21 00:41:02"
            "updated_at" => "2020-06-21 00:41:02"
          ]

but after the foreach in which I'm appending category_name I'm getting:

    "id" => 1
        "name" => "Krista Donnelly"
        "category_id" => 1
        "side" => false
        "side_only" => false
        "description" => "Sapiente est maiores non voluptatum odio placeat. Cum enim aut odit autem aut autem. Quasi excepturi omnis laborum aut officia tempora accusamus."
        "image" => "https://lorempixel.com/640/480/?96389"
        "available" => true
        "active" => false
        "created_at" => "2020-06-21 00:42:49"
        "updated_at" => "2020-06-21 00:42:49"
        "category_name" => "Dr. Christelle Purdy MD"
        "category" => array:4 [
          "id" => 1
          "name" => "Dr. Christelle Purdy MD"
          "created_at" => "2020-06-21 00:42:49"
          "updated_at" => "2020-06-21 00:42:49"
        ]
      ]

As you can see in the result, I do get category_name but I'm also getting the whole category object associated to that category, why is that? how do I prevent the whole object of being returned?

Mar
06
4 months ago
Activity icon

Replied to Check Existence Of Nested Value In Laravel Form Request Validation

Thanks @sti3bas , haven't tried yet but would you mind explaining it? I don't exactly understand what's happening here:

$rules[MenuItem::MENU_ITEM_PRICING . '.*'] = 'array';
$rules[MenuItem::MENU_ITEM_PRICING . '.*.sideprice'] = 'required';

I assume that the first part indicates that it must be an array and the second that it must have a property called sideprice?

I don't specifically understand the meaning of *

Feb
29
4 months ago
Activity icon

Started a new Conversation Check Existence Of Nested Value In Laravel Form Request Validation

Hi,

I've got the following validation rules:

[
        MenuItem::MENU_ITEM_NAME        => 'required|unique:menu_items,name',
        MenuItem::MENU_ITEM_DESCRIPTION => 'nullable',
        MenuItem::MENU_ITEM_CATEGORY    => 'required|exists:categories,id',
        MenuItem::MENU_ITEM_SIDE        => 'nullable|boolean',
        MenuItem::MENU_ITEM_SIDE_ONLY   => 'nullable|boolean',
        MenuItem::MENU_ITEM_IMAGE       => 'nullable',
        MenuItem::MENU_ITEM_AVAILABLE   => 'nullable|boolean',
        MenuItem::MENU_ITEM_ACTIVE      => 'nullable|boolean',
        MenuItem::MENU_ITEM_PRICING     => 'required',
    ]

they work fine until this test case that I need to implement:

Pricing aka MenuItem::MENU_ITEM_PRICING is an array of arrays. I need to check that when MenuItem::MENU_ITEM_SIDE is passed as true then the pricing array must contain a subarray with the some values for that specific item.

Ex:

    MenuItem::MENU_ITEM_SIDE => false,
     MenuItem::MENU_ITEM_PRICING => []
]

the previous example is valid. But:

Ex:

    MenuItem::MENU_ITEM_SIDE => true,
     MenuItem::MENU_ITEM_PRICING => []
]

is invalid, it should be:


Ex:

```[
    MenuItem::MENU_ITEM_SIDE => false,
     MenuItem::MENU_ITEM_PRICING => [['sideprice' => 2.20]]
]

How can I check (within my FormRequest class) that ifMenuItem::MENU_ITEM_SIDE == truethenMenuItem::MENU_ITEM_PRICINGshould contain a subarray with a key namedsideprice`?

Thanks

Feb
25
4 months ago
Activity icon

Replied to Vue: Add Third Party Library And Instantiate It

To do it that way the plugin must be listed in the npm repository. There's an equivalent npm package for this library but I need to do it the way I'm asking, loading it through a cdn

Feb
24
4 months ago
Activity icon

Started a new Conversation Vue: Add Third Party Library And Instantiate It

Hi. There's a third party library that I'm loading I'm my component in the mounted hook. Right after mounting it I'm trying to initialize a new instance but it's failing with the following message:


./src/components/HelloWorld.vue
Module Error (from ./node_modules/eslint-loader/index.js):

/Users/bigweld/Desktop/lucastmp/tmpproject/src/components/HelloWorld.vue
  29:11  error  'MediumEditor' is not defined  no-undef

✖ 1 problem (1 error, 0 warnings)

My component is the following:

<template>
  <div class="hello">
    <h1>Hello</h1>
    <div id="editor">

    </div>
  </div>
</template>

<script>

export default {
  name: 'HelloWorld',
  
  props: {
    msg: String
  },
  mounted() {
    const script = document.createElement('script')
    script.setAttribute('src', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/js/medium-editor.min.js')
    script.async = true
    document.head.appendChild(script)

    this.initEditor
  },
  methods: {

    initEditor() {
      new MediumEditor({
      element: document.getElementById("editor"),
      placeholder: {
        text: "Type your content here",
        hideOnClick: true
      }
    })
    }
  }
  
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

Any suggestions?

Feb
22
4 months ago
Activity icon

Replied to Multiple Dependency Injection Not Working

Please disregard this question. I tried to delete it but couldn't find a way to do it.

I've found the issue: Long story short. The method is expecting a double but getting an int.

Activity icon

Started a new Conversation Multiple Dependency Injection Not Working

Hi.

I've got the following service:

namespace App\Services;

use \App\Models\MenuItem;
use App\Models\Price;
use \App\Services\BaseService;
use Illuminate\Database\QueryException;
use InvalidArgumentException;

class MenuItemService extends BaseService
{

    /**
     * MenuItemService constructor.
     * @param MenuItem $model
     */
    public function __construct(MenuItem $model)
    {
        parent::__construct($model);
    }

up to this point everything was working fine. I was able to access MenuItem model with no issues. Then I had the need of using PriceService within this service so I decided to inject it as well and ended up with:

class MenuItemService extends BaseService
{

    private $pricingService;

    /**
     * MenuItemService constructor.
     * @param MenuItem $model
     * @param PriceService $pricingService
     */
    public function __construct(MenuItem $model, PriceService $pricingService)
    {
        parent::__construct($model);
        $this->pricingService = $pricingService;
    }

I have a method where I'm calling a method from PriceService like:

$pricing          = $this->pricingService->setPrice($menuItem->id, $pricing_category, $price);

But doesn't seem to be working. I added a dd() statement in the method I'm invoking but it's never hit. Here's my PriceService:

<?php
/**
 * Created by PhpStorm.
 * User: bigweld
 * Date: 2/22/20
 * Time: 6:04 PM
 */

namespace App\Services;


use App\Models\Price;
use Illuminate\Database\Eloquent\Model;

class PriceService extends BaseService
{
    public function __construct(Price $model)
    {
        parent::__construct($model);
    }

    public function setPrice(
        int $menu_item_id,
        string $pricing_category,
        double $price
    ) : array
    {
        dd("here");
        $data = [
            Price::MENU_ITEM_ID     => $menu_item_id,
            Price::PRICING_CATEGORY => $pricing_category,
            Price::PRICE            => $price
        ];

        return $this->create($data);
    }

}

what am I missing?

Feb
18
4 months ago
Activity icon

Started a new Conversation Laravel Validation Rule Fails When Trying To Update The Same Record With No Changes

I've got a table called Sides which consists of id, name, side_category_id and some other fields not important at the moment.

I wanted to validate that when creating a new side record, the record doesn't exist already. So, let's say I've got in the database a record such as:

id: 1
name: Salad
side_category_id: 3

If I try to insert a new record with name = 'salad' and side_category_id = 3 then the creation must fail and return an error.

I've achieved this by using the following rule:

$rules = [
   'name'             => 'required',
   'side_category_id' => 'required|exists:side_categories,id|unique:sides,side_category_id,NULL,id,name,' . $this->request->get('name')
]

So far so good. It works as it's supposed to. But now it's returning an error if I want to edit a record and save it without any modifications and this is not my desired outcome.

If I try to update the record with no modifications it should succeed. How can I update my rule to achieve this?

Feb
13
5 months ago
Activity icon

Replied to Vue Vee-validate Server Side Error Not Being Set At All

@sti3bas Not in my case. This is the response I'm getting from the server:

{"success":false,"message":"Validation failed","data":{"name":["The name has already been taken."]}}

So, in my case err.response.data.data contains an object of field => [errors]

Activity icon

Started a new Conversation Vue Vee-validate Server Side Error Not Being Set At All

I've got the following form:

<ValidationObserver ref="form" v-slot="{ handleSubmit }">
                    <form name="side-category" class="mb-4 md:flex md:flex-wrap md:justify-between" @submit.prevent="handleSubmit(onSubmit)">
                        <div class="md:w-full px-3">
                            <ValidationProvider name="Side" rules="required" v-slot="{ errors, failedRules }">
                                <label for="name" class="tracking-wide mb-2 uppercase font-bold text-xs text-grey-darkest">Side Category Name</label>
                                <input
                                        type="text"
                                        name="name"
                                        id="name"
                                        v-model.lazy="form.name"
                                        data-vv-as="beware asshole!!!"
                                        class="w-full border border-gray-200 rounded py-3 px-4 mb-3 bg-gray-200 text-blue-900 md:mr-2"
                                >
<!--                                <span v-if="failedRules.required">Yo! Save something!!!</span>-->
                                <span>{{ errors[0] }}</span>
                            </ValidationProvider>
                            <button id="submit-btn" class="bg-green-300 font-semibold hover:font-bold hover:bg-green-500 text-green-800 uppercase text-sm mx-auto p-2 rounded float-right"></button>
                        </div>
                    </form>
                </ValidationObserver>

My data method is the following:

data() {
            return {
                id: null,
                mode: 'new',
                form: {
                    name: ''
                }
            }
        },

and my submit method is:

onSubmit() {
                axios.post('http://127.0.0.1:8000/api/admin/sidecategories', this.form)
                    .then(response => {
                        // eslint-disable-next-line no-console
                        console.log(response)
                        
                            this.$router.push('/sidecategories/list')
                        }
                    })
                    .catch(err => {

                        if (!err.response.data.success) {
                            // eslint-disable-next-line no-console
                            console.log(err.response.data.data)
                            // { name: ['test error']}
                            this.$refs.form.setErrors(err.response.data.data)
                        }
                    })
            }

The problem that I have is that this.$refs.form.setErrors is not setting any error at all. If I print err.response.data.data (response from Laravel backend) I get the following:

{{"name":["The name has already been taken."]}}

which according to vee-validate's documentation is the format expected by setErrors.

I'm using vee-validate 3.

What am I missing?

Feb
01
5 months ago
Activity icon

Replied to Custom Rule Not Working

Although I figured out a way to do it I still would like to know why my previous effort was failing.

This is what I'm doing now:

public function rules(): array
    {
        $newRule = new OrderStatusCreated();
        $rules = parent::rules(); // TODO: Change the autogenerated stub
        array_push($rules[Order::ORDER_STATUS], $newRule);
        //dd($rules);
        return $rules;
    }
Activity icon

Replied to Custom Rule Not Working

hi @ahmeddabak . I'm sorry, that doesn't make sense to me. All the items you listed are simply constants that hold a string.

Activity icon

Replied to Custom Rule Not Working

expression is not allowed as field default value

Jan
30
5 months ago
Activity icon

Started a new Conversation Custom Rule Not Working

Hi. I've created the following custom rule:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class OrderStatusCreated implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return boolean
     */
    public function passes($attribute, $value) : bool
    {
        //dd($this->parameters);
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message() : String
    {
        return 'The order cannot be updated since it was already submitted or canceled.';
    }
}

at the moment it does nothing. It simply returns true. Now, when I implementing it i'm getting a syntax error:

public function rules()
{
    return [
        Order::ORDER_SESSION_ID       => 'required|alpha_num',
        Order::ORDER_NO               => 'string',
        Order::ORDER_STATUS           => ['required', 'numeric', new OrderStatusCreated],
        OrderItem::ORDER_ITEM_ITEM_ID => 'required|numeric',
        OrderItem::ORDER_ITEM_QUANTITY=> 'required|numeric|min:0|not_in:0'
    ]; 
}

what am i doing wrong?

Jan
25
5 months ago
Activity icon

Replied to Getting "Trying To Get Property 'subtotal' Of Non-object" When Using FindOrFail

Doesn't work. I'm getting the same error message back

Activity icon

Started a new Conversation Getting "Trying To Get Property 'subtotal' Of Non-object" When Using FindOrFail

I've got the following piece of code in a service:

public function add(array $data) : Order
    {
        // retrieve item data
        $item       = MenuItem::findOrFail($data[OrderItem::ORDER_ITEM_ITEM_ID]);
        $quantity   = $data[OrderItem::ORDER_ITEM_QUANTITY];
        $order_no   = $data[Order::ORDER_NO] ?? null;
        $session_id = $data[Order::ORDER_SESSION_ID];

        $order = $order_no ? Order::findOrFail($order_no) : $this->createOrder([Order::ORDER_SESSION_ID => $session_id]);
        
        $order_item = $this->order_item->createOrderItem($order->order_no, $item, $quantity);

        // update order total
        $order->subtotal += $order_item->subtotal;
        $order->total    += $order_item->subtotal;
        $order->update();

        return $order;
    }

When running a test I'm getting:

Getting "Trying to get property 'subtotal' of non-object"

The object has something, otherwise it'd have failed. But neither subtotal nor total belong to the object. If I print the object I get the other fields except for these two. They both are in my $fillable array and I defined a ->default(0); in my migration.

What's going on?

Activity icon

Replied to Post Data With Ajax In Laravel

Try:

Route::post('/addcustomer', '[email protected]');

and

$.ajax({ type:'POST', url:'/addcustomer', 
Jan
24
5 months ago
Activity icon

Replied to Laravel Mutator Not Converting Null Into Empty String

@nakov the fist one worked! thanks a lot. The second one did not, even though I used:

public function getPhoneAttribute(string $phone ="") 
Jan
23
5 months ago
Activity icon

Replied to Laravel Mutator Not Converting Null Into Empty String

@nakov not an option. I wanna find a better solution instead of starting to remove type hints from all over the place

Activity icon

Started a new Conversation Laravel Mutator Not Converting Null Into Empty String

I'm running an integration test and am getting the following error:

array:5 [ "message" => "Argument 1 passed to App\Models\Order::getPhoneAttribute() must be of the type string, null given, called in /Users/bigweld/Sites/restaurantbe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 454" "exception" => "Symfony\Component\Debug\Exception\FatalThrowableError" "file" => "/Users/bigweld/Sites/restaurantbe/app/Models/Order.php" "line" => 87 "trace" => array:44 [

So it seems to be related to my mutators, which are:

public function setPhoneAttribute(string $phone) : void
    {
        $this->attributes[self::ORDER_PHONE] = empty($phone) ? "" : preg_replace("/[^A-Za-z0-9 ]/", '', $phone);
    }

    public function getPhoneAttribute(string $phone) : string
    {
        return is_null($phone) ? "": preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
            '()--', $phone);
    }

my test is not passing Order::ORDER_PHONE meaning that an empty string should be stored in the database. If I declare the field in the data array along with the other fields even if empty (ie: [ Order::ORDER_PHONE => "" ]) then this error is not coming up.

Any ideas why?

Jan
20
5 months ago
Activity icon

Started a new Conversation How Does Method Injection Works In A Method That Is Expecting Other Parameters?

Hi,

I have the following call from my Order controller:

public function add(AddToOrder $request /*, int $item_id*/)
    {
        $order = $this->order->add($request->validated());
    }

into my OrderService.

My question is the following. I tried to inject a different service into the add method doing this:

public function add(OrderItemService $orderItem, array $data)
    {
        // retrieve item data
        $item       = MenuItem::findOrFail($data[OrderItem::ORDER_ITEM_ITEM_ID]);
        $quantity   = $data[OrderItem::ORDER_ITEM_QUANTITY];
        $order_no   = $data[Order::ORDER_NO] ?? null;
        $session_id = $data[Order::ORDER_SESSION_ID];

        $order = $order_no ? Order::findOfFail($order_no) : $this->createOrder([OrderItem::ORDER_ITEM_ITEM_ID => $session_id]);

        $orderItem->createOrderItem($order->order_no, $item, $quantity);

    }

But (as I expected) I'm getting an error:

Argument 1 passed to App\Services\OrderService::add() must be an instance of App\Services\OrderItemService, array given, called in /Users/bigweld/Sites/restaurantbe/app/Http/Controllers/API/OrderController.php on line 56

Is there a way to inject OrderItemService into the add method? I don't want to do it globally (in the constructor).

Thanks

Jan
19
5 months ago
Activity icon

Started a new Conversation Get Data From Header In Validation File

Hi.

I've created a test where I'm sending the following request to my api:

$data = [
            OrderItem::ORDER_ITEM_ITEM_ID => $menuItem->id,
        ];

        $response = $this->withHeaders([
            'session_id' => $this->faker->md5,
        ])->json('POST', '/api/orders/add/', $data);

Notice that I'm passing session_id as part of the headers and not as part of the data.

Now, I've created my AddToOrderRequest file in which I have:

protected static $FORM_RULES = [
        Order::ORDER_SESSION_ID       => 'required|alpha_num',
        Order::ORDER_NO               => 'string',
        OrderItem::ORDER_ITEM_ITEM_ID => 'required|numeric'
    ];

    public function validationData()
    {
        return array_merge(
            $this->request->all(),
            [Order::ORDER_SESSION_ID => $this->request->header('session_id')]
        );
    }

See how I'm attaching to the request array the new field (Order::ORDER_SESSION_ID is equivalent to session_id) but doesn't seem to work. I'm getting a response that contains the following:

"data" => array:1 [
    "session_id" => array:1 [
      0 => "The session id field is required."
    ]
  ]

indicating that my session_id field is not being attached.

What is going on?