shadrix

Experience

39,850

0 Best Reply Awards

  • Member Since 9 Months Ago
  • 363 Lessons Completed
  • 10 Favorites

14th September, 2018

shadrix left a reply on How To Implement A Multi Rating System? • 1 week ago

@MikeRees Okay interesting! Thank you! Learned a lot :)

shadrix left a reply on How To Implement A Multi Rating System? • 1 week ago

@MikeRees I need your help again... Hopefully, you are reading this again.

enter image description here

I changed the diagram a bit so that I can add the review bodies.

I implemented it like this, but then it struck me. Why do I need the pivot table, when I could use table "ratings" as my pivot table?

Because let's say I have the id of an "offer review", I can get easily all collections of ratings. And I get all values at the same time.

So I think I could just delete "offer_review_rating_types" or do I miss something?

13th September, 2018

shadrix left a reply on How To Implement A Multi Rating System? • 1 week ago

@MikeRees OH I see! I will give it a try!

And here is what I use to add a picture:

[![enter image description here][1]][1]
[1]: https://i.imgur.com/Rr9g0BY.png

How did you draw the diagram? Reminds me of a program that I used at school but it was years ago...

shadrix left a reply on How To Implement A Multi Rating System? • 1 week ago

@MikeRees thank you for your help. It's hard to for me to understand it still. I tried to "translate" your tips into this diagram, but I think it's weird for me.

enter image description here

so you would add all different kinds of ratings in one table? still confused sorry

shadrix started a new conversation How To Implement A Multi Rating System? • 1 week ago

First of all. Thank you for your time and help. I feel bad asking questions, but I'm stuck.

Currently, I'm trying to implement a rating system. Not a normal one. It's very similar to the Airbnb one, where a User can give the overall rating from 1-5 but also has the option to rate other things like the location/value etc.

In my case, I have an "offer" table. Each offer can be a different type of thing. It can be food, it can be an event, a service etc.

Every offer can be ordered by a user.

Now after buying the offer you can rate it. However, for each type of offer, you have optional ratings.

For example for the type "food", you can optionally rate the taste, the freshness, the quantity or the value.

I'm not sure how to implement this... my current thought is like this:

List item

Every review consists of the public body text, the optional private text to the seller and the response of the seller (if there is one). And it's overall rating.

One review has one optional review. In the example of food, I would save the additional ratings in JSON.

But again in my last post, you cannot calculate the averages etc very well with it. But I don't want to add for every offer type a special table again.

How would you handle this?

shadrix left a reply on Is There A Right Approach To Calculate The Average Of A Rating System? • 1 week ago

Guys it's super hard for me to mark the right answer. Every response was helpful. But I feel bad if I don't mark anything. I choose the one was the lowest XP and because I really like the approach with redis.

Thank you for the help!

12th September, 2018

shadrix started a new conversation Is There A Right Approach To Calculate The Average Of A Rating System? • 1 week ago

I'm curious what your thoughts are about this.

Let's say I have an offering table (for some items) with a rating system from 1-5. How would you implement it when you would like to display the average rating of an offer? I see two possible ways:

I could add those two columns in the offer table:

rate_count : 0,
rate_average: 0

And for each new review in the rating table, I would recalculate the rate_count and rate_average.

The second possibility is that I'm calculating the average on the fly with the aggregate methods avg() and count().

Personally, I feel like it's not a good idea to calculate these numbers in every query. However, in one episode Jeff is explaining how to implement a "favorite/liking" system. In there he counts the sum of likes with

 return $this->favorites->count();

How would you handle this?

7th September, 2018

shadrix started a new conversation Is There A Free Https Tunneling? • 2 weeks ago

I just implemented Stripe's Payment Request Button. It needs to have https to be shown. I'm using valet share but that needs to be http.

Is there a free https tunneling?

24th August, 2018

shadrix left a reply on Mocking Stripe - How Not To Call The API • 4 weeks ago

@Drfraker thank you! Helped me a lot. Btw you should have named yourself "DrFaker" :P You know how to mock ;)

