Drfraker

Drfraker

Member Since 5 Years Ago

Bozeman, MT

Experience Points 111,470
Experience Level 23

3,530 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 1129
Lessons
Completed
Best Reply Awards 32
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 May
3 days ago

Drfraker left a reply on Using WhereIn And Comma Separated Values

whereIn() is not going to work like that. Here's a better approach. Set up a keywords table and a pivot table for keyword_post. Then set up a manyToMany relationship a post hasMany Keyword and keywords hasMany Post. For related posts you would use the pivot table to query. This approach will allow the database to do the heavy lifting with the added benefit of not having duplicated keywords for posts. Tables:

| posts | | id | | status |

| keywords | | id | | name |

| keyword_post | | id | | keyword_id | | post_id|

14 Mar
2 months ago

Drfraker left a reply on Laravel Forge Load Balancer Problems

In case anyone else has a problem like this, the issue was that I added the public IP address to the trusted proxies middleware. Chris Fidao was kind enough to show me that I needed to add the private IP address to the array.

Drfraker started a new conversation Laravel Forge Load Balancer Problems

I added a load balancer to my server stack using forge. Now with each page load all of the forms in the page have unsecure urls. this is the error that is showing up in the conse.

Mixed Content: The page at 'https://domain.com/clients' was loaded over a secure connection, but contains a form that targets an insecure endpoint 'http://domain.com/userSettings/update'. This endpoint should be made available over a secure connection.

I have set up the TrustProxy middleware and added the IP address of the load balancer to it, but it still is not working. Any advice?

21 Feb
3 months ago

Drfraker left a reply on How Do You Guys Create Admin Panel In Laravel

I've used backpack and Nova. I can say Nova is worth the $$.

30 Jan
3 months ago

Drfraker left a reply on Run ZSH Command From Laravel

If you want to move the file to another server you'll have to use the scp command which allows you to transfer files between servers over ssh. Here's the basic syntax:

scp -r source_folder [email protected]:destination_folder

29 Jan
3 months ago

Drfraker left a reply on Best Practices For Laravel API Sandbox

@themsaid, a core laravel developer just published an article covering a deep dive into database connections. This article might give you some good ideas to move forward with.

https://divinglaravel.com/understanding-how-laravel-configures-database-connections

Drfraker left a reply on WhereBetween Does Not Exist

whereBetween is not available on the collection it's available on the query which is returned before you call the get() method. Try this instead:

$bookingsForCurrentWeek = auth()->user()->bookings()->whereBetween('date', [
   now()->format('Y-m-d'), now()->endOfWeek()->format('Y-m-d')
  ])->get();
28 Jan
3 months ago

Drfraker left a reply on Not Seeing How To Disable Caching Locally

@DAVESTEAD - If you run the command php artisan config:cache it will clear the config cache and then re-cache it. You want to runphp artisan config:clear that will clear it but not re-cache it.

Drfraker left a reply on Name Of Model Which Tracks Downloads...

How about FileActivity With this name you could conceivable add more logic to aside from just download count and it would still make sense.

//table
file_activity
id
file_id
type // string to add the type of activity, in your case would be 'downloaded'
created_at
updated_at

27 Jan
3 months ago

