lmartins

lmartins

Member Since 2 Years Ago

Experience Points 16,660
Experience
Level
Lessons Completed 157
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.

11 Jan
1 week ago

lmartins started a new conversation Signed Route Throws Invalid Signature

Hi, I'm having issues with a signed route that I have on my application.

This route is intended to generate a PDF files, and for that I use Browershot which then loads the signed route. This is placed on a action inside the model, which we ran by the user on the browser operates normally.

However, when I try to call this method via Tinker I always get Invalid Signature. I've went step by step in xdebug and the route that is generated on the fly does have the URL param with the signature, so I'm unsure as to what may be causing the signature error.

The middleware is using Laravel's own implementation: 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,

Any tips on what I should be looking into? Thanks so much!

06 Nov
2 months ago

lmartins left a reply on API Endpoint Returning 401 Errors After Upgrading To Laravel 5.7

Thanks for the feedback @D9705996

I think I've figured out the problem, adding it here for anyone facing the same issue.

On the previous Laravel update, there were changes related to Cookies serialization.

As described at the documentation https://laravel.com/docs/5.6/upgrade, you could opt for serialize or not the cookies, passing the static property in the App\Http\Middleware\EncryptCookies middleware.

I did that, so I though the cookies were working like before.

That apparently isn't the case, because today the only way I could get this to work again was by following the instructions on that same link, running the Laravel\Passport\Passport::withoutCookieSerialization() method in the AppServiceProvider.

This method was supposed to be only necessary if cookie serialization was disabled, but for some reason that isn't happening for me.

lmartins started a new conversation API Endpoint Returning 401 Errors After Upgrading To Laravel 5.7

Hi everyone,

I've been struggling to get around this problem that surfaced right after upgrading the framework to version 5.7.

I have this app in production, where part of the UI is driven by API requests. This has been working for more than a year, but since I've updated the framework the same requests now return {"error":"Unauthenticated."}.

Have anyone bumped into this problem too, how did you got around it?

07 Sep
4 months ago

lmartins left a reply on Session Expires While Doing API Requests

Ah interesting. These API routes still go through the auth:api middleware, so I though that would be enough to maintain the session. I'll test your suggestion, thank you!

lmartins started a new conversation Session Expires While Doing API Requests

Hi,

I've seen something weird happening on a project I'm working on. This project has a frontend that is composed of both regular server-side rendered pages, but also a few components that interact with an API provided by Laravel.

This API uses the same auth middleware as the main routes that render the "base" pages, but unlike full page loads the ajax requests don't seem to keep the session alive.

For policy reasons, project requires to have a short session time of 15 minutes, and one of the components of the project is a quiz like ui, where users can spend more than that interacting with it without doing a full page load. Those interactions make API requests, but what I've noticed was with such requests going out, the user session still expires.

Is there a way around this?

12 Jul
6 months ago

lmartins left a reply on Difficulties Getting A Nested Query To Work

Oh I was still trying make this work with Laravel's Query Builder methods, but for this use this makes it much simpler.

Thanks so much!

lmartins started a new conversation Difficulties Getting A Nested Query To Work

Hi,

I need to convert a query that is designed to find the higher price from two dimensions matrix (width/height).

On SQL is a fairly trivial query:

SELECT
    price
FROM
    matrices
    INNER JOIN (
            SELECT
                price_group_id,
                max_width
            FROM
                matrices
            WHERE
                price_group_id = 1
                AND max_width >= 74
            ORDER BY
                max_width
            LIMIT 1) AS t ON matrices.max_width = t.max_width
        AND matrices.price_group_id = t.price_group_id
    WHERE
        matrices.max_height >= 84
    ORDER BY
        matrices.max_height
    LIMIT 1

But I'm not being able to convert this into something Laravel can consume.

Thanks so much for any help you may provide.

08 Mar
10 months ago

lmartins left a reply on Checking For Logged In User On A Global Middleware

Just in case anyone comes to this same issue, the fix in my case was to simply load the middleware from the $middlewareGroups, after \Illuminate\Session\Middleware\StartSession::class

07 Mar
10 months ago

lmartins started a new conversation Checking For Logged In User On A Global Middleware

Hi everyone,

On my application I have two user models, one for regular users and another for admins, and I'm working on a feature that requires to run a global middleware for setting the app locale based of the user model.