20th August, 2018

shadrix started a new conversation Mocking Stripe - How Not To Call The API • 1 month ago

I feel bad asking, but I don't know how to solve my test. I need to test if a user is being charged or not. In my unit test, I'm testing my method with the real API. But in my feature test, I don't want to use the real API again.

I have a job "ProcessPayment" and somewhere in the handle method I'm calling $this->chargeBuyer();

 protected function chargeBuyer()
 {
    $customer = $this->firstOrCreateCustomer(); //it finds the Stripe\Customer

    return $this->order
                ->buyer
                ->payment()
                ->chargeOrder($this->order, $customer); //this part should be mocked (I know it works).
 }

How do I do this? My first approach is (it's not working but just an idea)

 /** @test */
 public function it_charges_user() 
 {
    $this->orderMock = \Mockery::mock(Order::class);

$this->orderMock->shouldReceive('accepted')
               ->once()
               ->andReturn(true);

    $this->orderMock->shouldReceive('buyer->customerId')
               ->once()
               ->andReturn(true);

    $this->orderMock->shouldReceive('transaction->source_id')
               ->once()
               ->andReturn('jibberish');

    $this->orderMock->shouldReceive('buyer->customer->create')
               ->once()
               ->with(['source' => 'jibberish'])
               ->andReturn('some-customer');

    $this->orderMock->shouldReceive('buyer->payment->chargeOrder')
               ->once()
               ->with('order', 'customer')
               ->andReturn('charged');

    $payment = new ProcessPayment($this->orderMock); //Inject Order

    $payment->handle(); //Start my Job
}

You see that this is super gross, but I don't know how to handle the test...

Here is an excerpt of the job code:

class ProcessPayment implements ShouldQueue
{
   use ...;

 public $order;

/**
 * Create a new job instance.
 *
 * @return void
 */
public function __construct(Order $order)
{
    $this->order = $order;
}

/**
 * Execute the job.
 *
 * @return void
 */
public function handle()
{
    if(! $this->order->accepted) return;

    if(! $this->order->transaction->isChargable){

        return $this->notifyBuyerToPay();
    }
    
    $this->chargeBuyer();
    
    //save charge_id in transactions


    //set payment job to the time to payout
    //
    //order complete?

}

 /**
 * Checks if Buyer is customer and 
 * is charge for the Order. 
 * @return Stripe\Charge 
 */
protected function chargeBuyer()
{
    $customer = $this->findOrCreateCustomer();

    return $this->order
                ->buyer
                ->payment()
                ->chargeOrder($this->order, $customer);
}

14th August, 2018

shadrix started a new conversation Hiding The Public Email Through A Middle Email. How Would You Call It? • 1 month ago

I'm looking for a way that hides the user's email through a middle email. Airbnb uses it for communication purposes after booking, for example. [email protected] But it's obviously not the real mail.

Is there a package out there that does that? I don't know how you would call such a thing.

shadrix left a reply on Paged Resource Collection Not Working • 1 month ago

@sgtpepper THANK YOU. I was looking for answers but could not find it. Indeed you cannot use response()->json()

13th August, 2018

shadrix started a new conversation Question To API Resource Collection - How To Use Own Names • 1 month ago

So I'm learning about API Resource and I need this for using HashIds.

I'm a bit confused how I can use my "own" names in a collection.

In single models I can say:

public function toArray($request)
{
    return [
        'myownid' => $this->id,
        'username' => $this->name,
        'awesomeemail' => $this->email,
    ];
}

In collection I need to write:

public function toArray($request)
{
    return [
        'data' => $this->collection,
    ];
}

But how can I change the attribute names?

So I can use: 'myownid' => Hashids::encode($this->id),

My collection result is quite big:

$order->with(['items', 'items.offer', 'items.offer.offering', 'transaction', 'billing', 'billing.buyer', 'seller'])
              ->filter($filters) //query filter
              ->paginate(10)

10th August, 2018

shadrix left a reply on Mockery - How To Mock A Class? (Somehow It Still Fires The "real" Methods) • 1 month ago

@martinbean Ok I see, that sucks. I hoped it would work without injecting it our retrieving from a container... Thank you anyways!

shadrix started a new conversation Mockery - How To Mock A Class? (Somehow It Still Fires The "real" Methods) • 1 month ago

I feel bad asking, but I'm a bit confused with mockery. Sometimes it works perfectly but right now, I cannot get it to work.

It should not be that hard, my code is quite simple:

    $payment = new Payment(auth()->user());

    $payment->updateOrCreateCustomer($this->data['source']['source']['id']);

In a Unit Test I'm already testing Payment, so I don't need this code above to work.

In the FeatureTest in Setup:

public function setUp()
{
    parent::setUp();
    
    $this->mock = \Mockery::mock(Payment::class);

    app()->instance(Payment::class, $this->mock); 

    $this->mock->shouldReceive('updateOrCreateCustomer')
               ->once()
               ->andReturn('value'); //I don't care for the value
 }

18th July, 2018

shadrix left a reply on Laravel Mix: Prevent Moment.js Locales • 2 months ago

@steveperrito thanks but don't forget to

const webpack = require('webpack');

13th July, 2018

shadrix left a reply on Can You Register A Helper Method In A Package Globally So It's Not Being Refreshed? • 2 months ago

So I found another way for my problem, an maybe it helps.

ServiceProvider:

    $this->app->singleton('myclass', function ($app) {
        return new Myclass($app);
    });

And in the helpers

   return app()->make(Tongue::class);

shadrix started a new conversation Can You Register A Helper Method In A Package Globally So It's Not Being Refreshed? • 2 months ago

So in my own vendor package, I have a helper method that returns me the Class that I'm using:

 function myclass()
 {
     return app(Myclass::class);
 }

With that, I can use it as a global method myclass() in my project.

Now, I'm a bit stuck, because it does not remember (obviously) it's current state and forgets it's protected values. How would you handle it?

Just that you understand where I have these problems:

For example in my main Project RouteServiceProvider.

 Myclass::detect(); //sets protected value
 Myclass::current(); //gets the protected value
 myclass()->detect(); //sets protected value
 myclass()->current(); //forgets it -> null because it calles a new instance

Thank you!

12th July, 2018

shadrix left a reply on Localization Series • 2 months ago

+1

shadrix left a reply on Is There A Good Package For Subdomain Laravel Translations? • 2 months ago

@lostdreamer_nl many thanks! It works :) still, need to adjust my needs to it.

And just one little side question, if you have a static page like about us. How would you save the other language, in /lang/de/de.json?

shadrix left a reply on Is There A Good Package For Subdomain Laravel Translations? • 2 months ago

@lostdreamer_nl ha sorry I think I was not clear enough, but its really nice thanks!

So what you showed me is how I can translate models. But first I need a good way to route and redirect to the languages etc.

shadrix started a new conversation Is There A Good Package For Subdomain Laravel Translations? • 2 months ago

I need your help. I'm a bit overwhelmed with localization.

My goals are to have subdomains referencing the current language used. So de.myapp.com for German, fr.myapp.com for French but myapp.com for English.

I thought it would be easy but I just find unmaintained packages. The only one I really like is made by mcamara. But still not perfect but it just adds prefixes like myapp.com/en. (And even if you change it you can't use the middleware because it just adds the prefix...)

Do you have some tips for me? Thank you!

11th July, 2018

shadrix left a reply on How To Boot A Model Via Trait? Event "updated" Is Not Called • 2 months ago

@lostdreamer_nl thank you it works :) it's super weird that it needs to be there, because in other traits it worked just fine. Thank you for your help! And good to know with protected

10th July, 2018

shadrix left a reply on How To Boot A Model Via Trait? Event "updated" Is Not Called • 2 months ago

@click

I recreated my problem and loaded to github. You just need to go to the unit test to test it. No installation at all. I stripped everything out what is not important.

https://github.com/pmochine/TraitBootBug

shadrix left a reply on How To Boot A Model Via Trait? Event "updated" Is Not Called • 2 months ago

@lostdreamer_nl sorry forgot to write it. That is the weird part. In phpunit auth()->check() is true. In the model event its also true, but in trait it is never been called...

shadrix left a reply on How To Boot A Model Via Trait? Event "updated" Is Not Called • 2 months ago

@click I tried but same thing.

shadrix started a new conversation How To Boot A Model Via Trait? Event "updated" Is Not Called • 2 months ago

In my phpunit test I'm updating values:

/** @test */
public function it_updates_newsletter_when_user_privacy_is_updated() 
{
    
    $privacy = create('App\UserPrivacy', ['user_id' => auth()->id()]);

    $privacy->update(['firstname' => 'Philipp']);

}

And I'm trying to catch the updated event in a trait. But the thing is, it is never beeing called. Here is the trait:

trait UpdatesNewsletter
{
    /**
     * Boot the trait.
     */
    protected static function bootUpdatesNewsletter()
    {
        if (auth()->guest()) return;

        static::updated(function ($model){
            var_dump('is called by trait');
        });
        
    }
}

Just for my sanity check, I wrote the event catch for the model itself.

class UserPrivacy extends Model
{
    use UpdatesNewsletter;

     /**
      * Boot the model.
      */
    protected static function boot()
    {
        parent::boot();

        static::updated(function ($privacy){
            var_dump('is called by class');
        });
    }
}

And in my console I see the only message:

string(18) "is called by class"

What am I doing wrong?

9th July, 2018

shadrix left a reply on How To Use Mockery For A Class Used In A Controller? • 2 months ago

@Talinon thanks! It helps me a lot. Mockery is super weird to understand, especially because I didn't need it until now. Thank you again!

shadrix left a reply on How To Use Mockery For A Class Used In A Controller? • 2 months ago

Ah I see I need to use something like that

 $this->mock = \Mockery::mock(Newsletter::class);

 $this->app->instance(Newsletter::class, $this->mock);

I'm getting on a right track.

shadrix started a new conversation How To Use Mockery For A Class Used In A Controller? • 2 months ago

Let's say my controller looks like that.

public function store()
{
    Newsletter::subscribePending($email);
}

And Newsletter is a Class to use MailChimps Api easier.

Now how do I write a test for it?

I tried this, but it does not work. (I'm new to Mockery and it sends the data to mailchimp).

class NewsletterTest extends TestCase {

    use RefreshDatabase;

    public function setUp()
    {
        parent::setUp();

        \Mockery::mock(Newsletter::class);
    }

    public function tearDown() {
        \Mockery::close();
    }


    /** @test */
    public function a_guest_can_subscribe_to_newsletter() 
    {
        $this->withoutExceptionHandling();
        $this->json('post', route('newsletter.store'), ['email' => '[email protected]'])
             ->assertStatus(201);
    }
}

shadrix started a new conversation Would You Save Newsletters Emails On DB Or Leave It On MailChimp? • 2 months ago

So I'm new to Newsletters and I'm following a tutorial on how to set up a newsletter system with MailChimp in Laravel.

The question that arises is if I need to store the given email on my database as well?

Just in case if I want to dismiss the services of MailChimp. What are you doing?

1st July, 2018

shadrix started a new conversation How To Make Closures Readable? • 2 months ago

Let's say I have got something like this:

->with(['messages' => function ($q) use ($authId) 
         {
             return $q->where(function ($q) use ($authId) {
                         $q->where('user_id', $authId)
                                      ->where('deleted_from_sender', 0);
                          })
                            ->orWhere(function ($q) use ($authId) {
                                    $q->where('user_id', '!=', $authId);
                                    $q->where('deleted_from_receiver', 0);
                           })
                             ->latest('id');
                                                 
  }, 'userone', 'usertwo'])

How do I make this more readable? In Javascript I could simply say something like that:

->with(['messages' => this.specialScope])

25th June, 2018

shadrix left a reply on Using Ajax To Edit A Form • 2 months ago

I'm curious why don't you use Axios? It's soo freaky simple!

22nd June, 2018

shadrix started a new conversation How To Use WhereNotNull In WhereHas? • 3 months ago

I'm not able to use whereNotNull in my query. I need to check if the column "fresh_until" is not null. If it is not null, we check the date as well.

 ->when($this->date, function ($query){
         $query->whereHas('food.date', function ($query){
                            $query->where('valid_from', '<=', $this->date); //this works perfectly
                            $query->whereNotNull('fresh_until') //this not
                                         ->where('fresh_until', '>=', $this->date);
           });
   })

17th June, 2018

shadrix started a new conversation Is It Possible To Extend A Model With A Function With Macros? • 3 months ago

So I just learned about macros, but cannot figure out how to use it for models.

I want that all my models have the function:

public function hasAttribute($attr)
{
    return array_key_exists($attr, $this->attributes);
}

how would you register this function anywhere in Model?

shadrix left a reply on Show Me Everything But Two Conditions • 3 months ago

Offer::where(function ($query) {
      $query->where('offering_type', '<>', 'App\Food')
                    ->orWhere('offering_id', '<>', 8);
})

Would have been the answer

16th June, 2018

shadrix left a reply on Show Me Everything But Two Conditions • 3 months ago

@cronix I know! Sorry English is not my mother tongue. I try to explain what I'm trying to do:

  "offering_type"

Can be different types. But in my case I don't want to see the value ("offering_id" => "8" and "offering_type" => "App\Food")

I cannot set where("offering_id", '<>', "8") because there might be an "offering_id" => "8" but with another offering_type.

shadrix started a new conversation Show Me Everything But Two Conditions • 3 months ago

I feel bad to ask this, but I know it should be easy but I don't get the solution.

In my model query I just don't want to have the values "offering_id" => "8" and "offering_type" => "App\Food", but it should show me everything else.

I tried

Offer::where(function ($query) {
          $query->where('offering_type', '<>', 'App\Food')
                        ->where('offering_id', '<>', 8);
       })

But my result is empty, what am I doing wrong?

And I see that I should have several results like

#attributes: array:7 [
    "id" => "6"
    "user_id" => "7"
    "offering_id" => "6"
    "offering_type" => "App\Food"
    "created_at" => "2018-06-16 19:58:38"
    "updated_at" => "2018-06-16 19:58:38"
  ]

11th June, 2018

shadrix left a reply on Polymorphic Relationship - Is It Possible To Constrain Some Data Out With Eager Loading? • 3 months ago

@Vilfago I had the same idea, but maybe we can do it the other way around. Videos, Posts or other models are being recorded in ProfileContent::class. But maybe I can write my Trait so that only values that have reviewed = 1 are being recorded. I'm trying to work on it, but just to post it here. My trait looks like that (it's copied actually from @JeffreyWay )

