MikeMacDowell

MikeMacDowell

Member Since 3 Years Ago

Bristol

Senior Engineer at Anthony Best Dynamics Ltd

Experience Points 73,140
Experience Level 15

1,860 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 628
Lessons
Completed
Best Reply Awards 18
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.

21 Feb
2 months ago

MikeMacDowell left a reply on 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?

11 Feb
3 months ago

MikeMacDowell left a reply on "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

MikeMacDowell left a reply on 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.

29 Jan
3 months ago

MikeMacDowell left a reply on 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);

MikeMacDowell left a reply on 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')
);

MikeMacDowell left a reply on Search According To Keys Defined In Laravel Resource Collection

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

MikeMacDowell left a reply on 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()

MikeMacDowell left a reply on 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 
28 Jan
3 months ago

MikeMacDowell left a reply on 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>
18 Jan
4 months ago

MikeMacDowell left a reply on 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

17 Jan
4 months ago

MikeMacDowell left a reply on 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);
}
16 Jan
4 months ago

MikeMacDowell left a reply on 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);

MikeMacDowell left a reply on 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.

MikeMacDowell left a reply on 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.

MikeMacDowell left a reply on 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.

11 Jan
4 months ago

MikeMacDowell left a reply on 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

10 Jan
4 months ago

MikeMacDowell left a reply on 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?

MikeMacDowell left a reply on 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
        }
    }

MikeMacDowell left a reply on 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']);
        });
    }
09 Jan
4 months ago

MikeMacDowell left a reply on Difficult Polymorphic Relationships

@XTREMER360 - @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

MikeMacDowell left a reply on Convert A Collection Or Object To An Array

@MAJEED - @majeed use unique on the collection

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

MikeMacDowell left a reply on 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.

MikeMacDowell left a reply on 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.

06 Nov
6 months ago

MikeMacDowell left a reply on 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...

MikeMacDowell left a reply on 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.

MikeMacDowell left a reply on Using ViewComposers When Each View Is Made Up Of Multiple Templates

@thebigk Assuming that you're actually using the data from the composer in each of your views, you can register a ViewComposer as a singleton which will stop it doing multiple DB queries.

class MyViewComposer
{
    protected $data;

    public function __construct()
    {
        $this->data = Data::all();
    }

    public function compose(View $view)
    {
        $view->with('data', $this->data);
    }
}
class ViewDataServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        view()->composer('view.name', MyViewComposer::class);
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        $this->app->singleton(MyViewComposer::class);
    }
}

This means when MyViewComposer is requested the first time, it will be constructed and the database queries will run - it will then be registered in the container as a singleton, which means any further references to it for the duration of the request will pull the instantiated object out of the container instead of new-ing it up again.

24 Oct
6 months ago

MikeMacDowell left a reply on Call To Undefined Relationship On Model - But It Is Definitely(!) Defined!

@craigivemy Your relationship is called "serviceCategories" not "service_categories".

The ->with() method takes the actual name of the relationship method, not the snake case version.

MikeMacDowell left a reply on Need To Assign My Vendor's ID To InvoiceTable - One To Many Relationship

<select id="vendor_id" name="vendor_id" v-model="form.vendor_id" type="text" class="form-control" :class="{ 'is-invalid': form.errors.has('vendor_id')}">
        <option disabled selected>Please Select Vendor</option>
        <option v-for="vendor in vendors" :key="vendor.id" :value="vendor.id">{{ vendor.vendor_company_name }}</option>
      </select>

That should work, the v-model tag needs to refer to the object in your data in the Vue Component.

MikeMacDowell left a reply on Need To Assign My Vendor's ID To InvoiceTable - One To Many Relationship

@partabsaifzakir yes there is, I didn't notice that before. You need v-model on the select.

MikeMacDowell left a reply on Need To Assign My Vendor's ID To InvoiceTable - One To Many Relationship

@partabsaifzakir what's not working? This should work and put the vendor_id in the database for each TicketInvoice.

However, there may be a typo issue in your select options:

<option v-for="vendor in vendors" :key="vendor.id" :value="vendor.vendor_id">{{ vendor.vendor_company_name }}</option>

Should have

