bigweld86

bigweld86

Member Since 2 Years Ago

Experience Points
8,950
Total
Experience

1,050 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-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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
8,950 XP
Jan
25
2 days 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
3 days 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
4 days 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
1 week 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
1 week 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?

Dec
10
1 month ago
Activity icon

Replied to Bubbling Up Exceptions

Hi @corcronje Thanks for your reply.

I tried before the first approach you suggested, but it returns the json structure from findAttributeById into edit method in the controller and messes up with the sendResponse method since now I have that response within the response returned by edit and that's what I want to avoid. Is there a way to do it?

Activity icon

Started a new Conversation Bubbling Up Exceptions

Hi.

I've got a Controller which extends a custom BaseController. My BaseController has these two methods (among others):

public function sendResponse(array $result, string $message = 'Success') : JsonResponse
    {
        $response = [
            'success' => true,
            'data'    => $result,
            'message' => $message
        ];

        return response()->json($response, 200);
    }

    public function sendError(
        string $error, 
        array $errorMessages = [], 
        int $code = 404) : JsonResponse
    {
        $response = [
            'success' => false,
            'message' => $error
        ];

        if (!empty($errorMessages)) {
            $response['data'] = $errorMessages;
        }

        return response()->json($response, $code);

    }

So when any of my methods in my controllers resolves successfully then I call sendResponse otherwise sendError.

I've got this method in my controller:

public function edit($id) : JsonResponse
    {
        
            try {
                $attribute = $this->attribute->findAttributeById((int)$id);
                return $this->sendResponse([$attribute]);
        } catch (ModelNotFoundException $e) {
                return $this->sendError($e->getMessage());
        }

    }

and findAttributeById is:

public function findAttributeById(int $id) {
    try {
            return $this->model->findOrFail($id);
        } catch (ModelNotFoundException $e) {
            throw new ModelNotFoundException('Record not found');
        }

the issue is that throwing the error from findAttributeById is not being caught by the edit method. How can I achieved that?

Thanks

Dec
08
1 month ago
Activity icon

Replied to Separate Controller Methods Seem To Be Messing With One Another

@gazd1977 thanks for the explanation @bugsysha good suggestion, will do that, thanks

Activity icon

Replied to Separate Controller Methods Seem To Be Messing With One Another

Oh sh*t, no way, that was the issue! Not in a 1000 years I would have thought it was a matter of order. How's that? Why does matter and specially in this context where they are not related? And thanks a lot, I've been hours trying to figured this one out.

Activity icon

Started a new Conversation Separate Controller Methods Seem To Be Messing With One Another

Hi. I've got the following routes:

Route::group(['middleware' => ['guest:api', 'cors']], function () {

    /**
     * Grouped Routes for Attributes
     */
    Route::group(['prefix' => 'attributes'], function() {
        Route::get('/{id}', 'Admin\[email protected]')->name('admin.attributes.edit');
        Route::get('/frontend-types', 'Admin\[email protected]');
    });
});

With their respective controller methods:

public function edit($id) : JsonResponse
    {
        $attribute = $this->attribute->findAttributeById((int)$id);
        return $this->sendResponse([$attribute]);
    }

public function getFrontendTypes() : JsonResponse
    {
        return $this->sendResponse(Attribute::ATTRIBUTE_FRONTEND_TYPES);
    }

When I have these two routes active I'm getting an error when accessing getFrontendTypes. But what's weird is that the error comes from the edit method although they are not dependent on one another. If I commented out the edit route then getFrontendTypes works fine and viceversa. But when both are active edit is failing with the following error:

(this is the url I'm testing via Postman: http://127.0.0.1:8000/api/attributes/frontend-types):

 "message": "Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Models\Attribute] 0 in /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:371\nStack trace:\n#0 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php(23): Illuminate\Database\Eloquent\Builder->findOrFail(0)\n#1 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1618): Illuminate\Database\Eloquent\Model->forwardCallTo(Object(Illuminate\Database\Eloquent\Builder), 'findOrFail', Array)\n#2 /Users/bigweld/Sites/csrecords/app/Services/BaseService.php(132): Illuminate\Database\Eloquent\Model->__call('findOrFail', Array)\n#3 /Users/bigweld/Sites/csrecords/app/Services/AttributeService.php(51): App\Services\BaseService->findOneOrFail(0)\n#4 /Users/bigweld/Sites/csrecords/app/Http/Controllers/Admin/AttributeController.php(57): App\Services\AttributeService->findAttributeById(0)\n#5 [internal function]: App\Http\Controllers\Admin\AttributeController->edit('frontend-types')\n#6 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array(Array, Array)\n#7 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction('edit', Array)\n#8 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Route.php(219): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(App\Http\Controllers\Admin\AttributeController), 'edit')\n#9 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Route.php(176): Illuminate\Routing\Route->runController()\n#10 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Router.php(680): Illuminate\Routing\Route->run()\n#11 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(130): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))\n#12 /Users/bigweld/Sites/csrecords/app/Http/Middleware/RedirectIfAuthenticated.php(24): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#13 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): App\Http\Middleware\RedirectIfAuthenticated->handle(Object(Illuminate\Http\Request), Object(Closure), 'api')\n#14 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#15 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))\n#16 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(59): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#17 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): Illuminate\Routing\Middleware\ThrottleRequests->handle(Object(Illuminate\Http\Request), Object(Closure), 60, '1')\n#18 /Users/bigweld/Sites/csrecords/app/Http/Middleware/Cors.php(42): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#19 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): App\Http\Middleware\Cors->handle(Object(Illuminate\Http\Request), Object(Closure))\n#20 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(105): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#21 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Router.php(682): Illuminate\Pipeline\Pipeline->then(Object(Closure))\n#22 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Router.php(657): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))\n#23 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Router.php(623): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))\n#24 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Routing/Router.php(612): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))\n#25 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(176): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))\n#26 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(130): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))\n#27 /Users/bigweld/Sites/csrecords/app/Http/Middleware/Cors.php(42): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#28 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): App\Http\Middleware\Cors->handle(Object(Illuminate\Http\Request), Object(Closure))\n#29 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#30 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))\n#31 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#32 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))\n#33 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#34 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))\n#35 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(62): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#36 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))\n#37 /Users/bigweld/Sites/csrecords/vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#38 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(171): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))\n#39 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(105): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))\n#40 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(151): Illuminate\Pipeline\Pipeline->then(Object(Closure))\n#41 /Users/bigweld/Sites/csrecords/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(116): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))\n#42 /Users/bigweld/Sites/csrecords/public/index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))\n#43 /Users/bigweld/Sites/csrecords/server.php(21): require_once('/Users/bigweld/...')\n#44 {main}",

but when I comment out this route: //Route::get('/{id}', 'Admin\[email protected]')->name('admin.attributes.edit');

then the previous test returns the right data:

{
  "success": true,
  "data": [
    {
      "id": "select",
      "value": "Select"
    },
    {
      "id": "radio",
      "value": "Radio"
    },
    {
      "id": "text",
      "value": "Text"
    },
    {
      "id": "text_area",
      "value": "Text Area"
    }
  ],
  "message": "Success"
}

what am I missing? what's going on here?

Thanks

Nov
30
1 month ago
Activity icon

Started a new Conversation Vue / Vuetify Dynamically Modify V-text-field Properties

I've got a couple fields:

<v-row>
                                <v-col cols="12" class="d-flex">
                                    <v-text-field
                                            clearable
                                            outlined
                                            required
                                            :rules="rules.codeRules"
                                            name="code"
                                            v-model="attribute.code"
                                            label="Code"></v-text-field>
                                </v-col>
                            </v-row>

                            <v-row>
                                <v-col cols="12" class="d-flex">
                                    <v-text-field
                                            clearable
                                            outlined
                                            required
                                            :rules="rules.nameRules"
                                            name="name"
                                            v-model="attribute.name"
                                            label="Name"></v-text-field>
                                </v-col>
                            </v-row>

In Vuetify's documents I see there's a couple properties named error which triggers an error state and error-messages with messages to be displayed.

When the form's submitted, if there's any errors on any of the fields I want to trigger these properties.

How can I do that? For instance, how can I manually set the field with the name of "code" into an error state by using the error property? how can I pass a personalized message to it? Do I need to specifically create a variable in the data() object in order to do what I wanna do? because if I have to do it that way it'd mean that I need to create an error and an error-messages properties in the data object for each and every field in my form!? or it can do by selecting exactly the field that I want to modify and somehow update its properties directly without the need of any variable from the model?

Thanks

Nov
17
2 months ago
Activity icon

Replied to GET Axios Request Blocked By CORS (only Failing For This Specific Request, Others Are Working)

@sinnbeck @nakov I just restarted the server and everything is working. Don't exactly know what was happening. Thanks both anyway!

Activity icon

Replied to GET Axios Request Blocked By CORS (only Failing For This Specific Request, Others Are Working)

@sinnbeck yeah, this is the output of the network tab:

Request URL: http://127.0.0.1:8000/api/categories/list?page=1
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
Connection: close
Content-type: text/html; charset=UTF-8
Date: Sun, 17 Nov 2019 17:46:07 +0000
Host: 127.0.0.1:8000
X-Powered-By: PHP/7.2.8
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Host: 127.0.0.1:8000
Origin: http://localhost:8080
Pragma: no-cache
Referer: http://localhost:8080/categories/
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36
1: 1
Activity icon

Replied to GET Axios Request Blocked By CORS (only Failing For This Specific Request, Others Are Working)

I saw the package before, but want to try to fix this issue first

Activity icon

Replied to GET Axios Request Blocked By CORS (only Failing For This Specific Request, Others Are Working)

What is weird is that I copied/pasted the URL I'm using in my ListCategories component to get a list of items and still doesn't work. I mean, the same URL is working in one component but no in the other:

This is my method to retrieve the data in ListCategories:

getCategories() {
                return new Promise((resolve, reject) => {
                    const {sortBy, descending, page, rowsPerPage} = this.pagination;

                    axios.get(`http://127.0.0.1:8000/api/categories/list?page=${page}&items-per-page=${rowsPerPage}`)
                        .then(response => {
                            this.items = this.massageData(response.data.data.data);
                            this.options = response.data.data.pagination;
                            this.totalItems = response.data.data.options.totalItems;
                            this.loading = false
                            resolve()
                        })
                        .catch(errors => {
                            // eslint-disable-next-line no-console
                            console.log(errors)
                            reject()
                        })
                })
            },

the previous one works perfectly. This is the one in my Category component which is not working due to the Cors error:

getCategories() {
                const page = 1;
                // http://127.0.0.1:8000/api/categories/list?page=1&items-per-page=100&sort-by=asc&fields=id,name
                axios.get(`http://127.0.0.1:8000/api/categories/list?${page}=1`)
                    .then(response => {
                        // eslint-disable-next-line no-console
                        console.log(response);
                        //resolve()
                    })
                    .catch(errors => {
                        // eslint-disable-next-line no-console
                        console.log(errors)
                        //reject()
                    })
            }
Activity icon

Replied to GET Axios Request Blocked By CORS (only Failing For This Specific Request, Others Are Working)

@sinnbeck here's my CORS middleware:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', '*')
            ->header('Access-Control-Allow-Headers', '*');
    }
}
Activity icon