<?php

 namespace App\Profile;

trait RecordsProfileContent
{
    /**
     * Boot the trait.
     */
    protected static function bootRecordsContent()
    {
        if (auth()->guest()) return;
        foreach (static::getContentToRecord() as $event) {
            static::$event(function ($model) use ($event) {
                $model->recordContent($event);
            });
        }
        static::deleting(function ($model) {
            $model->content()->delete();
        });
    }
    /**
     * Fetch all model events that require offer recording.
     * Also nur bei created soll es recorden. Es gibt natürlich auch
     * andere Events. Mich interessiert nur das
     *
     * @return array
     */
    protected static function getContentToRecord()
    {
        return ['created'];
    }
    /**
     * Record new content for the model.
     *
     * @param string $event
     */
    protected function recordContent($event)
    {
        $this->content()->create([
            'profile_id' => auth()->user()->profile->id,
            'type' => $this->getContentType($event)
        ]);
    }
    /**
     * Fetch the profile content relationship.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function content()
    {
        return $this->morphMany('App\ProfileContent', 'content');
    }
    /**
     * Determine the content type.
     *
     * @param  string $event
     * @return string
     */
    protected function getContentType($event)
    {
        $type = strtolower((new \ReflectionClass($this))->getShortName());
        return "{$event}_{$type}";
    }
}

