mstrauss

mstrauss

Member Since 3 Years Ago

Web Developer at Self-employed

Experience Points 31,740
Experience Level 7

3,260 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 196
Lessons
Completed
Best Reply Awards 20
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.

18 Jul
14 hours ago

mstrauss left a reply on Route Facade Vs $router Variable

It looks like in Lumen, they make the $router variable publicly available here: https://github.com/laravel/lumen-framework/blob/0f450f8d6ee47bdef6c88a2492883c6e48a33a95/src/Application.php#L82


    /**
     * The Router instance.
     *
     * @var \Laravel\Lumen\Routing\Router
     */
    public $router;

Although the Route facade seems to also be available in Lumen: https://github.com/laravel/lumen-framework/blob/0f450f8d6ee47bdef6c88a2492883c6e48a33a95/src/Application.php#L703

Whereas Laravel uses the Route facade, which references the same router as Lumen: https://laravel.com/docs/5.8/facades#facade-class-reference. And I would guess that you can use the $router variable in your Laravel project, but you will have to declare the binding yourself as it is not made public by Laravel (that I am aware of anyway). Functionally it should work the same though, so it would just be a convention thing. And most Laravel developers, if anyone else is working on the project with you or will be in the future, are used to the Route facade.

mstrauss left a reply on Trying To Get Property Laravel

Everything looks to be set up okay to me, maybe the issue is with this:

  <td>{{$mp->progestudio->nombre_pe}}</td>

If the $mp->progestudio does not have any relationships, then it will return null. And then when you do this >nombre_pe you will get the error: Trying to get property 'nombre_pe' of non-object (0).

mstrauss left a reply on Conditions In Scopes?

As long as it is a local scope (as opposed to global) something like this should work:

  public function scopeLimitWhenChildren($query, $number)
    {
        return $query->children->take($number);

Maybe handle it right in the relationship setup if this will always be the way you want then returned:

public function children()
{
    return $this->hasMany('App\Child')->take(1);
}
17 Jul
1 day ago

mstrauss left a reply on Laravel Model OrderBy Relationship

I'm not quite getting your relationship setup. Within the Comment model, you have a relationship called children where a Comment can have many Comments. I'm not saying this is wrong, It's just not something I'm used to seeing. Usually, a relationship relates one model to a different model.

Also, on your upvotes relationship, you only want to return the CommentVote models if they have 1 vote? i.e. ->where('vote', 1);.

Can you share your CommentVote model? This may be needed to figure out how to accomplish your stated goal.

mstrauss left a reply on Method Illuminate\Mail\Mailer::from Does Not Exist.

I don't think there is a from method. Check out the API: https://laravel.com/api/5.7/Illuminate/Mail/Mailer.html

The from address would be in your config.mail file:

   /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],

mstrauss left a reply on How To Obfuscate Ids?

As @snapey said, a user knowing their own ID doesn't seem like a big security issue. But a user being able to guess other people's ID, can, potentially, lead to security vulnerabilities if everything else isn't locked down. In my opinion, it doesn't hurt, especially if your app is a potential high value target.

Check out this package: https://github.com/jenssegers/optimus

mstrauss left a reply on Help With Scopes

Take a look at how it's done with Soft Deletes in the Framework:

    /**
     * Add the without-trashed extension to the builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @return void
     */
    protected function addWithoutTrashed(Builder $builder)
    {
        $builder->macro('withoutTrashed', function (Builder $builder) {
            $model = $builder->getModel();

            $builder->withoutGlobalScope($this)->whereNull(
                $model->getQualifiedDeletedAtColumn()
            );

            return $builder;
        });
    }

Which uses the getModel method on the Builder class below:

    /**
     * Get the model instance being queried.
     *
     * @return \Illuminate\Database\Eloquent\Model|static
     */
    public function getModel()
    {
        return $this->model;
    }

So maybe something like this would work in your case, like the below. Although it's pretty heavy on pseudo code and not tested at all, hopefully it gets you moving in the right direction.

 protected function addApproved( Builder $builder ) {
  $builder->macro( 'approved', function( Builder $builder ) {
   // how do I query models based on the relation?

    $model = $builder->getModel();

    $builder->where($model->moderations->status === 'approved' )
     );

   return $builder;
  } );
 }

mstrauss left a reply on Blade Echoing Returning 1

What is the value of $body_class before it is sent to the view? Is it just a string like 'home'?

mstrauss left a reply on Mail Notifications - Add Custom Variable

@fi