The issue i'm facing is that when I try to check the current logged in user, I can get the Auth::guard('admin')->check() to work, as it always returns false, maybe because its running before the user's session is verified perhaps.

What am I missing here?

Thanks!

16 Feb
11 months ago

lmartins left a reply on Update Scout Index On Cascade Deleted Models

@rin4ik thanks. Yes, I did included the trait on the model.

lmartins left a reply on Update Scout Index On Cascade Deleted Models

Sorry for the delay. My initial description was actually not fully accurate.

I'm using algolia Vue components to list the entries from this model, and when I press delete, the model does get deleted from the DB and removes from the Algolia index but the first time the index loads it still shows the deleted entry.

It seems like that for a few seconds the Algolia index is out of sync with the model database, so I wonder how do you typically approach this cases, where we need to give Algolia some time to process the data.

02 Jan
1 year ago

lmartins left a reply on Policies/Gate Against Multiple User Types?

This is awesome, thanks so much @martinbean !

lmartins left a reply on Policies/Gate Against Multiple User Types?

Okay I now understand why the different user types have different results. The admin users routes have a middleware 'middleware' => 'auth:admin' so that's why I can't get information from the Admin user while trying to retrieve a frontend route.

I see two options here:

  1. Have two routes, one for admins other for users which doesn't feel right
  2. Find a way to check against the admin user even though the frontend routes use the auth:web provider while admins rely on auth:admin

Is there a way to achieve 2. or am I better of just going with 1. ?

lmartins left a reply on Policies/Gate Against Multiple User Types?

Hi @martinbean

Yeah I know, problem appears to be somewhat related to the user model, which on this case can be User or Admin as I have them as separate models. That's why I'm not type hinting on the policy method.

I have even tried returning true or false directly from the policy method and I still get different behaviour for admin and frontend users, so it seams like admins never reach the policy method and I'm not getting why.

Btw, I don't have any before method on this policy either which could explain the different behaviour for different user models.

Thanks so much for your feedback.

lmartins left a reply on Policies/Gate Against Multiple User Types?

Yeah, I've made that mistake before but not on this case.

30 Dec
1 year ago

lmartins started a new conversation Policies/Gate Against Multiple User Types?

Hi,

I have a bit of an edge case which I'm not being able to resolve using the methods described in Laravel's documentation.

On this app, I have two user types, admin and front-end, which use different models for each case. I need to allow both user types to see a third model, lets say Products, with each user type having its own set of rules, but both using the same controller and view to see the product.

Let's say:

App\User can see model App\Product if App\User bought that product. App\Admin can see model App\Product if App\Admin is the author of that product.

The problem im facing is that when I check the policy on the App\Product controller, no matter what try I cannot get the admin to be authorised.

I've tried to simplify the test case, to something like this:

    public function view(Product $product)
    {
        $this->authorize('view', $product);
        return view('products.view', compact('product'));
    }

and then in ProductPolicy I'm returning true just to check if I'm getting to the gate method:

    public function view($user, Product $product)
    {
        return true;
    }

I'm also not type hinting the $user variable, just because they come from different models. My guess is that this is related to my problem here, but I'm not getting to figure this one out.

Anyone with experience in a similar use case?

Thanks so much!

20 Dec
1 year ago

lmartins started a new conversation Update Scout Index On Cascade Deleted Models

I have a situation where I have two models: User and Purchase. The Purchase model is indexed via Scout and pushed to Algolia.

