MikeMacDowell

MikeMacDowell

Head of Business Systems at Anthony Best Dynamics Ltd

Member Since 4 Years Ago

Bristol

Experience Points
102,190
Total
Experience

2,810 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
883
Lessons
Completed
Best Reply Awards
24
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 21
102,190 XP
Oct
04
2 weeks ago
Activity icon

Replied to How To Custom Resources Controller With Specific Middleware

I think the only way you can specify for particular actions is in the controller with Controller Middleware

https://laravel.com/docs/5.8/controllers#controller-middleware

Alternatively you can just set up the routes twice?

Route::resource('api/tasks', 'TaskController', [
    'only' => ['update', 'destroy']
])->middleware(['tasks_view']);    

Route::resource('api/tasks', 'TaskController', [
    'only' => ['index', 'show', 'store']
]);
Activity icon

Replied to Sanity Check My Eager Loading + Filtering?

You could also do this as part of the query building when you're populating the model/collection of Audit using wherePivot.

Alternatively you can set up a new relationship on your Audit model which means you always would have access to the "Good" checks

// Audit.php
public function goodChecks()
{
    return $this->belongsToMany(Check::class)->wherePivot('result', 'Good');
}

Lastly, and this may be off base, but I'm wondering why you have a Many-to-Many relationship? Obviously without knowing the business logic behind your code structure I'm guessing, but it seems strange that an Audit can have many Checks and each Check can have many Audits.

Unless the model you are calling "Check" is actually the type of check? In that case I would restructure your models as I believe it would end up being simpler.

You'd have:

/* Audit.php */

public function checks()
{
    return $this->hasMany(Check::class);
}


/* Check.php */
// This is new, it's a first class citizen model as I believe this is what's important to you
// This would contain the status of the check and any other information that is relevant about the check
// Storing it not on a pivot table makes it easier to access everything and you can form relationships on the model too

public function audit()
{
    return $this->belongsTo(Audit::class);
}

public function type()
{
    return $this->belongsTo(CheckType::class);
}


/* CheckType.php */
// this is what you're currently calling Check

public function checks()
{
    return $this->hasMany(Check::class);
}

Just my two cents, but this is a pattern I see repeated a lot where people try to use Many-to-Many relationships when what they're really interested in is information about the join itself

Oct
01
2 weeks ago
Activity icon

Replied to Combination Of Two Column Must Unique

You can check this in validation using the "different" validation rule (if what you want is the column values to always be different, making each entry unique in the table is a different check)

https://laravel.com/docs/5.8/validation#rule-different

Activity icon

Replied to Hash:: Facade And Hash() Helper Differences?

Look at the Laravel documentation for Hashing

https://laravel.com/docs/5.8/hashing

Activity icon

Replied to How To Show Only 3 First Words Of A Text Variable ?

I wouldn't do it with regex, I'd just use split() and join() in the filter

Activity icon

Replied to Validating Unique Via Pivot Table

I think this should do it


'role' => [
    'required', 
    Rule::unique('role_user', 'role_id')->where(function ($query) {
        return $query->where('user_id', $this->user_id); 
// assuming you're sending 'user_id' in the request
    }),
]

However, if you're using sync() on the ManyToMany relationship, you don't need to check this as it will only be added once into the table anyway

Activity icon

Replied to How To Show Only 3 First Words Of A Text Variable ?

You can use split() and join() to do this

<h5 class="modal-title" id="deleteTaskModalLabel">
{{ modalTitle.split(" ", 3).join(" ") + modalTitle.split(" ").length > 3 ? "..." : "" }}
</h5>

You probably want to move this to its own function though

Activity icon

Replied to Add Dynamic Prefix In Laravel Routes Web.php

Like my previous reply, with a wildcard as a route prefix which you then check in a middleware if a valid Customer exists (or load a tenant based upon the prefix).

Route::group([
    'prefix'     => '/{customer_name}',
    'middleware' => \App\Http\Middleware\IdentifyCustomer::class,
    'as'         => 'customer:',
], function () {
    // routes here
});

Check out the link I posted for how you'd do this and load only the information for that customer on every other database request.

Sep
30
2 weeks ago
Activity icon

Replied to Add Dynamic Prefix In Laravel Routes Web.php

