shadrix

Experience

34,110

0 Best Reply Awards

  • Member Since 7 Months Ago
  • 311 Lessons Completed
  • 8 Favorites

18th July, 2018

shadrix left a reply on Laravel Mix: Prevent Moment.js Locales • 4 days 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? • 1 week 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? • 1 week 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 • 1 week ago

+1

shadrix left a reply on Is There A Good Package For Subdomain Laravel Translations? • 1 week 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? • 1 week 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? • 1 week 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 • 1 week 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 • 1 week 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 • 1 week 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 • 1 week ago

@click I tried but same thing.

shadrix started a new conversation How To Boot A Model Via Trait? Event "updated" Is Not Called • 1 week 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? • 1 week 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? • 1 week 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? • 1 week 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? • 1 week 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? • 3 weeks 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 • 3 weeks 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? • 1 month 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? • 1 month 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 • 1 month 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 • 1 month 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 • 1 month 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? • 1 month 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? • 1 month 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? • 1 month 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? • 1 month 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? • 1 month 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? • 1 month 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 • 1 month 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? • 1 month 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? • 1 month 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() • 2 months ago

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

shadrix started a new conversation Eloquent Does Not Eager Load When Calling Create() • 2 months ago

In my controller I'm creating a new line in the database with:

 return  Food::create(['user_id' => auth()->id()])
                ->load('address', 'cookInfo') ;

But it just loads 'address' and 'cookInfo' and forgets to load my protected $with in the Food Model:

 /**
 * The relations to eager load on every query.
 *
 * @var array
 */
 protected $with = ['cook', 'time', 'picture', 'favorites'];

So it just completely ignores it and I have to load the rest like this:

->load('address', 'cookInfo', 'cook', 'time', 'picture');

Does someone have a clue why it is like that?

and p.S. if I just say Food::find(1) I get my eager loading.

14th May, 2018

shadrix started a new conversation How Does It Work? Eloquent Models Can Be Called Statically And Non Static. • 2 months ago

I'm curious how can I write a code like that? Because with Eloquent I can call these like that:

Model::find(1);

Or

$a = new Model();
$a->find(1);

Now I want to have the same method name as well because I'm stuck with

  public static function uncompleted(){}
  public function uncompleted() {} //not working

12th May, 2018

shadrix left a reply on Where Would You Save Dozens Of Lists Of Arrays? • 2 months ago

@Nash and @Drfraker thank you for the answer. So the list is set once and is never changed after. That is why I didn't want to set it to the database.

But it also feels weird to set the data in a config file. Isn't there a way to save a file to {name}.json in the Storage Folder and load the file?

11th May, 2018

shadrix started a new conversation Where Would You Save Dozens Of Lists Of Arrays? • 2 months ago

So let's say I have an array list with adjectives that describe a thing (> 20).

I need to call this list via javascript but as well for php.

Besides that I have a copy of the list in every language that I support.

Now, I'm actually not sure how and where to save the lists.

Before thinking about this problem I just had a blade list that contained the array and I could get it with:

 //giving the list to a vue component
 :text='@include('data.listofadjectives')'

My guess is that I should save it as Json. But where should I save it? In the storage folder? And if so, how can I import it with Javascript?

I hope it's understandable. Thank you!

10th May, 2018

shadrix left a reply on Can Not Reach "email" Value To Reset Password • 2 months ago

Hmm... the old email cannot work, but the idea with session should work. Before sending the mail you could save the email in the session.

Otherwise, you could get the mail by finding the user with the token.

shadrix started a new conversation Does It Make A Difference If I Use $dates In Eloquent? • 2 months ago

I'm trying to understand the difference.

In my model:

class Info extends Model
{
    protected $casts = [
    'valid_from' => 'date:Y-m-d',
    'valid_end' => 'date:Y-m-d',
    ];

    protected $dates = ['valid_from', 'valid_end']; 
}

I tried with $dates and without. I get the same result.

So I guess it should be the same? First eloquent is mutating it to date and only when I'm using an Array or Json Output I get my correct format?.