:value="vendor.id

in it instead of vendor.vendor_id?

MikeMacDowell left a reply on Get A 404 Error When Making A Request Via New Route

@Someone2088 I'm not sure what else to suggest, you'll just have to take a logical approach to debugging - maybe clear out everything in the Controller method and then add it all back in slowly.

Keep checking the log file as this will show any errors that are being thrown.

Hope you find the problem!

MikeMacDowell left a reply on Get A 404 Error When Making A Request Via New Route

@Someone2088 okay, that's the javascript errors caused by the 404 I'm assuming.

You can run "php artisan route:list" from the console to view a list of routes for the project. This should give you some idea as to possible conflicts.

You can use the --name= option to filter down the list of routes too.

It's also possible to look in storage/logs/laravel.log and see the 404 error, this should have a PHP stack trace for the error too.

MikeMacDowell left a reply on Saving Multiple Records In DB - One To Many Relationship

@partabsaifzakir I would, it's not serving any purpose because you don't know the id of the TicketInvoice before it's created.

MikeMacDowell left a reply on Get A 404 Error When Making A Request Via New Route

@Someone2088 what's the exact 404 message being returned? Can you see a stack trace as part of it? That should give you a hint as to which Controller and method are being called.

MikeMacDowell left a reply on Saving Multiple Records In DB - One To Many Relationship

You're not accessing the TicketInvoiceItems data correctly in the request. You're currently doing:

$ticketInvoiceItems - > push(new TicketInvoiceItems([
        'ticket_invoice_id' => $request['ticket_invoice_id'],
        'passenger_name' => $request['passenger_name'],
        'ticket_no' => $request['ticket_no'],
        'departure_date' => $request['departure_date'],
        'fares' => $request['fares'],
        'sub_total' => $request['sub_total']
      ]));

But your request data you're sending back from the front end has all of this wrapped up in an array of ticketInvoiceItems.

So you need to do something like:

foreach($request['ticketInvoiceItems'] as $invoiceItem) {
    $ticketInvoiceItems - > push(new TicketInvoiceItems([
            'ticket_invoice_id' => $invoiceItem['ticket_invoice_id'],
            'passenger_name' => $invoiceItem['passenger_name'],
            'ticket_no' => $invoiceItem['ticket_no'],
            'departure_date' => $invoiceItem['departure_date'],
            'fares' => $invoiceItem['fares'],
            'sub_total' => $invoiceItem['sub_total']
      ]));
}

I'm also not sure why you're explicitly setting 'ticket_invoice_id' on the TicketInvoiceItems as this will get populated by the saveMany() method.

MikeMacDowell left a reply on Merge Multiple Array Values

@Kaustubh there's two options, you can either just loop through the array and set up new object and assign in the variables.

Alternatively you can use reduce on the array like below:

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)

let result = arr.reduce((result, item) => {
    result.view |= item.view;
    result.edit |= item.edit;
    result.delete |= item.delete;
    return result;
}, { view: false, edit: false, delete: false});

You could go one step further and loop over the object inside the reduce function if you have lots of keys by using Object.keys().each().

MikeMacDowell left a reply on Get A 404 Error When Making A Request Via New Route

@Someone2088 it's purely speculation based on your error and my experiences, but usually you get a 404 in this situation where your new route URI satisfies a previous route in the routes file.

Example:

Route::get('posts/{id}', '[email protected]');
Route::get('posts/no-replies', '[email protected]');

If you have these two routes in your routes file, when hitting the URI /posts/no-replies it takes the "no-replies" as the wildcard {id} from the first route, and hits the store method first, because this pattern matches this route. This would lead to a 404 because no resources with id = 'no-replies' exists.

This is because the routes file is parsed top to bottom to match the current URI.

To avoid this problem, place specific routes before wildcard routes that they would match against

Route::get('posts/no-replies', '[email protected]');
Route::get('posts/{id}', '[email protected]');

This arrangement will solve this problem.

Hopefully that's your issue.

19 Oct
7 months ago

MikeMacDowell left a reply on Simple Html With Vue.js Not Working

Your html needs to come before your script tag containing the new Vue instance.

Like:

<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js">
</script>