That's a multi-tenanted application if you're then segmenting all the data for each company based upon the URL.

IF you still want to just pre-generate all the URLs, you can do it like this, but be warned, for each company you add to the database you're duplicating all your routes again for that extra company, so if you have 100 routes, and 10 companies then you'll have 1000 routes.

Company::all()->each(function($company) {

    Route::group([
        'prefix' => $company->name, 
        'name' => $companyName . '.',
    ], function() {
    // routes go here
    });

});


Activity icon

Replied to Add Dynamic Prefix In Laravel Routes Web.php

Are you trying to create a multi-tenanted application?

Functionally doing what you ask is pretty simple, but I'm not sure you actually want to do this as what you're asking for is to create a pre-defined set of routes for every company_name, which is just going to duplicate the entire routes file across however many companies in your database (which means that the routes can't be cached etc...)

I think what you instead want, is for all routes to require a company_name as a wildcard which then triggers a tenant to be loaded for that request?

You'd do that like this:

Route::group([
    'prefix'     => '/{tenant}',
    'middleware' => \App\Http\Middleware\IdentifyTenant::class,
    'as'         => 'tenant:',
], function () {
    // Tenant routes here
});

Taken from https://ollieread.com/articles/laravel-multi-tenancy-avoiding-over-engineering which I've used to implement multi-tenancy on an application previously

Activity icon

Replied to Carbon AddDays

Carbon::now()->lastOfMonth()->addDays(37)->toDateString();

https://carbon.nesbot.com/docs/#api-addsub

Activity icon

Replied to Prevent Reactivity Of Data Once Pushed To An Array.

Can you post more of your child component? Specifically how you're setting selectedProduct and emitting it to the parent?

Sep
17
1 month ago
Activity icon

Replied to Is Mass Assignment Dangerous ?

I think you might have misunderstood some of the comments,

Laravel automatically protects you against SQL Injection Attacks because it uses PDO binding when you use Eloquent to do database transactions - this happens automatically and you don't have to worry about it as long as you're not using the DB facade or directly creating database queries.

Mass Assignment Attacks are not SQL Injection and are where you've left mistakes in your code logic to allow an attacker to exploit them by setting database fields in a way they should not be able to. The examples everyone has given are the dangers of mass assignment attacks. Typically you'd be adding an extra field into the request data on a Mass Assignment Attack, like

{is_admin = 1}

SQL Injection is where the request allows a user to enter extra SQL information into a database query to take extra actions, this usually involves pushing malformed or "clever" text into an already existing request field to take action on the database like

{name = "bob' ; drop table users;"}
Sep
16
1 month ago
Activity icon

Replied to Is Mass Assignment Dangerous ?

Laravel protects you from SQL injection if you use Eloquent.

Mass assignment is fine as long as you understand the potential issues and protect against them with validation or by using the $fillable array on a model.

It's good practice to validate the input from the user and only use the validated array to mass assign https://laravel.com/docs/6.x/validation#quick-writing-the-validation-logic

Activity icon

Replied to Vue V-for

Why don't you group your collection in your controller before returning it to the front-end. That way PHP is doing the heavy lifting on your dataset.

$data = Model::all()
    ->groupBy('carMake');

This will give you a collection like:

[
"Fólksbíll" : [
      0: {id: 1, carMake: "Fólksbíll", …},
      1: {id: 2, carMake: "Fólksbíll", …}
   ],
"Jepplingur" : [
      2: {id: 3, carMake: "Jepplingur", …}
      3: {id: 4, carMake: "Jepplingur", …},
   ],
"Jeppi" : [
      4: {id: 3, carMake: "Jeppi", …}
      5: {id: 4, carMake: "Jeppi", …}
   ]
]

Then you can loop through this collection and then each of the sub-collections if you wish

Sep
03
1 month ago
Activity icon

Replied to Is There Such Method In Collection?

You won't make that map function any simpler without PHP 7.4 where you can use short closure syntax.

There's no built in Laravel Collection method for you to do this, but you could make your own Macro.

Collection::macro('keyItems', function ($key) {
    return $this->map(function ($value) use ($key) {
        return [$key => $value];
    });
});

$animals = collect(['dog', 'cat', 'tiger']);

$columnized = $animals->keyItems('animal');

Put your Macro definition in a Service Provider and it will be available globally.

Aug
23
1 month ago
Activity icon

Replied to Self Join Query Is Too Slow

Do you have Models set up? This could be achieved using Eloquent without having to do a massive SQL join (which is probably what's taking the time, but without a similar recordset I can't tell you for sure).

What are you trying to achieve? Some background of the business logic you're trying to implement will help with understanding possible solutions.

Activity icon

Replied to More Than One Listener On Events

Can you post the whole Listener class? Makes it easier to look at and try to see the problem

Aug
22
1 month ago
Activity icon

Replied to More Than One Listener On Events

@orion in reference to your second paragraph, surely that defeats the object of having events - if you're just going to essentially call a method which dispatches different jobs, you can call that method from wherever you're dispatching the event (obviously excepting that you can fire an event from anywhere).

The way shown here is a framework recommended way of handling multiple required outcomes of an event - especially if those outcomes are dependant upon each other in some way, you can stop the event propagating to further listeners. Even if they are not dependent upon each other, you're isolating single responsibilities in response to an event to a given listener, and then you can couple the same listener to another event or events.

By putting all your jobs in a single listener it's no longer reusable and you're just using events as a tool to essentially call a single method?

Happy to discover and learn your reasonings behind your approach.

Activity icon

Replied to More Than One Listener On Events

Nothing looks incorrect in your EventServiceProvider.

Can you post your first listener class?

Aug
13
2 months ago
Activity icon

Replied to SELECT The Newest (latest) Query FOREACH Location

Look at HasManyThrough relationships https://laravel.com/docs/5.8/eloquent-relationships#has-many-through

They should do what you need, though you'll need to fiddle with the foreign keys a bit to get it to work.

Aug
12
2 months ago
Activity icon

Replied to Using A Non-unique Route Key Name?

If you're talking about this in the context of Route Model Binding, you can use the following on your model - code from Laravel docs Route Model Binding

/**
 * Retrieve the model for a bound value.
 *
 * @param  mixed  $value
 * @return \Illuminate\Database\Eloquent\Model|null
 */
public function resolveRouteBinding($value)
{
    return $this->where('sequence', $value)
                 ->where('org_id', /* however you get your org_id */)
                 ->first() ?? abort(404);
}
Jul
12
3 months ago
Activity icon

Replied to File In Console Directory Loses Value Inside Another Function?

You're not referring to the $accessToken in the Class, you're creating a new local variable in your constructor.

$accessToken = config('values.accessToken');

should be

$this->accessToken = config('values.accessToken');
Activity icon

Replied to Foreign Key With 2 Columns

Why do you need two foreign keys?

Your ddt_id references a single record in your first table, that's enough to give you the unique record you require.

Feb
21
7 months ago
Activity icon

Replied to Using A ManyToMany With Additional Pivot Fields - Dedicated Model Or Not?

@BARRYJAMES - Hi, sorry for long time not responding, been away and missed your reply!

What's your workflow that a user would be running through? Are you creating users to be linked to properties? Or are you linking yourself or existing users to properties?

Feb
11
8 months ago
Activity icon

Replied to "No Query Results For Model [App\WorkExperience\WorkExperience] {id}"

Your url is wrong in the ajax request

url: "/workexperiences/{id}", 

You actually need to put the id you want to load from the database

Activity icon

Replied to Using A ManyToMany With Additional Pivot Fields - Dedicated Model Or Not?

@barryjames if you're looking to treat PropertyUser as a first class citizen, i.e. with it's own controller and the ability to edit it directly, changing the user and/or property and the type attribute, I would make it its own model and not use a pivot table and belongsToMany relationship.

Make a PropertyUser model and table which belongsTo a User and belongsTo a Property and has the type field as an attribute.

Jan
29
8 months ago
Activity icon

Replied to Search According To Keys Defined In Laravel Resource Collection

@SARMADINDHAR - It doesn't look like it - because the ResourceCollection is acting as a presenter and doesn't actually create the transformation until it's being returned as an array or JSON.

And I probably agree with the implementation, what you're handing to the ResourceCollection should be determined by your application logic, with the ResourceCollection only responsible for formatting the output to keep it consistent. It's not a full Collection implementation.

You'll have to add the transformations as accessors in your model in order to filter the collection down.

I'm also not sure what you gain by doing what you're attempting, why can't you put a filter on the jobs relationship?

// Technician.php

public function jobs()
{
    return $this->hasMany(Job::class);
}

public function completedJobs()
{
    return $this-jobs()->where('status', 'completed');
}
$technician=Technician::findOrFail(1);
$data=TechnicianJobResource::collection($technician->completedJobs);
Activity icon

Replied to Search According To Keys Defined In Laravel Resource Collection

@SARMADINDHAR - Having had another look at the code, it appears you can't do what you're asking.

You need to filter down the initial collection before handing it to the resource collection.

$technician=Technician::findOrFail(1);
$data=TechnicianJobResource::collection(
    $technician->jobs->where('request_status','completed')
);

Activity icon

Replied to Search According To Keys Defined In Laravel Resource Collection

@SARMADINDHAR - What didn't work? Are you getting any errors?

Activity icon

Replied to Search According To Keys Defined In Laravel Resource Collection

@sarmadindhar you're extending Resource instead of ResourceCollection which is what you need to do as you're trying to then filter the collection down.

You'll also need to change the ->findOrFail to ->get()

Activity icon

Replied to Looping Through A Json Object?

@SKOOBI - I think your problem is occurring because you're calling json_decode on a collection of activities

// Get the record
$data = CustomerActivity::where('user_id', $user->id)->get(); // This returns a collection as ->get() always returns a collection
$activities = json_decode($data); // This is json_decoding a collection, when you want to json_decode a column in each model in this collection

Add this as an accessor in your model file, it will json_decode the value from the database when you want to use it

// CustomerActivity.php
public function getDataAttribute($value)
{
    return json_decode($value);
}

The this will work

@foreach($activities as $activity)
<tr>
    <td>{{ \Carbon\Carbon::parse($activity->created_at)->format('d/m/Y H:i:s') }}</td>
    <td class="textLeft">
         <strong style="text-transform: capitalize;">Old</strong>:: {{ $activity->data['old']['telephone'] }} <br>
        <strong style="text-transform: capitalize;">New</strong>:: {{ $activity->data['new']['telephone'] }}
    </td>
</tr>
@endforeach 
Jan
28
8 months ago
Activity icon

Replied to Looping Through A Json Object?

@skoobi at its simplest, you'll end up with an 'old' array and a 'new' array in php once you've run the activity back through json_decode,

So a simple way to get the diff displayed would be

// get $data from database previous to this point

$activity = json_decode($data);

$keys = array_keys(array_merge($activity['old'], $activity['new']));

// activity.blade.php

<table>
<tr>
<th>Key</th>
<th>Old</th>
<th>New</th>
</tr>

@foreach($keys as $key)
    <tr>
        <td>{{ $key }}</td>
        <td>{{ $activity['old'][$key] ?? 'N/A' }}</td>
        <td>{{ $activity['new'][$key] ?? 'N/A' }}</td>
    </tr>
@endforeach
<table>
Jan
18
9 months ago
Activity icon

Replied to Eager Load Same Type Siblings With Different Children

@WMD - You can just treat the the travelers variable as a standard variable and assign to it. This has no adverse effects unless you refresh the model, in which case it's overwritten.

$merge = $order_data->travelersWithOverride->merge($order_data->travelersWithoutOverride);

$order_data->travelers = $merge;

I'm curious though at this approach, why does this not work for you

$order_data = Orders::with([    
'travelers' => function ($q){
    $q->with(
           'ticket.package.info1',
           'ticket.package.info2',
           'ticket.package.info3',
       'ticket.info1',
           'ticket.info2',
           'ticket.info3'  
    )
    ->WhereNull('override')
    ->orWhere('override', 1);
   })
])->find($id);