Drfraker left a reply on How Do I Get A Count Of How Many Columns Are (or Aren't) Null In A Query?

I can help you live on https://devallies.com . I'm drfraker on there too. Might be easier.

Drfraker left a reply on How Do I Get A Count Of How Many Columns Are (or Aren't) Null In A Query?

$query->whereNull('column_name')->count();

Drfraker left a reply on Vue-select A Select2 Library With Laravel

I think what you want to do is wrap the vue-select component in your own custom component. Then within your custom component, you can create methods for retrieving data etc with ajax calls. I could help you live on https://devallies.com, my username is drfraker on there too. I'll only be available for the next hour though.

26 Jan
3 months ago

Drfraker left a reply on How Do I Check If A Model Has A Job On The Queue?

Without storing the state of the model being in the queue, in some state management system (database, redis, etc), and then updating that state to tell it that the model isn't in the queue anymore, I'm not sure how you're going to achieve what you're original question was about.

Good luck...

25 Jan
4 months ago

Drfraker left a reply on How Do I Check If A Model Has A Job On The Queue?

You could use queue before and after events to keep track of which jobs are in the queue at any given time. Add them before they run and remove them after they run. Here's the link and an example from the docs.

https://laravel.com/docs/5.7/queues#job-events


<?php

namespace App\Providers;

use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Queue::before(function (JobProcessing $event) {
        // get the model from the payload
        $model = $event->job->payload();
            // store the model in the db as queued
        });

        Queue::after(function (JobProcessed $event) {
        // get the model from the payload
        $model = $event->job->payload();
            // remove the model row from the database
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


Drfraker left a reply on Free Domain Emails

I haven't done this but I think you might be able to use a service like Mailgun, which has a nice free tier, and this package to get the job done. https://laravel-news.com/laravel-inbound-email

Let me know how it goes. I might use this setup for a new side project I'm working on.

23 Jan
4 months ago

Drfraker left a reply on Axios Always Returns A Null Data And Status

I think the issue is that your nativescript can't reach your application because it's a different app. I've solved this before using valet and running valet share and then using the ngrok IP address for the URL in nativescript.

Give that a try...

Drfraker left a reply on DB Schema: Multiple Choice And Fill In The Blank Q & A

If the answer will only ever be attributed to the user that gave the answer, why not put user_id on the answers table. Skip the pivot table altogether. A pivot table is more for when you might have an answer that could be attributed to more than one user, one to many or many to many relationships. Correct me if I'm wrong about that though...

16 Jan
4 months ago

Drfraker left a reply on Do Modified Collections Maintain The Same Keys As Original?

I'm not sure what you're referring to when you say "keys". But here's an attempt to clarify for you.

If you have a collection of 30 items keyed 0-30 and you remove the odd keys using a filter method on the collection you will have a collection of 1-29 only containing the odd keyed items. Those keys and the items they refer to will be the same as they were before the filter was run.

If you mean something else, try to elaborate on the question.

Drfraker left a reply on How To Allow CSS Content To Be Rendered In My Local Apache Web Server With Chrome?

I know I don't speak for everyone, but I'm not chasing down links on stack overflow in order to answer your question here.

Drfraker left a reply on Storage Problem

I think if you familiarize yourself with this: https://laravel.com/docs/5.7/filesystem you will be very happy with the time you spent on it. You're making things hard on yourself with that code.

08 Jan
4 months ago

Drfraker left a reply on How To Speed Up This Sql Query

@JLRDW - the list() function assigns variable as if they were an array. You can see that the return of the function that is being called returns an array. Well by using list($query, $totalcount) the variables are set automatically from the return value.

Drfraker left a reply on How To Speed Up This Sql Query

@CLICK - Wow thanks for the in depth reply.

I will look at the article and see about the simple paginator instead of length aware. I think it is the count() that is taking so much time. I'll also check my indexes to ensure they are set up correctly. Also, yes the filter is using LIKE %search% maybe I'll have to find a better way to do that too.

Drfraker started a new conversation How To Speed Up This Sql Query

In my application ( which is multitenant) I have a query that can take up to 10 seconds depending on the number of rows in the database for a given office. I'd like to speed this up but I'm not sure how to do it. The table for this query "notes" is quite large and has around 800,000 rows in it. Additionally, the note_text on the notes table can be quite large.

Here's the controller, I believe the code that is slow is in the getFilteredNotes($request) method, and possibly related to getting the count. But I'm not sure. It is difficult to test because in development environment I don't have nearly as much data in the notes table.

My questions:

  1. Is there a clear problem with the query that is making it slow?
  2. Is there a way to measure this query for debugging without replicating production data? (Due to privacy regulation, I really don't want production data on my machine)
  3. Could removing the note_text field have an effect on the time of the query to complete?
<?php

namespace Quickernotes\Http\Controllers\Api;

use Carbon\Carbon;
use Quickernotes\Interfaces\ClientRepositoryInterface;
use Validator;
use Quickernotes\Note;
use Quickernotes\Helpers;
use Illuminate\Http\Request;
use Quickernotes\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
use Quickernotes\Interfaces\NoteRepositoryInterface;
use Quickernotes\Http\Resources\Note as NoteResource;

class NotesController extends Controller
{
    private $note;

    public function __construct(NoteRepositoryInterface $note)
    {
        $this->note = $note;
    }

    public function index(Request $request)
    {
        $paginationPage = $request->page ?? 1;
        $take = 25;

        list($query, $totalCount) = $this->getFilteredNotes($request);

        $notes = $this->getPaginationData($query, $take, $paginationPage);

        $clientIds = $notes->pluck('client_unique_id')->unique()->reject(function ($id) {
            return ! $id;
        });

        $clients = app()->make(ClientRepositoryInterface::class)->getClients($clientIds);

        $notes->map(function ($note) use ($clients) {
            $note->setRelation('client', $clients->where('api_unique_id', $note->client_unique_id)->first());
        });

        return new LengthAwarePaginator($notes, $totalCount, $take, $paginationPage);
    }
  

    /**
     * Get the notes for the view and filter by search text and user.
     *
     * @param Request $request
     * @return array
     */
    private function getFilteredNotes($request)
    {
        $filter = $request->filter;

        $query = Note::with('staff')
            ->select([
                'id',
                'client_unique_id',
                'user_id',
                'created_at',
                'deleted_at',
                'service_date',
                'note_text',
                ])
            ->when($filter, function ($q) use ($filter) {
                return $q->clientName($filter)
                    ->staffName($filter)
                    ->clientId($filter);
            })
            ->when(! $request->user()->isOwner(), function ($q) use ($request) {
                return $q->ownedByUser($request->user());
            });

        return [$query, $query->count()];
    }

    /**
     * Get the paginated results for the view.
     *
     * @param $query
     * @param $take
     * @param $paginationPage
     * @return mixed
     */
    private function getPaginationData($query, $take, $paginationPage)
    {
        return $query->orderBy('service_date', 'desc')
            ->take($take)
            ->skip(($paginationPage * $take) - $take)
            ->get();
    }
}

Drfraker left a reply on Multiple Variables Returned With Axios In Vue

axios.get('url/to/route').then((res) => {
    this.object1 = res.data.object1
    this.object1 = res.data.object2
})

07 Jan
4 months ago

Drfraker left a reply on Custom Error Message

[
            "cover_letter.max" => 'Maksimal 500 karakter', 
            "zip.integer" => 'Kode zip harus angka',            
        ]

Drfraker left a reply on Multiple Variables Returned With Axios In Vue

//controller code
return response()->json(['object1' => ['one', 'two'], 'object2' => ['three', 'four']]);
04 Jan
4 months ago

Drfraker left a reply on Catching Errors With Stripe?

$e->getMessage()

Drfraker left a reply on Best Way To Validate Range In Laravel?

You can easily use a custom rule for this use case: run php artisan make:rule ValidAmount

Rule Code:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ValidAmount implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value >= 0 && $value <= 999;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be between 0 and 999.';
    }
}

Use in controller:

use App\Rules\ValidAmount;

$request->validate([
    'field' => [new ValidAmount],
]);

11 Dec
5 months ago

Drfraker left a reply on Select Query Posts With Likes

This topic is covered from inception to implementation on the "build a forum" series.

You might want to review the series, starting with this episode https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/18 to get a feel how @jeffreyway did this.

On the forum series it is called a "favorite" instead of a "like" but the concept is the same.

05 Dec
5 months ago

Drfraker left a reply on Suggestions On Payment-processing

You'll want to use Stripe to process payments. https://stripe.com. Like @jlrdw said, they handle the actually transaction so you don't have to worry about storing (or even receiving) credit card information on your server. As for security, of course Laravel has sufficient security for an ecommerce site. It is running many many many many e commerce sites.

04 Dec
5 months ago

Drfraker left a reply on Incorrect Date Value

Use this package https://packagist.org/packages/cmixin/business-day + Illuminate\Suport\Carbon. No need to reinvent the wheel :) I've used it in a project doing something similar to what you're describing and it worked like a charm. Good luck!

Drfraker left a reply on Laravel Relative Paths In Urls

@jerauf You can make a new disk that points to any directory you want. See config/filesystems.php

 'disks' => [
    // This disk is there by default
        'local' => [
            'driver' => 'local',
            'root'   => storage_path().'/app',
        ],

    // add a new disk array, name it something else and change the path.
        'local-files' => [
          'driver' => 'local',
          'root' => '/path/to/files'
        ],

    // continue disks array ...

Then use Storage::disk('local-files')->files(); That will give you a list of all the files in the /path/to/files directory.

03 Dec
5 months ago

Drfraker left a reply on Laravel Relative Paths In Urls

What do you think is stored in /storage or /public? Maybe your question isn't clear.

02 Dec
5 months ago

Drfraker left a reply on Push Is Not A Function Vuejs

You don't have a push() method defined on Cart.vue but you are calling it in Main.vue. That's why you see that error.

Drfraker left a reply on Cache And Pagination

I second what @jlrdw said.

29 Nov
5 months ago

Drfraker left a reply on How Should I Go About This

@s3riouss If you like the solution I provided can you mark it as the best answer? Thanks.

28 Nov
5 months ago

Drfraker left a reply on Exception Handling In Laravel

public function store(Request $request)
   {
         // you always want to validate $request data
        // this validation will return the user back to the view and there will be errors in the error bag for you to check for in the view.
        $data = $request->validate([
            'deptstatus' => 'boolean'
        ]);
            
               $notification = Department::create([
            'deptstatus' => $data['deptstatus'] ? 'on' : 'disabled'
        ]);

        if(! $notification) {
            session()->flash('error', 'Something went wrong!');
        }
        
        session()->flash('message', 'Your department was saved');
               
        return view('departments.index');
   }
27 Nov
5 months ago

Drfraker left a reply on How Should I Go About This

You can make a view for selecting locations to manage.

// in view where user would select locations to manage
@if(auth()->user()->locations->count())
    @foreach(auth()->user()->locations as $location)
        <a href="{{route('location.show', $location)}}">{{$location->name}}</a>
    @endforeach
@endif

// LocationsController assuming you are using route model binding...
public function show(Location $location) {
    // make sure this user has permission to view the location. (requires a policy class)
    $this->authorize('view', $location);

    //return a view that show the details of the location and has a button on it to edit the location
    return view('location.show')->withLocation($location);
}
26 Nov
5 months ago

Drfraker left a reply on Call To A Member Function Can() On Null

@jackjones you can test it manually but I recall it does perform a check to determine if there is an authenticated user present. Which would prevent you from having to do it :) Also, it just looks so much better without the @if(auth()->user()->can('do-shit', ToSome::class) logic in the view. Just my opinion though.

Mostly I wanted to point out that it would work as I suggested for other people that read this post.

Drfraker left a reply on Call To A Member Function Can() On Null

@talinon It is a helper for the auth()->user()->can() method but it performs a check of an authenticated user out of the box. @jackjones you won't get the error if you use the blade helpers and they look cleaner, IMHO.

Hope that helps...

Drfraker left a reply on Call To A Member Function Can() On Null

This might be what you're looking for.

@can('update', $post)
    <!-- The Current User Can Update The Post -->
@elsecan('create', App\Post::class)
    <!-- The Current User Can Create New Post -->
@endcan

The can() method is on the user object. If the user is null there is no can() method to run, hence the error. Null has not method can()

24 Nov
6 months ago

Drfraker left a reply on Pass Response Data To The Parameters Of Another AJAX Request With AXIOS

methods: {

    getSchedule() {
        axios.get('/get-schedule', params).then(response => {
            this.getClassroom(response.data.schedule.classroom_id)
        })
    },

    getClassroom(roomId) {
        axios.get('/get-classrooms', params {                                           
                    classroom_id: roomId
        }).then(response => {
            console.log(response.data);
        })
    } 
}
19 Nov
6 months ago

Drfraker left a reply on Sort A Collection According To An Array Of IDs In Laravel

You can use collection methods for this:

$grids_arr = collect([11,10,1]);

$sorted = $ids->map(function($id) use($categories) {
    return $categories->where('cat_id', $id)->first();
});

18 Nov
6 months ago

Drfraker left a reply on Live Pair Programming

@ianfain It is a site I'm working on that will make pair programming really easy to set up and record. It's especially for situations where you have a problem and want to get live help from other dev's that you may or may not know. I'll have more time to add to the site next week and hopefully make things easier to use and open to more people.