Replied to GET Axios Request Blocked By CORS (only Failing For This Specific Request, Others Are Working)

@nakov here's the api.php:

Route::group(['middleware' => ['guest:api', 'cors']], function () {

    Route::group(['prefix' => 'categories'], function() {


        Route::get('/list', 'Admin\[email protected]')->name('admin.categories.index');
        Route::post('/', 'Admin\[email protected]'); //->name('admin.categories.store');
        Route::get('/{id}', 'Admin\[email protected]')->name('admin.categories.edit');
        Route::post('/{id}', 'Admin\[email protected]')->name('admin.categories.update');
        Route::delete('/{id}', 'Admin\[email protected]')->name('admin.categories.delete');
    });
});

The one I'm using with for my parameterized query is:

Route::get('/list', 'Admin\[email protected]')->name('admin.categories.index');

Activity icon

Started a new Conversation GET Axios Request Blocked By CORS (only Failing For This Specific Request, Others Are Working)

Hi. From my Vue frontend I'm executing a GET request using axios:

axios.get(`http://127.0.0.1:8000/api/categories/list?page=1&items-per-page=100&sort-by=asc&fields=id,name`)
                    .then(response => {
                        // eslint-disable-next-line no-console
                        console.log(response);
                        //resolve()
                    })
                    .catch(errors => {
                        // eslint-disable-next-line no-console
                        console.log(errors)
                        //reject()
                    })