As this returns the collection you're getting by merging the two other collections together

Jan
17
9 months ago
Activity icon

Replied to Eager Load Same Type Siblings With Different Children

@WMD - You can achieve this in a couple of ways, but the best way would be to create an accessor which loads the relationships and returns them.

public function getAllTravelersAttribute()
{
    return $this->travelersWithOverride->merge($this->travelersWithoutOverride);
}
Jan
16
9 months ago
Activity icon

Replied to Eager Load Same Type Siblings With Different Children

@wmd create a relationship for travellers with an override and travellers without.

In your Orders.php Model

public function travelers()
{
    return $this->hasMany(Travelers::class); // assuming this existing relationship
}

public function travelersWithOverride()
{
    return $this-travelers()->where('override', 1);
}

public function travelersWithoutOverride()
{
    return $this-travelers()->whereNull('override');
}

Then in your controller:

$order_data = Orders::with([    
'travelersWithoutOverride' => function ($q){
    $q->with(
           'ticket.package.info1',
           'ticket.package.info2',
           'ticket.package.info3'
    );
},
    'travelersWithOverride' => function ($q){
        $q->with(
           'ticket.info1',
           'ticket.info2',
           'ticket.info3'               
        );
}
])->find($id);
Activity icon

Replied to Another Shot At Clarity