shadrix left a reply on Polymorphic Relationship - Is It Possible To Constrain Some Data Out With Eager Loading? • 3 months ago

@Vilfago So my content function looks like this:

public function content()
{
    return $this->morphTo();
}

That is why I can retrieve both models with only one relationship.

Btw Vilfago, thank you for your patience and your help!

10th June, 2018

shadrix left a reply on Polymorphic Relationship - Is It Possible To Constrain Some Data Out With Eager Loading? • 3 months ago

@Vilfago Exactly that is what I did. And with('content') loads "content" => null. It's clear because reviewed = 0 and null is given. And whereHas does not work on morphTo... That sucks :D

shadrix left a reply on Polymorphic Relationship - Is It Possible To Constrain Some Data Out With Eager Loading? • 3 months ago

@ksparkar do you know where should I put whereHas()?

shadrix left a reply on Polymorphic Relationship - Is It Possible To Constrain Some Data Out With Eager Loading? • 3 months ago

@Vilfago so I really liked the idea to work with global scope, but how do you handle it when the content is null?

In my case reviewed is false that is why it's not loaded:

 content:null
 content_id:2
 content_type:"App\Food"
 created_at:"2018-06-10 10:32:43"
 id:3
 profile_id:1
 type:"created_food"
 updated_at:"2018-06-10 10:32:43"
 user_id:1

