BarryJames

BarryJames

Member Since 4 Months Ago

Experience Points 3,430
Experience Level 1

1,570 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 31
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

20 Jun
5 days ago

BarryJames left a reply on Vuelidate And @blur Not Working Correctly.

After finding an article from 2017... I finally found the answer..

use v-model.lazy="data"

Should anyone run into the same problem. It seems Vuelidate doesn't handle @blur correctly when using an asynchronous validator.

Thanks!

BarryJames left a reply on Vuelidate And @blur Not Working Correctly.

Thanks guys! Although it didn't work..

Can I just find out - when you try something like this does it (@blur) function as expected? I mean using a custom unique validation?

I want to find out perhaps it's my browser or something...

Cheers!

19 Jun
6 days ago

BarryJames left a reply on Vuelidate And @blur Not Working Correctly.

Yep, just did that and still the same results.

      required,
      email,
      unique: function (value) {
        if (value === '') return true
        return new Promise((resolve, reject) => {

          return axiosGuest.get('users/' + this.users[this.selectedUser].id + '/email-exists-exc?email=' + value)
            .then(response => {
              if (response.data.email) {
                return true
              }
            })
            .catch(error => {
              if (error.response.data.error.email[0] == 'The email has already been taken.') {
                return false
              }
              return true
            })
        })
      },
    },

BarryJames left a reply on Vuelidate And @blur Not Working Correctly.

Strangest thing! I turned on my machine tonight and the validation is working... That solves problem number one (although I'm a little worried about when this might happen again...)

Although I have recreated my @blur event that sends a GET request on every keystroke using a lot of different methods and it still does that... Is this perhaps a limitation with Vue and custom validations?

BarryJames started a new conversation Vuelidate And @blur Not Working Correctly.

Hey coders! I'm building a Vue front-end using a Laravel back-end and I seem to have run into two problems,

(1) When I have my create new user the Vuelidate works like a charm, but when I use the same validation logic on my edit user form - it doesn't run. It seems that when I pre-populate the fields using props the vuelidate $error doesn't trigger - although the $model does change.. Any ideas? Is this a bug with Vuelidate or am I doing it wrong?

(2) My @blur event runs properly on every property except for my custom validation 'unique' - which sends a GET request on every keystroke.

I have Googled for days without finding anything that mentions this and would really appreciate your help on this :)

Ok so take into consideration that I pass two props into this component with an array of users and a number containing the selected user's index in that array...

Here is my simplified script in my component for Edit User:

<script>
import { required, email, minLength } from 'vuelidate/lib/validators'
import axios from 'axios'
export default {
  data() {
    return {
      name: this.users[this.selectedUser].name,
      email: this.users[this.selectedUser].email
    }
  },
  props: {
    users: {
      type: Array,
      required: true
    },
    selectedUser: {
      type: Number,
      required: true
    }
  },
  validations: {
    name: {
      required: true,
      minLength: minLength(2)
    },
    email: {
      required: true,
      email,
      unique: value => {
        if (value === '') return true
        return axios.get('email-exists?email=' + value)
          .then(response => {
            return !response.data
          })
          .catch(error => {
            console.log(error)
          })
      }
    }
  },
  methods: {
    updateUser() {
      // axios request...
    }
  }
}

And here is my simplified HTML in my component in Edit User:

<template>
  <form @submit.prevent="updateUser">
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" id="name" class="form-control" :class="{'is-invalid': $v.name.$error}" @blur="$v.name.$touch()" v-model="name">
      <span v-if="!$v.name.error" class="invalid-feedback" role="alert">
        <strong v-if="!$v.name.minLength">Please enter a valid first name</strong>
        <strong v-if="!$v.name.required">Please enter your first name</strong>
      </span>
    </div>
    <div class="form-group">
      <label for="email">Email</label>
      <input type="email" id="email" class="form-control" :class="{'is-invalid': $v.email.$error}" @blur="$v.email.$touch()" v-model="email">
      <span v-if="!$v.email.error" class="invalid-feedback" role="alert">
        <strong v-if="!$v.email.email">Please enter a valid email address</strong>
        <strong v-if="!$v.email.unique">This email address already exists</strong>
      </span>
    </div>
    <button type="submit" class="btn btn-primary" :disabled="$v.$invalid">Update User</button>
  </form>
</template>

Thank you in advance! Maybe I am missing something here?

10 Mar
3 months ago

BarryJames left a reply on Pivot With A One To Many Relationship

Excellent news! Thanks @

BarryJames started a new conversation Pivot With A One To Many Relationship

Howdy

I'm building a web app and have a many to many relationship between users and properties. The pivot is called 'property_user'

There is an additional attribute named 'type' which I want to like to another table named 'property_user_types' which will contain the values to choose from.

Can this be done?

22 Feb
4 months ago

BarryJames left a reply on Using A ManyToMany With Additional Pivot Fields - Dedicated Model Or Not?

@mikemacdowell - No worries, I was over-complicating. Decided to just go with leaving the the two models separate and only have a controller to show the pivot data. Creating and updating the models are done separately.

Thanks again!