@XTREMER360 - Yes, your relationships for Room and Property would have to change.

class Room extends Model
{
    /**
     * Get the properties that are assigned to the room.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function propertyRooms()
    {
        return $this->hasMany(PropertyRoom::class, 'room_id');
    }
}
class Property extends Model
{
    /**
     * Get the properties that are assigned to the room.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function propertyRooms()
    {
        return $this->hasMany(PropertyRoom::class, 'property_id');
    }

And then you'd have to modify the test to something like:

/** @test */
    public function an_administrator_can_create_a_new_observation_for_a_room_at_a_property_belonging_to_their_business_unit()
    {
        // $this->withoutExceptionHandling();
        $signedInUser = factory(User::class)->states('administrator')->create();
        $property = factory(Property::class)->create(['business_unit_id' => $signedInUser->businessUnit->id]);
        $property->propertyRooms()->create([
        'room_id' => $property->businessUnit->rooms()->first()->id,
        'room_name' => Room::default()->first()->name
    ]);

        $response = $this->actingAs($signedInUser)->json('POST', '/properties/'.$property->id.'/rooms/'.$property->propertyRooms->first()->room_id.'/observations', []);

        $response->assertStatus(201);
        $this->assertCount(1, $property->rooms->first()->observations);
    }

Those changes would make it work I think.

However I'd consider just passing through the ID of the PropertyRoom to the controller rather than the Property and Room IDs.

Personally I'd rename PropertyRoom to just Room, and Room to RoomType. Because your "Room" model currently describes a type of room, not an actual, physical room, whereas PropertyRoom is currently the physical room on which Observations are being made.

Activity icon

Replied to Is There A Way To Put This In An Eloquent Collection Method?

@erik your group by returns a collection of collections, which means you can do something like this

$invoices = Invoice::query()
    ->whereIn('charter_id', $charters)
    ->where('status', Invoice::STATUS_PAID)
    ->whereNotNull('payment_date')
    ->orderBy('payment_date')
    ->get()
    ->groupBy(function (Invoice $invoice) {
        return Carbon::parse($invoice->payment_date)->format('M-Y');
    });

$revenue = $invoices->map(function($group) {
    return $group->sum(function(Invoice $invoice) {
        return $invoice->total();
    });
});

If you want a collection of years with each containing a collection of months, you can do two group bys on the original collection like

$invoices = Invoice::query()
    ->whereIn('charter_id', $charters)
    ->where('status', Invoice::STATUS_PAID)
    ->whereNotNull('payment_date')
    ->orderBy('payment_date')
    ->get();

$years = $invoices
    // Creates a collection of years
    ->groupBy(function (Invoice $invoice) {
            return Carbon::parse($invoice->payment_date)->format('Y');
        })
    // map across this collection, so each time we have a collection of invoices in that year
    ->map(function($group) {
        // group this collection by months
        return $group->groupBy(function(Invoice $invoice) {
            return Carbon::parse($invoice->payment_date)->format('M');
        })
        // then map across each month and sum the invoices
        ->map(function($group) {
            return $group->sum(function(Invoice $invoice) {
                return $invoice->total();
            });
        });
    });
    

Hopefully that works, typing it from memory so they may be something not quite correct with it.

Activity icon

Replied to Another Shot At Clarity

@XTREMER360 - You can't do this

$propertyRoom = PropertyRoom::where(['property_id' => $property->id, 'room_id' => $room->id])->first();

As PropertyRoom extends Pivot, which can't be instantiated in this way.

Make PropertyRoom a full Model if you want to have access to it without going through either of its parents. Obviously you'll lose the easiness of a ManyToMany Relationship between Property and Room, but having PropertyRoom as a full Model makes it easier to deal with if you're trying to attach Observations to it and treat it like a 1st class citizen (which it appears you are by your code).

Jan
11
9 months ago
Activity icon

Replied to Carbon - Get Date Depending On Now() Value

@nickdavies07 try

Carbon::createMidnightDate(Carbon::now()->subMonths(8)->year, 9, 1)

This gets the current date, removes 8 months from it to get the correct year as your "year" starts on 1st September and then creates a midnight time date for the 1st September that year

Jan
10
9 months ago
Activity icon

Replied to Location.href

@davy_yg You're opening new php tags inside a blade template tags, which already give you access to PHP.

'{{ url("/form/".<?php echo $data["detail_id"]; ?>) }}'

Try instead

'{{ url("/form/". $data["detail_id"]) }}'

Also, any reason you're not using an anchor tag instead of a button and javascript?

Activity icon

Replied to Define Permissions From Database

Just put a check for running in the console in the boot method