<div id="my_view">
{{ name }}
</div>

<script>

var myModel = {
  name: "Ashley",
  age: 24
};

var myViewModel = new Vue({
  el: '#my_view',
  data: myModel
});

</script>
</body>
17 Oct
7 months ago

MikeMacDowell left a reply on Optimizing Query Using Chunk

@eddy1992 as an alternative you can chunk the original DB query to limit the memory usage.

DB::table('products1')->where('startdate', '>', $newdates)->chunk(100, function ($products) {
        collect($products)->map(function($item){ 
            unset($item->multi_new);
            unset($item->subCategoryId);
            return (array) $item; 
        })->toArray();

    $add = DB::table('advertisements')->insert($data);
});

MikeMacDowell left a reply on Issue Retrieving Posts With A Category Name Using WhereHas

The latest method in the query build takes the name of the column you want to sort by, so when you're doing

->latest(5)

It's taking 5 as the name of the column (by default it uses 'created_at' as the column for this).

What you're trying to do it sort by latest, and then get 5 records, so what you need to do is use the take() method to only get 5 results:

$footerClassesPosts = Post::whereHas("postcategory", function($q){
                $q->where("name","=","Clases");
                })->latest()->take(5)->get();

MikeMacDowell left a reply on Getting File From Storage Problem

Sorry, my bad, the storage helper function is

storage_path($path)

Your latest issue is caused because you're plucking from a Query Builder, which will return a collection, not a single item. This means that the collection is being cast to an array when you're putting it into the string to download the file.

Try

$file = \App\Downloads::where('slug', $slug)->first()->file;
        return Storage::download('app/public/download/' . $file);
16 Oct
7 months ago

MikeMacDowell left a reply on Getting File From Storage Problem

@SiNi_Si the helper for the storage location is

storage($filePatch)

You're trying to use

download($filePath)

You want:

return response()->download(storage('download/' . $file->path));

MikeMacDowell left a reply on How Much Eager Loading Is Too Much?

@jpeterson579 it depends what you're using it for and whether it slows down your requests.

In your case, if the query

Reservation::where('customer_id', Auth::user()->id).......->get()

is loading 200+ records, I'd be considering whether I could reduce this initial load, rather than removing the eager loads. Can you paginate this into 10/20/50s? Does it affect the user experience to do this?

Also a tip, if you're eager loading multiple levels down, you don't need to include the initial levels on their own, as they are automatically loaded.

$reservations = Reservation::where('customer_id', Auth::user()->id)
->with('trip.company.terms')->get();

Will give you access to Trip, Company and Terms down the relationships.

05 Oct
7 months ago

MikeMacDowell left a reply on Undefined Variable: Request

@amin93je you're within a closure (anonymous function) for that line of your code, so you need to "use" the request variable to be able to access it, like below

$seekers = $seekers->join('job_seeker_education', function ($join) use ($request)
                    {
                        $join->on('job_seekers.id', '=', 'job_seeker_education.seeker_id')
                             ->whereRaw("job_seeker_education.institute like '%".$request->session()->get('search_institute')."%'");
                    })  
04 Oct
7 months ago

MikeMacDowell left a reply on New Email Verification Question

I guess you'd have to store a token against each user and then any links emailed out need to contain that token which can be used to silently login the correct user before doing anything else on the request.

MikeMacDowell left a reply on New Email Verification Question

I don't see why you'd want to make it that way, it's a pretty big security hole to not force users to re-login on new devices.

MikeMacDowell left a reply on Events Fired Via $dispatchesEvents Are Receiving Stale Data

@Dalma I'm pretty sure this is because you've already loaded the status relationship and it's using this loaded relationship in your event model even though you've changed the underlying status_id column.

To fix it, you can either not load the relationship before doing the update or call ->fresh() on the model in the event.

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\Project;

class ProjectSaved
{ 
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $project;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Project $project)
    {
        $this->project = $project->fresh();
        \Log::debug('In ProjectSaved.php = '.$project->status['name']);

    }
}

MikeMacDowell left a reply on Struggling To Find Error In Test

@RossUK where's the $data variable coming from in your Controller Method?

I'd guess that's what causing the issue

$customer->update($data);