bigweld86

bigweld86

Member Since 2 Years Ago

Experience Points
8,510
Total
Experience

1,490 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,510 XP
Nov
17
1 day 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
1 week 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
3 weeks 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
1 month 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
1 month 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
1 month 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
3 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
3 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?

Jul
10
4 months ago
Activity icon

Commented on Building The Layout

Nevermind. When running npx tailwind init a config file called tailwind.config.js is created, but when compiling it's trying to get tailwind.js (without .config) so that's why it's failing. I simply renamed the config file to be tailwind.js and voilá, it works

Activity icon

Commented on Building The Layout

I added the directives into app.scss, then installed laravel-mix-tailwind and added the code to webpack.mix.js but when compiling an error is thrown.

/Users/bigweld/Desktop/webdev/vue/assetsProject/node_modules/webpack-cli/bin/cli.js:93
                throw err;
                ^

Error: Specified Tailwind config file "/Users/bigweld/Desktop/webdev/vue/assetsProject/tailwind.js" doesn't exist

Any suggestion?