and I'm getting the following message: Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/categories/list?page=1&items-per-page=100&sort-by=asc&fields=id,name' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already have in place a CORS middleware in my Laravel backend, and so far all requests such as:

axios.get(`http://127.0.0.1:8000/api/categories/${this.id}`)
                    .then(response => {
                        this.category = response.data.data[0];

                        // eslint-disable-next-line no-console
                        console.log(this.category);

                    })
                    .catch(errors => {
                        // eslint-disable-next-line no-console
                        console.log(errors)
                    })

or

axios.get(`http://127.0.0.1:8000/api/categories/list?page=${page}&items-per-page=${rowsPerPage}`)
                        .then(response => {
                            this.items = this.massageData(response.data.data.data);
                            this.options = response.data.data.pagination;
                            this.totalItems = response.data.data.options.totalItems;
                            this.loading = false
                            resolve()
                        })
                        .catch(errors => {
                            // eslint-disable-next-line no-console
                            console.log(errors)
                            reject()
                        })

are working correctly.

This is the only request (at the moment) in which I'm passing query parameters and it's the only one failing.

Any ideas?

Nov
10
2 months ago
Activity icon

Replied to Validation Is Filtering Out Fields Not Listed In Rules

Is that so? I thought that as long as they were listed in the $fillable array they were allowed to be inserted and validation it was only for fields on which we needed to enforce some kind of rules but those not listed there were supposed to go through (if they were listed in $fillable)

Activity icon

Replied to Validation Is Filtering Out Fields Not Listed In Rules

Not a silly question but yes, they were already in the $fillable array

Activity icon

Started a new Conversation Validation Is Filtering Out Fields Not Listed In Rules

Hi. My FormRequest validation seems to be filtering out the fields not listed in the rules array. Here's my file:

<?php

namespace App\Http\Requests;

use App\Http\Requests\BaseFormRequest;
use App\Models\Category;

class StoreCategory extends BaseFormRequest
{
    
    protected static $NEEDS_AUTHORIZATION = false;

    protected static $FORM_RULES = [
        Category::CATEGORY_PARENT_FIELD => 'required',
        Category::CATEGORY_NAME_FIELD   => 'required|unique:categories,name',
        Category::CATEGORY_IMAGE_FIELD  => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ];

    /**
     * @return array
     */
    public function rules(): array
    {
        $rules = parent::rules();

        // needed for update
        $id = $this->request->get('id') ? ',' . $this->request->get('id') : '';

        // append it to the rules with 'unique' check
        $rules[Category::CATEGORY_NAME_FIELD] .= $id;

        return $rules;
    }
}

When I send a request with the following body:

{
    "name": "one more cat",
    "parent_id": "1",
    "description": "this is a desc",
    "featured": 1,
    "menu": 1
}

only

"parent_id": 1,
"name": "one more cat",

are being saved. All other fields (description, featured, menu) are being excluded. Here's the store method in my controller:

public function store(StoreCategory $request) : JsonResponse
    {
        $category = $this->category->create($request->validated());
        return $this->sendResponse([$category], 'Category created successfully.');
    }

any idea why this is happening?

Oct
28
2 months ago
Activity icon