    public function boot()
    {
        $this->registerPolicies();

        if (!app()->runningInConsole()) {
        // Register the permissions here
        }
    }
Activity icon

Replied to Trouble Understanding Dependency Injection

Hi @micahwallace - in your ApifyServiceProvider you're passing the variables in as an array, but your Option A constructor is expecting two parameters.

Change back to Option A and make the service provider code as below

    public function register()
    {
        $this->app->singleton(Apify::class, function ($app) {
            $config = config('services.apify');
            return new Apify($config['user_id'], $config['token']);
        });
    }
Jan
09
9 months ago
Activity icon

Replied to Difficult Polymorphic Relationships

@xtremer360 no, you'd have 50 records with a room_type_id that relates to the RoomTypes table which has a name of Kitchen.

Essentially you're creating instances of a RoomType as your Rooms, instead of just defining a pivot table between RoomType (what you're currently calling Room) and House

Activity icon

Replied to Convert A Collection Or Object To An Array

@majeed use unique on the collection

$data=Auth::user()->roles()->with('permissions')->get()->pluck('permissions')->flatten()->unique();
Jan
08
9 months ago
Activity icon

Replied to Convert A Collection Or Object To An Array

@majeed

$data=Auth::user()->roles()->with('permissions')->get()->pluck('permissions')->flatten();