Cool, glad you got some use out of it.

mstrauss left a reply on How To Change Email In Laravel App?

Try:

php artisan config:clear

mstrauss left a reply on Checking If Relation Exists In Blade

Yes, Auth::user()

I generally just type into the forum, so there no intellisense or anything like that ;)

mstrauss left a reply on Checking If Relation Exists In Blade

If I understand the logic correctly, I think you want to change the wishlist relation on your Product model to belongsToMany, since a Product can belong to many Wishlists. And maybe adding a relationship for the user as well, see below:

   public function wishlist()
    {
        return $this->belongsToMany(Wishlist::class); // update to belongsToMany
    }

User Model

  public function wishlist()
    {
        return $this->hasMany(Wishlist::class); 
    }

  public function itemOnWishlist($product_id)
    {
        return $this->wishlist->where('product_id', $product_id) != null 
    }

Wishlist Model

  public function user()
    {
        return $this->belongsTo(User::class); 
    }

And then in your view:

 @if($auth()->user->itemOnWishlist($product->id) )
       <i class="far fa-heart icon" id="{{$product->id}}"></i>
@else
       <i class="fas fa-heart icon" id="{{$product->id}}"></i>
@endif

mstrauss left a reply on Laravel Connection Refused Tcp://127.0.0.1:6379

Just a quick thought, if you are attempting to use Redis without the predis package:

From the docs:

Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and sorted sets. Before using Redis with Laravel, you will need to install the predis/predis package (~1.0) via Composer.

https://laravel.com/docs/5.2/redis#introduction

mstrauss left a reply on Relations With If Condition

That's an interesting approach. But I think you are experiencing why you can't use the conditional in the relationship method if you are going to eager load the relationship, since the returned null throws off the eager loading process.

That being said, why have it return null as opposed to just returning no relations? For example:

/* === Goals Relation === */
    public function goals()
    {
        return $this->hasMany('App\MidYearReviewTemplateGoal','mid_year_review_template_id','id');
    }

If the process_type != 'Non-Operations', then I would assume that no relations would be returned. But at least your eager loading wouldn't throw an error.

mstrauss left a reply on Mail Notifications - Add Custom Variable

Try passing that variables through the constructor:

 protected $variableOne, $variableTwo;

    public function __construct($variableOne, $variableTwo)
    {
        $this->variableOne = $variableOne;
        $this->variableTwo = $variableTwo;
    }

And then

/**
     * Get the mail representation of the notification.
     *
     * @param  mixed $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
       
        $variableOne = $this->variableOne;
        $variableTwo = $this->variableTwo;

        return (new MailMessage)
            ->subject('Whatever')
            ->greeting('Hey there!')
            ->line('The tester, ' . $variableOne . ' has accepted your ' . $variableTwo)
            ->action('Login to check it out!', url('/customURL'));
    }
16 Jul
2 days ago

mstrauss left a reply on Get The Site Url

Try this:

url()->full();

mstrauss left a reply on Blade Echoing Returning 1

@luismldias Can you share the view?

mstrauss left a reply on This Action Is Unauthorized. For All User Except User Have Id Of 2

Okay, so let's try this:

// first just return true on the policy to see if the issue is the comparison of the user id and the project owner id.


    /**
     * Determine whether the user can view the project.
     *
     * @param  \App\User  $user
     * @param  \App\Project  $project
     * @return mixed
     */
    public function update(User $user, Project $project)
    {
        return true; // $project->owner_id == $user->id;
    }

If the $user is able to view the project after doing this, then check in your local DB to make sure that the auth user's ID and the project ID you are trying to access are ==.

mstrauss left a reply on This Action Is Unauthorized. For All User Except User Have Id Of 2

Please share how you are using the ProjectPolicy.

mstrauss left a reply on This Action Is Unauthorized. For All User Except User Have Id Of 2