Replied to Use A Separate Project Only For Migrations And Reference It From Other Projects

thanks @sinnbeck . Would be possible to strip completely the project and leave only the database (factories, migrations, seeds) folder?

Activity icon

Started a new Conversation Use A Separate Project Only For Migrations And Reference It From Other Projects

Hello. I've got an e-commerce app which will be basically divided in 2 sections/projects:

  1. One section will be in charge of frontend/backend transactions. Frontend pages will be in Vue, backend in Laravel
  2. The other section will be basically an admin section, to manage (add/edit/delete) products, orders etc and will be completely build in laravel

Both projects will obviously query and modify the same database.

Here's my question:

Can I have a separate project just in charge of database migrations? if so, how could I reference those migrations for each of the projects (repositories)?

I don't want to have these functionality together (store itself and the admin part of it), that's why I want to separate them.

I don't think there's gonna be much code replication, I mean, I know there's gonna be some, at least for the login part but other than that (and a few other cases) not many.

Is there a way to accomplish this?

Thanks.

Oct
18
3 months ago
Activity icon

Replied to Laravel Passport Error: CreateToken Method Doesn't Exist

I've got the answer in a different forum. But you were getting closer @sinnbeck . Indeed, my classes where different. I had created a Models directory to store my models but in my provider I was using the default reference to the models assuming they where directly located under app. Here's the answer that I got in case someone else needs it:

Since your guard is returning the wrong User model, App\User, you should check your auth configuration, 'config/auth.php'. In the providers array adjust any provider, usually users, that is using the App\User model to App\Models\User instead.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        // 'model' => App\User::class,
        'model' => App\Models\User::class,
    ],
    ...
],
Oct
17
3 months ago
Activity icon

Replied to Laravel Passport Error: CreateToken Method Doesn't Exist

So, this is not the right way to do it but it's working at the moment:

<?php

namespace App\Http\Controllers\API;

//use Illuminate\Foundation\Auth\AuthenticatesUsers;
//use Illuminate\Http\Request;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\API\BaseController;

class AuthController extends BaseController
{
    public function login()
    {
        if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
            $authenticated_user = \Auth::user();
            $user = User::find($authenticated_user->id);
            dd($user->createToken('myApp')->accessToken);
        }

        dd('here');
    }



}

Now I'm seeing the token.

I wanna do it the right way so I still would appreciate if any one could help me. Thanks

Activity icon

Replied to Laravel Passport Error: CreateToken Method Doesn't Exist

@sinnbeck and do you know what's weird? When registering an user (I'm using a separate controller and also using a service) am returning a token an the token is created successfully:

Here's my controller:

<?php

namespace App\Http\Controllers\API;

use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterUserRequest;


class UserController extends Controller 
{
    private $user;

    public function __construct(UserService $user)
    {
        $this->user = $user;
    }

    public function store(RegisterUserRequest $request) : JsonResponse
    {
        // TODO: verify message on error
        
        $user = $this->user->register($request->validated());
        $token = $user->createToken('MyApp')->accessToken;
        dd($token);

        return response()->json(['status' => 201, 'user_id' => $user->id]);
    }

}

Here's my service:

<?php

namespace App\Services;

use App\Models\User;
use App\Services\BaseServiceInterface;

class UserService implements BaseServiceInterface
{
 
    public function register(array $formValues) : User
    {
        // 'terms and conditions' should not be saved into the db, hence it's removed
        unset($formValues['terms_conditions']);
        return User::create($formValues);
    }

}

and here's my model again:

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    const USER_FIRST_NAME_FIELD        = "first_name";
    const USER_LAST_NAME_FIELD         = "last_name";
    const USER_PREFERRED_NAME_FIELD    = "preferred_name";
    const USER_EMAIL_FIELD             = "email";
    const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
    const USER_PASSWORD_FIELD          = "password";
    const USER_REMEMBER_TOKEN_FIELD    = "remember_token";
    const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
    const USER_ACTIVE_FIELD            = "active";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        self::USER_FIRST_NAME_FIELD, 
        self::USER_LAST_NAME_FIELD,
        self::USER_PREFERRED_NAME_FIELD,
        self::USER_EMAIL_FIELD,
        self::USER_PASSWORD_FIELD,
        self::USER_RECEIVE_NEWSLETTER_FIELD,
        self::USER_ACTIVE_FIELD,
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        self::USER_PASSWORD_FIELD,
        self::USER_REMEMBER_TOKEN_FIELD
    ];