This will remove the "double" array, as you're getting a collection of roles and then plucking 'permissions' which returns an array itself.

Activity icon

Replied to Difficult Polymorphic Relationships

@xtremer360 for what you're trying to achieve I don't think your relationship structure is the best.

Because you're making observations about specific rooms, a room seems important enough to be a model, not just an entry in a pivot table.

I'd have models for House, Room, RoomType, Observation with relationships:

House hasMany Room - Room belongsTo House Room belongsTo RoomType - RoomType hasMany Room Observation belongsTo Room - Room hasMany Observation

This avoids a pivot table to which you're trying to attach a relationship, in my mind as soon as you're trying to do this for a non-trivial reason, the pivot table deserves to be its own model.

Nov
06
11 months ago
Activity icon

Replied to Element UI Data Attribute Not Getting Updated On Submission

@mjoseph you're not setting the value of getNID anywhere apart from

submitUpload(notificationId) {
                this.getNID = notificationId;
                // File upload trigger submit
                document.getElementById('my-custom-btn').click();
            },

which isn't being called anywhere in your code, so it will always be using the initial value which is 12...

Activity icon

Replied to Failed Sending Email When Using Microsoft Exchange Email Account

@klmat what Port and Encryption are you using?

And do you have a domain prefix requirement for the username on the exchange server?

We have this working internally with no issues, so it does work.

Who are you trying to send the email as? The account you're using to authenticate must have permission to send as the 'from' address in mail.php or whatever from address you're setting when you send the email.