You don't need to define the 'project` gate method, since you are handling it with a policy, which makes more sense in a CRUD situation with a defined model.

$ability is just a stand in for the action i.e. Gate::define('update-post', 'App\Policies\[email protected]');

mstrauss left a reply on This Action Is Unauthorized. For All User Except User Have Id Of 2

Try removing this trait:

use HandlesAuthorization;

mstrauss left a reply on How To Multiply Number Of Rows In Result Set Testing Pagination

Are you using a seeder? If not, that's a great way to get any amount of dummy data you need into your app.

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

mstrauss left a reply on Laravel 5.7 | External Server Router Error

The error is saying that it can't find the Illuminate\Contracts\Routing\BindingRegistrar interface that is implemented in the below framework code:

/**
 * @mixin \Illuminate\Routing\RouteRegistrar
 */
class Router implements RegistrarContract, BindingRegistrar
{

That file should be here: /domains/example.com/public_html/example/vendor/laravel/framework/src/Illuminate/Contracts/Routing/BindingRegistrar.php

mstrauss left a reply on Laravel 5.7 | External Server Router Error

Laravel and your PHP install should take care of all of those request types.

mstrauss left a reply on BelongsToMany

You are querying a relationship so maybe something like:

return $this->withCount('comments')->get() > 0; 

Or possibly this, but I'm not quite sure if it will return a boolean or not...

return $this->has('license'); 

mstrauss left a reply on This Action Is Unauthorized. For All User Except User Have Id Of 2

What does your App\Policies\ProjectPolicy' look like?

mstrauss left a reply on This Action Is Unauthorized. For All User Except User Have Id Of 2

It's likely this causing your issue:

        $this->registerPolicies();
        Gate::before(function ($user){
            return $user->id == 2;
        });

Traditionally it would look more like:

Gate::define('project', 'ProjectPolicy');

 Gate::define('project', function ($user, $project) {
        return $user->id == $project->user_id;
    });

mstrauss left a reply on Error During Tests

Oh, I think I see the issue:

Set variables for the collaborator to be used in the URL below

  
       $collaborator = factory(Collaborator::class)->create();

Then...

Current

'api/collaborators/1'

Change to

'api/collaborators/'.$collaborator->id

mstrauss left a reply on Error During Tests

I noticed one issue with the test, see below $company->id. But that shouldn't cause all of those validation failures.

    /** @test */
    public function it_should_store_a_new_collaborator()
    {
        $faker = Factory::create('fr_FR');

        $full_name = $faker->firstName . ' ' . $faker->lastName;  //BTW you can use $faker->name for a full name
        $username = strtolower(str_replace(' ', '.', $full_name)); /// BTW you can use $faker->userName, if that makes sense for your app
        $company = factory(Company::class)->create();

        $this->json('POST', 'api/collaborators', [
            'full_name' => $full_name,
            'username' => $username,
            'mail_address' => $faker->safeEmail,
            'phone_number' => $faker->phoneNumber,
            'position' => $faker->jobTitle,
            'company_id' => $company->id
        ])->assertExactJson([
            'success' => 'Collaborator ' . $full_name . ' has been created successfully'
        ])->assertStatus(Response::HTTP_CREATED);

        $this->assertDatabaseHas('collaborators', [
            'id' => 1,
            'full_name' => $full_name,
            'username' => $username,
            'company_id' => $company->id
        ]);
    }

mstrauss left a reply on How To Populate A Drop Dropdown Menu From Another Drowdown Menu ?

Apologies, I misunderstood your question. The code I provided was just supposed to be a generic example of making an AJAX request to get data from your database. But I see now that you just want to move values from one select box to another. Give this a shot:

       $(document).ready(function() {
            $("#pr_menu li a").click(function(){
                $('.selectedLi').removeClass('selectedLi');
                $(this).addClass('selectedLi');
                var selText = $(this).text();
                $("#md_menu").html('<li><a href="#" >' + selText +' </a></li>');
                $("#produit").val(selText);
            });

            // I'm not really sure what is supposed to happen here, so I did't make any changes
            // except to add the needed )} at the end... 
            $("#md_menu li a").click(function(){
                $('.selectedLi').removeClass('selectedLi');
                $(this).addClass('selectedLi');
                var selText = $(this).text();
                $("md_#dropdown-toggle").html(selText+
                    ' <span class="caret"></span>');
                $("#produit").val(selText);
            })
        });

mstrauss left a reply on How To Manage Laravel Big Update Methods

You can use $request->all() as opposed to going through the fields singly. But, make sure you have the model's fillable array completed to protect against mass assignment hacks. And also you can separate the complex validation logic with a form request.

$something->update($request->all());

mstrauss left a reply on Flatten Laravel Nested Relationship (parent To Descendants)

Ah, right, I forgot about ->find($parent->id). Added it to the query chain below.

$parent = $parent->select(['name', 'address', 'contact_info', 'id'])->with(['descendants' => function (Builder $query) {
    $query->select(['name', 'address', 'contact_info', 'id']);
}])->find($parent->id); 

Also, your initial recursive function was interesting. Perhaps with the small adjustment below it may work:

    protected function traverseTree($subtree)
    {
        $descendants = collect([]);

        foreach ($subtree->descendants as $descendant) {

            $descendants->push($descendant);

            if($descendant->descendants instanceof Collection) {

                foreach ($descendant->descendants as $node) {

                    $descendants->push($node);
                }

                $this->traverseTree($descendant->descendants);
            }
        }

        return $descendants;
    }
15 Jul
3 days ago

mstrauss left a reply on Flatten Laravel Nested Relationship (parent To Descendants)

How about->get()?

$parent = $parent->select(['name', 'address', 'contact_info', 'id'])->with(['descendants' => function (Builder $query) {
    $query->select(['name', 'address', 'contact_info', 'id']);
}])->get(); 

mstrauss left a reply on Eager Loading Multiple Relationships Error Thrown

If the answered helped, please mark it as correct/resolved so that future forum members can find it more quickly.

mstrauss left a reply on Eager Loading Multiple Relationships Error Thrown

I think so:

 $menu_group = MenuGroup::with([
            'groupItems.options', 'homeModels', 'communities'])
                ->whereHas('homeModels', function ($query) use ($model_id) {
                    $query->where('home_models.id', $model_id);
                })->whereHas('communities', function ($query) use ($community_id) {
                    $query->where('id', $community_id);
            })->get();

mstrauss left a reply on Using WhereHas To Return Results Where ALL Relations Match?

One more try!

$recipes = Recipe::latest()->whereHas('ingredients',  $ingredientsFilter = function(Builder $query) {
    $query->where('buying_current', true);
})->whereHas('resultants', $resultantsFilter = function(Builder $query) {
    $query->where('selling_current', true);
})->whereHas(['ingredients' => $ingredientsFilter])->whereHas(['resultants' => $resultantsFilter])->get();;

Inspired by: https://blog.jgrossi.com/2018/querying-and-eager-loading-complex-relations-in-laravel/

mstrauss left a reply on Asset() Work With Localhost , Not With Domain.local

In your .env what is your APP_URL set to?

APP_URL=http://localhost

mstrauss left a reply on Using WhereHas To Return Results Where ALL Relations Match?

Not tested, but how about this:

$recipes = Recipe::latest()->whereHas(['ingredients', 'resultants'], function(Builder $query) {
            $query->where('ingredients.buying_current', true)->where('resultants.selling_current', true);
         })->get();

mstrauss left a reply on Internationalizing URL While Keeping Routes Name

This package may be a good option to save you from reinventing the wheel: https://github.com/mcamara/laravel-localization

Check out the translated routes: https://github.com/mcamara/laravel-localization#translated-routes

mstrauss left a reply on User- Delivery Address - Many To Many

In my opinion..yes EX: wife and husband have the same delivery address( no the same order) In fact I was thinking for a option like: check your order before to pay. If all is correct go to payment.

But in this case, wouldn't the Wife and Husband be two separate users? Even if not, and they were both using the same account login, the order would still belong to one User.

As for getting the most recent address, give this a shot:

$latestDeliveryAddress = App\User::find(1)->whereHas('deliveries', function (Builder $query) {
    $query->select('address')->max('updated_at);
})->get();

mstrauss left a reply on Flatten Laravel Nested Relationship (parent To Descendants)

Yes, I just ran a local test and found the similar output issues. Let's try another way:

$parent = $parent->select(['name', 'address', 'contact_info', 'id'])->with(['descendants' => function (Builder $query) {
    $query->select(['name', 'address', 'contact_info', 'id']);
}])->get();

mstrauss left a reply on Flatten Laravel Nested Relationship (parent To Descendants)

I wonder if the below is returning an instance of Collection

$parent = $parent->with('descendants')->find($parent->id);

Maybe try

$parent = $parent->with('descendants')->find($parent->id)->get();

Just a heads up, this is the way I am used to seeing eager loaded constraints

$users = App\User::with(['posts' => function (Builder $query) {
    $query->where('title', 'like', '%first%');
}])->get();

mstrauss left a reply on User- Delivery Address - Many To Many

I'm a little confused wit this:

public function users()
    {
        return $this->belongsToMany('App\User');
    }

Does a Delivery really have many Users? Or does a Delivery belong to one User? Just curious...

Assuming you didn't disable timestamps, why not retrieve the latest Delivery by get the latest updated_at timestamp?

mstrauss left a reply on Flatten Laravel Nested Relationship (parent To Descendants)

Hmm... Would you share the code that is using the ->pluck method?