9th May, 2018

shadrix started a new conversation Ignores My Middleware In Controller, Why? • 2 months ago

I don't get it. Php unit is just ignoring my middleware in my controller. My code is simple:

    public function __construct()
{
    $this->middleware(function ($request, $next) {
        if(auth()->check() && auth()->user()->confirmed){
            return redirect()->route('home');
        }

        return $next($request);
    });
    
}

When I check with:

 dd('test');
 $this->middleware...

I can see the test. But when I put it inside the middleware I cannot see.

 /** @test */
 public function a_confirmed_auth_user_cannot_see_the_resend_page(){

    $this->signIn();

    $this->get(route('resend.confirm'))->assertRedirect(route('home'));
 }

It fails because it goes straight to my index() of route('resend.confirm'). I can't explain it :(

p.S. if I test it with the Browser, everything works fine.

8th May, 2018

shadrix started a new conversation Laravel Dusk - How To Deal With Recaptcha? • 2 months ago

How would you deal with recaptcha? In my case, I use the invisible one, but don't know how to write a test for that.

shadrix left a reply on Oh-my-zsh Laravel 5 Plugin Available • 2 months ago

Thanks!!

3rd May, 2018

shadrix left a reply on Do I Need An HTML Sanitizer/Purifier? • 2 months ago

@jlrdw thanks!

@Cronix

So a User can "tweet" a message, but the message itself is displayed with vue v-text. So I think it should be save then?

And what do you think if the User uses an WYSIWYG Editor. Should I still sanitize? My editor is doing a sanitization front end. Is that enough?

shadrix started a new conversation Do I Need An HTML Sanitizer/Purifier? • 2 months ago

So when I save something to the database, even if I try to write code inside. Laravel always displays it as text and not code.

So should I use an HTML Sanitizer/Purifier? And if so, when is it the case?

2nd May, 2018

shadrix started a new conversation Validate Checkbox: If One Is Chosen, Others Are False. If Others Are Choosen, The First Is False. • 2 months ago

So I have got four checkboxes with let us say these values:

["none", "X", "Y", "Z"]

If you check the first checkbox with the value "none", you are not able to choose the other three.

["none"]  //stays none

If you choose the rest let us say:

["X"] || ["Y","Z"] || ["X","Y","Z"]

this is all correct.

How can I validate such a case with the available Validation Rules provided by Laravel, without using Complex Conditional Validation?

My start is:

 'preferences' => 'sometimes|required',
 'preferences.*' => 'sometimes|required|in:none,X,Y,Z',
 'preferences.0' => 'sometimes|required_unless:preferences.*,in:X,Y,Z',

But I know that the third line cannot work, but I just don't know how to solve it.

Thank you!

29th April, 2018

shadrix left a reply on Why Is A Empty Wildcard Not Acceptable For Request? • 2 months ago

@Snapey is that also possible for

 Request::is('settings/*?')

that is not working :(

shadrix started a new conversation Why Is A Empty Wildcard Not Acceptable For Request? • 2 months ago

Currently I've to do something like that:

Route::get('/settings','Settings\[email protected]'); Route::any('/settings/{any}', 'Settings\[email protected]') ->where(['any' => '.*']);

Without the first line, I could not go to domain.test/settings

The same is for Request::is('settings/*')

Why can't the Wildcard be empty?

shadrix left a reply on Is There A Difference Between Lazy Eager Loading And E.g. User->info ? • 2 months ago

@Cronix Sorry I thought you mean it without the load part.

But thank you it's a good tip!

28th April, 2018

shadrix left a reply on Is There A Difference Between Lazy Eager Loading And E.g. User->info ? • 2 months ago

@Cronix hmm... good point. Perhaps because I remember to have learned that in the view part you should not call queries. (Only in the controller/model part).

But if you see it as "variables" then it would be also viable.

(but honestly, I like to see what variables I get to my views)

(but you can correct me, I have so much to learn :)

Edit Your Profile
Update

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