As I told you, when creating an user the token is being generated correctly.

Activity icon

Replied to Laravel Passport Error: CreateToken Method Doesn't Exist

This is my AuthServiceProvider.php:

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();
        Passport::tokensExpireIn(now()->addHours(8));
        Passport::refreshTokensExpireIn(now()->addDays(10));
        // Passport::personalAccessTokensExpireIn(now()->addMonths(6));
    }
}

Activity icon

Replied to Laravel Passport Error: CreateToken Method Doesn't Exist

I will check later today as I don't have my computer at the moment, although I think I did not.

Activity icon

Replied to Laravel Passport Error: CreateToken Method Doesn't Exist

I'm pretty sure I did, correct me if I'm mistaken but if I had not I wouldn't see "laravel/passport": "^7.5" in my composer.json nor any table related to passport in the database, right?

Activity icon

Replied to Laravel Passport Error: CreateToken Method Doesn't Exist

@sinnbeck yes sir, it's installed indeed. This is part of my composer.json:

"license": "MIT",
    "require": {
        "php": "^7.2",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "^6.2",
        "laravel/passport": "^7.5",
        "laravel/tinker": "^1.0"
    },
Activity icon

Replied to Laravel Passport Error: CreateToken Method Doesn't Exist

correct, it returns the currently authenticated user:

User {#294 ▼
  #fillable: array:3 [▶]
  #hidden: array:2 [▶]
  #casts: array:1 [▶]
  #connection: "mysql"
  #table: "users"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:12 [▶]
  #original: array:12 [▶]
  #changes: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
  #rememberTokenName: "remember_token"
}
Activity icon

Started a new Conversation Laravel Passport Error: CreateToken Method Doesn't Exist

I'm trying to generate a token to authenticate users in my Controller the following way:

namespace App\Http\Controllers\API;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class AuthController extends Controller
{
    public function login()
    {
        if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
            $user = Auth::user();
            
         
            $success['token'] = $user->createToken('myApp')->accessToken;
            dd($success['token']);
            
        }
    }

Currently, I'm just trying to print out the token. And this is my User's model:

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    const USER_FIRST_NAME_FIELD        = "first_name";
    const USER_LAST_NAME_FIELD         = "last_name";
    const USER_PREFERRED_NAME_FIELD    = "preferred_name";
    const USER_EMAIL_FIELD             = "email";
    const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
    const USER_PASSWORD_FIELD          = "password";
    const USER_REMEMBER_TOKEN_FIELD    = "remember_token";
    const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
    const USER_ACTIVE_FIELD            = "active";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        self::USER_FIRST_NAME_FIELD, 
        self::USER_LAST_NAME_FIELD,
        self::USER_PREFERRED_NAME_FIELD,
        self::USER_EMAIL_FIELD,
        self::USER_PASSWORD_FIELD,
        self::USER_RECEIVE_NEWSLETTER_FIELD,
        self::USER_ACTIVE_FIELD,
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        self::USER_PASSWORD_FIELD,
        self::USER_REMEMBER_TOKEN_FIELD
    ];

    /**
     * Automatically creates password hash when password is submitted
     *
     * @param string $password
     * @return void
     */
    public function setPasswordAttribute(string $password) : void
    {
        $this->attributes['password'] = Hash::make($password);    
    }
}

As you can see I'm using HasApiTokens, Notifiable traits and nonetheless I'm getting an error from my controller saying:

Call to undefined method App\User::createToken()

Any idea why? Thanks

Oct
13
3 months ago
Activity icon