9th June, 2018

shadrix started a new conversation Polymorphic Relationship - Is It Possible To Constrain Some Data Out With Eager Loading? • 3 months ago

So I'm a bit stuck and I don't know how to solve it. I show you an example to understand my problem. My fictional table structure looks like that:

posts
    id - integer
    title - string
    body - text
    reviewed - boolean

videos
    id - integer
    title - string
    url - string

profileContent
    id - integer
    user_id - integer
    content_id - integer
    content_type - string

My problem is that when I morph the content, I don't want to have posts that are not reviewed. But the table "videos" does not have the column "reviewed" at all.

How would you solve it?

Now I show you some additional information:

With profileContents you get all content of the users profile:

public function profileContents()
{
    return $this->hasManyThrough(ProfileContent::class, Profile::class);
}

So my Query to get paginated Profile Content looks like that:

$user->profileContents()
      ->latest()
      ->with(['content' => function ($query){
          //That does not work! Because Videos has no reviewed and thus 
              nothing is loaded.
          $query->where('reviewed', true);
       }])
      ->paginate(5); 

But I don't know how I can "filter" the non-reviewed posts out. Any ideas?

Thank you!

7th June, 2018

shadrix started a new conversation Legal Rights About Creative Commons • 3 months ago

For my page, I'm creating a Component that is able to search via google for Public Domain Pictures.

The goal is that if a user does not have a specific picture (let's say french fries), he is able to use the component to choose a picture via google.

The user can sell his services on my page and the picture is needed to show what he is doing.

The picture itself is not stored on my server, only the URL to it, except if he wants to change it (crop something out or zoom more in).

Now google gives me these options in the query:

cc_publicdomain, cc_attribute, cc_sharealike, cc_noncommercial, cc_nonderived 

Besides public domain, is there something else I could use in my component?

cc_attribute is not really possible because how should the user know the name or how should he give the licensor the credits?

30th May, 2018

shadrix left a reply on How To Get The First Of Many Relationship? • 3 months ago

@Resin01 well but I don't want to call first(). I need this to be

$user->about  //And without the first()

shadrix started a new conversation How To Get The First Of Many Relationship? • 3 months ago

Is it possible to get only the very first of hasManyThrough? Since there is no hasOneThrough?

public function about()
{
    return $this->hasManyThrough(ProfileAbout::class, Profile::class);
}

A user has only one profile about page.

21st May, 2018

shadrix left a reply on Eloquent Does Not Eager Load When Calling Create() • 4 months ago

@lostdreamer_nl you are a genius! thank you! and never knew that you can call fresh like this

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.