The purchase is setup so that when a user is deleted, the associated purchases are also removed from the BD:

        Schema::create('purchases', function (Blueprint $table) {
            $table->uuid('id');
            $table->primary('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->tinyInteger('status')->default(0);
            $table->timestamps();
        });

Problem is when the user is deleted even though the purchase is removed from the DB, it stays indexed in Algolia. Am I missing any step?

Thanks!

lmartins left a reply on Using Env Variables In Javascript With Different Local/production Values

Finally got to test this and works beautifully. Thanks so much @ejdelmonico

17 Dec
1 year ago

lmartins started a new conversation Using Env Variables In Javascript With Different Local/production Values

I'm working on a application that is connected to Algolia. Because I'm working locally with test data, I need to connect my local install to a different Algolia index, so I'm using .env variable to set different keys for my local and remote installs. Then, in Javascript, I'm reading those values using process.env.MIX_ALGOLIA_APP_ID which sadly isn't enough as these values will still be compiled using my local values when running npm prod. How do you typically approach this? Thanks!

lmartins left a reply on View To Manage Many-to-Many Relationships Between Two Models

Ok this turned out to be simpler than I anticipated.

We can simply use the contains method from the relationship like this:

$purchase->demographics->contains($demographic->id)

If using Laravel Collective to generate the form controls, this would translate to:

{{ Form::checkbox('demographics[]', $demographic->id, $purchase->demographics->contains($demographic->id) ) }}

Thanks again.

lmartins left a reply on View To Manage Many-to-Many Relationships Between Two Models

Thanks for your comment Povilas.

It is not what I was going for though. Displaying tags (or demographics from my example), both assigned or not is very straightforward, however combining those two in a single list, so that assigned tags are checked and unassigned unchecked, not as much as that's what I'm trying to accomplish.

16 Dec
1 year ago

lmartins started a new conversation Approach For View To Manage Many-to-Many Relatioships

Hi, I have two models linked by a Many-to-Many relationship, and I'm struggling to find a reliable approach to build the blade view where these relationships can me managed.

Model A - Purchases Model B - Demographics

Goal is to have a admin screen for Purchases, where I list all available Demographics, each one with a checkbox and for those already linked to the Purchase with the corresponding checkbox selected.

How would you typically approach this?

25 Sep
1 year ago

lmartins left a reply on Valet .dev Domain To Have Https Forced By Chrome

Thank you @ejdelmonico,

Yeah, that I ended up doing, although it kinda annoys me so hence the question if there would be a way to force the .dev domain to be local scoped and keep that for Valet.

Thanks!

24 Sep
1 year ago

lmartins started a new conversation Valet .dev Domain To Have Https Forced By Chrome

Hi everyone,

Recently .dev stopped working for me on Chrome, I believe due to what's described on this post: https://ma.ttias.be/chrome-force-dev-domains-https-via-preloaded-hsts/

Has anyone bumped into this too? Any workaround to keep using the .dev domain with Valet but not have https forced?

15 Sep
1 year ago

lmartins left a reply on Group By 3rd Level Relationship

To anyone who might find this looking for a similar result, in my case the solution was to use the DB facade to be able to pass a few raw SQL statements:

      $results = $assessment->results()
            ->select(
                'assessment_id',
                'results.category_id',
                'categories.title as category',
                DB::raw('sum(results.score) as score'),
                DB::raw('avg(results.score) as average'),
                DB::raw('count(results.score) as count'),
                DB::raw('group_concat(results.id) as results')
            )
            ->join('questions', 'results.question_id', '=', 'questions.id')
            ->join('categories', 'results.category_id', '=', 'categories.id')
            ->groupBy('categories.id')
            ->orderBy('category_id')
            ->get();

        foreach ($results as $key => &$result) {
            $results_ids = explode(',', $result->results);
            $result->results = Result::with('question')->find($results_ids);
        }

Perhaps there are better ways to achieve this, if so please comment, so far this was the best solution I've found.

14 Sep
1 year ago

lmartins left a reply on Group By 3rd Level Relationship

Sorry @vanderb, my example wasn't all that great so your suggestion is not exactly what I'm after, let me update it to better illustrate the problem.

13 Sep
1 year ago

lmartins started a new conversation Group By 3rd Level Relationship

Hi,

Im building an app that has these 3 entities:

  • Product
  • Question
  • Category

They have these relationships:

class Product extends Model
{
    public function questions()
    {
        return $this->hasMany(Question::class);
    }
}
class Question extends Model
{
    public function product()
    {
        return $this->belongsTo(Product::class);
    }
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
class Category extends Model
{
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

}

My goal was from the Product view to list all Questions but grouped by the Category, which has no direct relationship with the Product. How would you approach this?

12 Sep
1 year ago

lmartins left a reply on Generate Dummy Data With Faker While Still Maintaining Consistent Data And Relationships

Thanks all.

Final version was quite close to what @mindz suggested:

$factory->define(App\Assessment::class, function (Faker $faker) {

    $org =  App\Organization::all()->random();
    $purchase = $org->purchases()->get()->random();

    return [
        'name' => $faker->name(),
        'email' => $faker->email(),
        'organization_id' => $org->id,
        'purchase_id' => $purchase->id,
    ];
});

lmartins started a new conversation Generate Dummy Data With Faker While Still Maintaining Consistent Data And Relationships

Im trying to generate a few records in a table that relates to two foreign keys, as shown bellow:

$factory->define(App\Assessment::class, function (Faker $faker) {
    return [
        'name' => $faker->name(),
        'email' => $faker->email(),
        'organization_id' => $faker->randomElement([1, 2]),
        'purchase_id' => $faker->numberBetween(1, 6),
    ];
});

Problem with this approach is that Purchases are also related to the Organization, so with the approach above we can end up with invalid combinations of organization and purchase, in other words pointing to a purchase which does not belong to the organization set randomly.

How would you typically approach this?

10 Sep
1 year ago

lmartins started a new conversation Process Data From Pivot Table Relationships

Hi,

I'm looking to build an app where a organization can make multiple purchases of a given product, with every purchase adding a X amount of credits for that product to that organization.

So, the Schema looks like this:

        Schema::create('organizations', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('purchases', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('credits')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')
                    ->references('id')
                    ->on('products');
            $table->integer('organization_id')->unsigned();
            $table->foreign('organization_id')
                    ->references('id')
                    ->on('organizations');
            $table->timestamps();
        });

Then on the Organization controller I load the product model for each purchase:

    public function show(Organization $organization) {
        $organization->load('purchases.product');
        return view('organizations.show', compact('organization'));
    }

Which then allows me to display a list of purchases like this:

PURCHASES 2 months ago | Prod A | 51 Credits 4 months ago | Prod A | 62 Credits 6 months ago | Prod B | 118 Credits 8 months ago | Prod A | 346 Credits 9 months ago | Prod C | 377 Credits

These credits will control actions the organization can do, so my goal now is first to get the total credits for each product, so I can easily display and interact with those total amounts.

How would you approach this?

09 Sep
1 year ago

lmartins left a reply on Pull Models From Relationship Data

Whoa, debug bar is so sweet :) In this case it went from 9 to 5 queries, not a huge thing with such low numbers but this for sure changes dramatically as the numbers grow.

Thanks again @Snapey

lmartins left a reply on Pull Models From Relationship Data

Oh wow, thanks for all the help guys.

@Snapey answer ended up being what I needed, although I haven't implemented the eager loading yet, trying to figure that out.

To get the product information within the purchases loop, all I had to was, as @Snapey mentions declare the relationship in the Purchase model, and then I just needed to access the product object:

                @foreach($organization->purchases as $purchase)
                    <li>
                        {{ $purchase->created_at->diffForHumans() }} |
                        {{ $purchase->product->name }} |
                        {{ $purchase->credits }} Credits
                    </li>
                @endforeach 

This is so neat.

Now I'm a bit confused about the eager load. Each organization can have many purchases so I'm not quite getting where I should the with method in the controller:

    public function show(Organization $organization) {
        return view('organizations.show', compact('organization'));
    }

I'll keep looking at the docs, thanks so much everyone for the help here.

lmartins started a new conversation Pull Models From Relationship Data

Hi,

Just starting with Laravel, so please be patient with what might be an obvious question.

I have a model "Organization" that is linked to many purchases in its model:

public function purchases(){
        return $this->hasMany(Purchase::class)->orderBy('created_at','DESC');
    }

The purchases table include a foreign key for another table "Products", like this:

Schema::create('purchases', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('credits')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')
                    ->references('id')
                    ->on('products');
            $table->integer('organization_id')->unsigned();
            $table->foreign('organization_id')
                    ->references('id')
                    ->on('organizations');
            $table->timestamps();
        });

When I'm listing the purchases on the frontend, I'd like to show the linked product to each purchase, instead of it's ID, how could one achieve that?

        @if( count($organization->purchases) )
            <section class="Section">
                <header class="Section__header">Purchases</header>
                @foreach($organization->purchases as $purchase)
                    <li>
                        {{ $purchase->created_at->diffForHumans() }} |
                        {{ $purchase->product_id }} |
                        {{ $purchase->credits }} Credits
                    </li>
                @endforeach
            </section>
        @endif
12 Mar
1 year ago

lmartins left a reply on Vue Components And AJAX Loaded HTML Content

@atorscho did you found a solution for this?

08 May
2 years ago

lmartins started a new conversation Using Php70-xdebug With Valet

Hi,

I just started using Valet and im quite impressed how easy it is to get everything going. Having two issues though:

  1. Can't view logs - Always says "No log files were found."
  2. Can't use php70-xdebug either

Have anyone tried these and have any tips that might share?