BarryJames

BarryJames

Member Since 2 Weeks Ago

Experience Points 2,240
Experience Level 1

2,760 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 21
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.

22 Feb
19 hours 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
1 week 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
2 weeks 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!