11 Feb
4 months ago

BarryJames left a reply on Using A ManyToMany With Additional Pivot Fields - Dedicated Model Or Not?

@mikemacdowell This is what I would of done thinking in vanilla OOP terms:

$users = DB::table('users')
            ->join('property_users', 'users.id', '=', 'property_users.user_id')
            ->join('property', 'property_users.property_id', '=', 'property.id')
            ->select('users.*', 'properties.*', 'property_user.type')
            ->get();

I'm guessing this isn't the Laravel way, and I would want to do it the Laravel way, but the above seems somewhat busy.

Or am I on the right track?

BarryJames left a reply on Using A ManyToMany With Additional Pivot Fields - Dedicated Model Or Not?

This seems a little complex. I have followed the above instructions and am now trying to store a PropertyUser - which means I need to create the user first. So I will need to use Transactions I'm guessing, since I don't want a user without the entry in the PropertyUsers table. My code:

    public function store(Request $request, Property $property)
    {
        $valid_data = request()->validate([
            'firstname'     => ['required', 'string', 'min:2', 'max:50'],
            'lastname'      => ['required', 'string', 'min:2', 'max:50'],
            'email'         => ['required', 'email', 'max:150', 'unique:users'],
            'password'      => ['required', 'string', 'min:6', 'confirmed'],
            'type'          => ['required', 'string',
                Rule::in(['owner', 'tenant', 'agent'])
            ]
        ]);

        $valid_data['password'] = Hash::make($valid_data['password']);

        DB::transaction(function ($valid_data) {

            $user = DB::table('users')->create([
                'firstname' => $valid_data['firstname'],
                'lastname' => $valid_data['lastname'],
                'email' => $valid_data['email'],
                'password' => $valid_data['password'],
            ]);

            DB::table('property_users')->create([
                'user_id' => $user->id,
                'property_id' => $property->id,
                'type' => $valid_data['type']
            ]);

        });

        return redirect()->route('admin.propertyusers.index', $property);
    }

I have watched the videos on transactions and read the docs but I can't get this to work. The first exception was that $valid_data was undefined, then I inserted it into the function closure, but not the exception reads "cannot use object of type mysqlconnection as array.

I know Jeff usually says that things shouldn't get too complex, and I fear this might be hitting that upper limit.

Any ideas of what I'm doing wrong?

BarryJames left a reply on Using A ManyToMany With Additional Pivot Fields - Dedicated Model Or Not?

Hi @mikemacdowell thanks for the response. That sounds just crazy enough that it might work. Didn't even think of that, but yes I definitely want it as a first class citizen, since this entity will be used predominantly throghout my site.

This is brilliant!

BarryJames started a new conversation Using A ManyToMany With Additional Pivot Fields - Dedicated Model Or Not?

Hi I'm afraid I've complicated things and now I'm a little stuck, have read many articles but still cannot find the solution. So I have 2 resources - Users and Properties. It's a many to many as each owner can have many properties and each property can have many users.

My User Model:

class User extends Authenticatable
{
    public function properties()
    {
        return $this->belongsToMany(Property::class)->withPivot('type')->withTimestamps();
    }
}

My Property model:

class Property extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot('type')->withTimestamps();
    }
}

My pivot table:

class CreatePropertyUserTable extends Migration
{
    public function up()
    {
        Schema::create('property_user', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->index();
            $table->unsignedInteger('property_id')->index();
            $table->string('type', 50);
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('property_id')->references('id')->on('properties')->onDelete('cascade');
        });
    }
}

You can see from the above there is an additional field named 'Type' on the pivot table. This can be either 'Owner', 'Tenant', 'Agent'

Now when it comes to my Controller for showing the resource of the PropertyUsers, my route keeps track of the property and user, which means my controller also needs this with the edit function:

    public function edit(Property $property, User $user)
    {
        $user = User::whereHas('properties', function ($q) use ($property) {
            $q->where('id', $property->id);
        });

        return view('admin.propertyusers.edit')->withProperty($property)->withUser($user);
    }

This however doesn't work. I need the specific property user where the property equals that property and the user equals that user, then I need to show the 'type' field in the edit form so that I can change them to one of the other types if needed.

My problem is that no matter what I try the I cannot get the related table populated in my queries.

Also, it seems cumbersome to use a controller that needs two resources to compute queries and CRUD.

Any input would be greatly appreciated!

Cheers

06 Feb
4 months ago

BarryJames started a new conversation Using WherePivot Only If $value Present ?

Hi guys

I have been scratching my hair and searched 50% of the entire web for a solution to this, but perhaps I'm going about this wrong... Any help would be tremendously appreciated! - wouldn't ask if it wasn't completely necessary..

public function users($type = null)
    {
        return ! $type ? $this->belongsToMany(User::class)->withPivot('type') : $this->belongsToMany(User::class)->withPivot('type')->wherePivot('type', $type);
    }

I currently have 2 functions - one where there is no $type and no wherePivot - and another where there is $type and withPivot - which works fine. But then I thought, surely there must be a way to have one function to do both tasks?

Thanks!