Replied to Laravel 6 Custom Validation Error 'class Does Not Exist' When Overriding FormRequest's FailedValidation Method

Never mind, found the issue. I had to use Illuminate\Contracts\Validation\Validator instead Illuminate\Validation\Validator

Activity icon

Started a new Conversation Laravel 6 Custom Validation Error 'class Does Not Exist' When Overriding FormRequest's FailedValidation Method

I created a custom validation class located in app\Http\Requests:

<?php

namespace App\Http\Requests;

use App\Http\Requests\BaseFormRequest;

class RegisterUserRequest extends BaseFormRequest
{
    protected static $NEEDS_AUTHORIZATION = false;

    protected static $FORM_RULES = [
        'first_name'              => 'required|string|max:80',
        'last_name'               => 'required|string|max:80',
        'email'                   => 'required|unique:users|email',
        'password'                => 'required|string|min:6|confirmed',
        'terms_conditions'        => 'accepted'
    ];
    
}

and extends BaseFormRequest in the same directory:

<?php 

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
//use Illuminate\Http\Request;

abstract class BaseFormRequest extends FormRequest 
{
    protected static $NEEDS_AUTHORIZATION = true;
    protected static $FORM_RULES          = [];
    protected static $ERROR_MESSAGES      = [];

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize() : bool
    {
        return !static::$NEEDS_AUTHORIZATION;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() : array
    {
        return static::$FORM_RULES;
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
    */
    public function messages()
    {
        return static::$ERROR_MESSAGES;
    }


    /**
     * @overrride
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator) : void
    {
        //throw (new ValidationException(response()->json($validator->errors(), 422)));
        throw new HttpResponseException(response()->json($validator->errors(), 422));
    }

}

Now, when trying to use it in my controller:

<?php

namespace App\Http\Controllers\API;

use App\Services\UserService;
use Illuminate\Http\JsonResponse as JsonResponse;
//use Iluminate\Http\Request;
use App\Http\Requests\RegisterUserRequest;

class UserController extends Controller
{
    private $user;

    public function __construct(UserService $user)
    {
        $this->user = $user;
    }

    public function store(RegisterUserRequest $request) : JsonResponse
    {   
        $registered_user = $this->user->register($request->validated());

        return response()->json(['status' => 201, 'user_id' => $registered_user->id]);
    }

}

I'm getting the following error:

ReflectionException Class App\Http\Requests\RegisterUserRequest does not exist

The funny thing is that if I remove the overwritten method failedValidation the error is gone, although it redirects me to home page which is what I'm trying to avoid. I want to return always a json response.

Any suggestions? Thanks

Aug
13
5 months ago
Activity icon

Started a new Conversation Authentication With VueX And Laravel Passport

I'm currently using Vue (and VueX) and Laravel Passport. I have my register page working fine, now I've moved into my Login page. All the tutorials and posts I've seen online show a login system where the generated token is stored in localStorage but I've seen also that everybody says we shouldn't store any sensitive data in localStorage, then how should I do it? How can I manage sessions if my frontend (VueX) is separated from my backend (laravel)?

Aug
10
5 months ago
Activity icon

Started a new Conversation Why The Response From The Same Endpoint Is Different

While unit-testing a method from my RegisterController I noticed that it responds back differently depending on the method use to make the request.

So if I perform the following request:

$response = $this->post(
            "/api/register/",
            $user2,
            [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]
        );

dd($response->content());

The dump is the following:

"{"message":"The given data was invalid.","errors":{"first_name":["The first name field is required."],"last_name":["The last name field is required."],"email":["The email field is required."],"password":["The password field is required."],"terms_conditions":["The terms conditions must be accepted."]}}"

Not what I'm expecting since my test is about trying to register the same user (using the same email address) more than once.

But if I perform the following request:

$response = $this->withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ])->json('POST', "/api/register/",
        $user2);
dd($response->content());

The dump is:

"{"message":"The given data was invalid.","errors":{"email":["The email has already been taken."]}}"

Which is exactly what I'd expect.

Why is this happening?