Buy your loved one the ultimate gift. Lifetime gift certificates are $100 off.

ftrillo

Experience

14,030

21 Best Reply Awards

  • Member Since 6 Months Ago
  • 0 Lessons Completed
  • 0 Favorites

25th October, 2017

ftrillo left a reply on PHP - Pushing Only Key First To An Array And Adding Values Later • 1 month ago

That looks like a nested array more than an associative array.

If you want an array of contents where the key is the content_id and the value is an array of taxonomy names, try this:

(assuming you defined a taxonomies relation method in the content model)

$contentTaxonomies = [];
foreach($contents as $content) {
    $contentTaxonomies[$content->id] = $content->taxonomies->pluck('name');
}

or

$contentTaxonomies = $contents->keyBy('id)->transform(function($content) {
    return $content->taxonomies->pluck('name');
})->all();

ftrillo left a reply on How To Stop Laravel Scheduler In Case Of First Task Failure • 1 month ago

You could use when() in the scheduler to make sure that a certain command only runs when a given function returns true. Like this:

$schedule->command('bank:do-stuff')->daily()->when(function () {
    return true; // TODO: check if the connection's good
});

As for aborting a command that is running, any exception thrown will abort execution.

ftrillo left a reply on Constraining Relationship Query By An Array • 1 month ago

Do you want the contents that are related to ALL of the taxonomies in the array? Or the contents that are related to ANY of the taxonomies in the array?

Also, where are you getting the names from? Because It would be easier to do if instead of getting an array of names you got an array of primary keys(aka id).

ftrillo left a reply on Order By Tag Priority • 1 month ago

If an user can 'tag' a location with more or less priority, then It makes sense to save the priority value in the pivot table.

To get the sorted results you'd probaby need to join both tables and order by the priority column.

ftrillo left a reply on Call A Method Inside The Same Method! • 1 month ago

Well, $something is not defined anywhere. And you're calling ThisFunc() instead of $this->ThisFunc().

Also, function names should begin with lower case. thisFunc()

ftrillo left a reply on Laravel Get An Object From Collection • 1 month ago

Call the collection's first() method and pass a callback that checks if the id is the one you're looking for. Like so:

$itemIWant = $collection->first(function ($value) {
    return $value->id == $idOfItemIWant;
});

20th October, 2017

ftrillo left a reply on Adding And Populating A Field To The Users Table • 1 month ago

If you can get the email of any user just by concatenating the same domain at the end of the username. You could add an accessor to the User model.

docs: https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor

It'd work like this:

//User model

public function getEmailAttribute()
{
    return $this->username.'@domain.net';
}

With that function defined you can access the email of any user like any other attribute:

$user->username // Gets me the username
$user->email // Gets me the email

ftrillo left a reply on Calculate The Difference In Days From An Array • 1 month ago

diffInDays() returns an integer that's the number of days between two dates truncated down (so 23 hours is 0 days).

And reduce() is the same than doing a foreach and adding the results yourself.

How do the results differ from the expected results? Without knowing that I can't help much.

19th October, 2017

ftrillo left a reply on Calculate The Difference In Days From An Array • 1 month ago

You're not being very clear. If you want the total number of days you could do this:

// Assuming each item represents a range of dates with a start and an end
$days = $collection->reduce(function ($carry, $item) {
    return $carry + $item->start->diffInDays($item->end);
}, 0);

18th October, 2017

ftrillo left a reply on Relation Not Working In FormRequest • 1 month ago

Does that user have a related Club?

Compare the result of running

$user->club

and

Club::where('user_id', $user->id)->get();

ftrillo left a reply on How To Manually Query The Soft Deleted Data • 1 month ago

Straight from the docs:

If a model has a non-null deleted_at value, the model has been soft deleted.

So basically you basically this: $query->whereNotNull('deleted_at).

17th October, 2017

ftrillo left a reply on Jobs Processed, But Not Doing Anything • 1 month ago

If you're running Laravel 5.5 try using the dispatch static method on the class instead of the helper. Like so;

SendReminderEmail::dispatch()->onQueue('myEvents');

ftrillo left a reply on Model Relationship Not Working Out As Expected. Keeps Using Wrong Foreign Id. • 1 month ago

UserSetting

public function employee_layout()
{
    // return $this->hasOne('App\Models\EmployeeLayout'); // wrong!
    return $this->belongsTo(App\Models\EmployeeLayout);
}

ftrillo left a reply on Jobs Processed, But Not Doing Anything • 1 month ago

You have to instantiate a job to dispatch it in the first place. If the constructor isn't running then there's something wrong before the queue even gets involved.

What's the code that dispatches the job?

ftrillo left a reply on Laravel OrderBY With Specific Value • 1 month ago

I would make the country a related model and order by the foreign key value. Specially if the records table is very big.

ftrillo left a reply on Carbon Match By Date, Month And Year • 1 month ago

@abhishek009 You might want to show the code that isn't wroking.

ftrillo left a reply on Carbon Match By Date, Month And Year • 1 month ago

If you want to match only year, month and day, ignoring time, you have to use whereDate to compare with a date string. Like so:

$query->whereDate('record', '=', $carbonObject->toDateString());

ftrillo left a reply on Property [category] Does Not Exist On This Collection Instance. • 1 month ago

First, in your innermost loop in the view you're calling $events, the variable you're looking for is $event.

Second, calling $event->category is not going to return a collection, because It's a belongsTo relationship. It'll return a single Category model. So, either you should not have that loop or you defined the wrong relationship.

ftrillo left a reply on Jobs Processed, But Not Doing Anything • 1 month ago

Are you dispatching the jobs on the default queue connection? If not, you need to pass the connection name to the queue:work command.

ftrillo left a reply on Laravel 5.1 - 5.3 Upgrade - Broken Routes • 1 month ago

If I recall correctly there was a change on how the routes inside groups inherit, or not, the prefix.

Try running php artisan route:list. Your routes url might not be what you think they are.

ftrillo left a reply on Carbon Match By Date, Month And Year • 1 month ago

Try calling toDateString() on the Carbon object. You also don't need the '=' argument, that's the default.

GetRecords::where("student_id",$id)->where("record" ,Carbon::parse($selected_date)->toDateString())->first();

16th October, 2017

ftrillo left a reply on Return Relationship IDs • 1 month ago

What your global scope is doing is eager loading the related Type model on every query.

If you want to get an array of containing the ids of related Typemodels you could do this:

$partner->types->pluck('id')->all();

If you want to shorten that expression you could define a custom accesor that returns that.

Details here: https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators

13th October, 2017

ftrillo left a reply on Sync Saving Just One Column • 1 month ago

Then those ids should be the keys of the array. And each should have a value indicating the user_id. Like this:

// Currently you have this:
$arrayProducts = [12, 25, 138]; // Those are ids

// Instead you should have this
$arrayProducts = [ // Notice now the ids are the keys of the array
    12 => ['user_id' => Auth::id()], // The user_id could be the id of any user
    25 => ['user_id' => Auth::id()],
    138 => ['user_id' => Auth::id(),]
];


$newProduct->products()->sync($arrayProducts);

ftrillo left a reply on Sync Saving Just One Column • 1 month ago

Of course it doesn't work. You're not sending what you're supposed to. What are the contents of arrayProducts?

Each key of the array is the id of a related model, and the associated value is an array indicating which fields should be filled in the pivot table.

ftrillo left a reply on Eloquent Model Collections With Duplicates • 1 month ago

Where you put the code depends on what you want it for. If all this randomizing is only for testing purposes or to get a random set of data to work with, you should keep in Factories or Seeders.

As for how to have some wrestlers keep a manager and others not... I would generate the wrestlers as I described before, that would get you a set of wrestlers who currently have no manager (either because they never had one or because they fired all of them after a period of time). At the end of the process, you only need to pick any number of wrestlers you want and make them hire a new manager but not fire him.

ftrillo left a reply on Sync Saving Just One Column • 1 month ago

Instead of passing simply an array of products Ids, like this:

$newProduct->products()->sync([1, 2]);

You should pass an array where the keys are the Ids, and the values are the extra fields you want in the pivot table, like the user_id in this case.

$newProduct->products()->sync(1 => [['user_id' => Auth::id()], 2 => ['user_id' => Auth::id()]]);

You can get an array with that structure from a collection of models like this:

$ids = $productCollection->keyBy('id')->transform(function($product) {
    return ['user_id' => Auth::id()]
})->all();

ftrillo left a reply on Reject Collection Method • 1 month ago

In the code above you're rejecting any Post of TYPE_ONCE or TYPE_DAILY.

Your second block of code is only rejecting posts of TYPE_ONCE.

It's only natural that you get different results. Which is the intended behaviour?

ftrillo left a reply on Relationship Understanding Problem • 1 month ago

After creating the tables in your DB. The next step is defining the relationships in each model. Details here: https://laravel.com/docs/5.5/eloquent-relationships#defining-relationships.

If you're just learning Eloquent you should start with simpler relations, but here we go.

Looking at the tables it seems these are the relationships:

User: hasMany routes() and hasMany locations() I don't know why the locations table has an user_id though.

Route: belongsTo user(), belongsTo locationA() and belongsTo locationB() For locationA and locationB you'll have to define a custom foreign key in the relation method. It's all in the documentation.

Location: belongsTo user(), hasMany routeA() and hasMany routeB() Again, routeA and routeB are relations to the same model, but with different foreign keys. You can name the methods however you want to make them make sense in your buisiness logic.

After all the relations are defined, or at least the ones you need, you can get the routes of the authenticated user like this:

// The locations are eager loaded for performance
$userRoutes = Auth::user()->routes()->with('locationA', 'locationB')->get();

foreach ($userRoutes as $route) {
    $route; // the Route model
    $route->locationA // The Location model with id matching location_id_a
    $route->locationB // The Location model with id matching location_id_b
}

ftrillo left a reply on How To Retrieve All Of The Ids In A Nested Array • 2 months ago

Region model

public function getIds()
{
    $ids =  [$this->id];
    foreach ($this->children as $child) {
        $ids = array_merge($ids, $child->getIds());
    }
    return $ids;
}

Try calling this function. Should get you the id of a region and all of it's childrens, and It's children's childrens, etc.

12th October, 2017

ftrillo left a reply on How To Retrieve All Of The Ids In A Nested Array • 2 months ago

To get all the ids try:

$arrayOfIds = $collection->flatten()->pluck('id')->all();

Then to query anything with that id:

Model::whereIn('whatever_id', $arrayOfIds)->get();

ftrillo left a reply on Performance Issue • 2 months ago

What query are you running to get the $products collection?

ftrillo left a reply on How To Improve This Code ^^' • 2 months ago

$beShareValue = max($beShareValue, $object->fixedAmount);

Caring is the first step. I learn by reading books and working, mostly.

ftrillo left a reply on Eloquent Model Collections With Duplicates • 2 months ago

Well, I would make a function that takes care of a wrestler hiring a manager and firing him after a random period of time. That function would take a date as an argument, indicating the earliest possible hiring date (in the pivot table).

Then for each wrestler you can generate a random number, let's say between 0 and 5. And you call the function I mentioned before that many times.

ftrillo left a reply on How To Get Data From Many To Many Relationship • 2 months ago

$company->activity->name wont work because a single company can have more than one activity. Knowing that:

$company->activity; // returns a collection of activity models
$company->activity->first(); // Gets you the first activity of the company

The relation should be called activities, instead of activity, to avoid being missleading.

ftrillo left a reply on Eloquent Model Collections With Duplicates • 2 months ago

Whenever I have to generate random dates I usually start from the last one:

$lastDate= $faker->date;
$earlierDate= $faker->date('Y-m-d', $max = $lastDate);
$earliestDate = $faker->date('Y-m-d', $max = $earlierDate);

If you need to generate them from earliest to latest, the best way I've found is making the previous date a Carbon object and adding a random number of days(with a limit). Since faker doesn't seem to support a min attribute when generating dates.

ftrillo left a reply on Object-oriented Design Book • 2 months ago

@tisuchi Hey, thanks for that list. I'll end up reading most of those.

ftrillo left a reply on Multiple Many To Many Relationship Between Same Models • 2 months ago

Oh, I see what you mean. The only way I know of saving stuff in the pivot table when attaching models is this:

$meeting->users()->attach($user->id, ['type' => 'caller']);

Maybe you could just do a wrapper function to shortten that expression. Something like this:

Meeting model

public function attachUser(User $user, string $type)
{
    $meeting->users()->attach($user->id, ['type' => $type]);
}

ftrillo left a reply on Trouble Chaining Multiple Relationships • 2 months ago

You could just filter the collection in the view as needed.

// that's the value in the pivot table of the plan with id 1.
$field->data->where('id', 1)->first()->pivot->value;

If you want a cleaner view you could define a getter in the Field model:

public function getValueOfPlan($plan_id)
{
    return $this->data->where('id', 1)->first()->pivot->value;
}

And then call it from the view

$field->valueOfPlan(1);

ftrillo left a reply on Multiple Many To Many Relationship Between Same Models • 2 months ago

You set up a many to many relationship between User and Meeting, and you include an extra field called type in the pivot table. Then you set up our Meeting model like this:

public function users()
{
    return $this->belongsToMany(User::class); // all users
}

public function callers()
{
    return $this->belongsToMany(User::class)->wherePivot('type', 'caller');
}

public function attendees()
{
    return $this->belongsToMany(User::class)->wherePivot('type', 'attendee');
}

public function writers()
{
    return $this->belongsToMany(User::class)->wherePivot('type', 'writer');
}

ftrillo left a reply on How To Get Data From Many To Many Relationship • 2 months ago

Assuming you setup the relationships in the Eloquent, try this:

I don't actually know if that would work for sure, but give it a try.

$companies = Company::whereNotNull('businessclub_id')->whereHas('activities', function($query) {
    $query->wherePivot('countrycode', 'ml');
});

ftrillo left a reply on Object-oriented Design Book • 2 months ago

I read this one when I wanted to learn about design patterns. It's a good one. Even if It doesn't look very serious. http://shop.oreilly.com/product/9780596007126.do

There's one about object oriented design. I haven't read that one, but I'm sure It's worth looking into: http://shop.oreilly.com/product/9780596008673.do

ftrillo left a reply on Trouble Chaining Multiple Relationships • 2 months ago

Assuming you want a collection of FieldCategory models, each including a collection of Field models. And each Field model includes the data relationship too.

Something like this would do:

$categories = FieldCategory::with('fields.data')->get();

Then in the view:

@foreach($categories as $category)
    <!-- Display info of each category -->

    @foreach($category->fields as $field)
        <!-- Display the field -->
        
        @foreach($field->data as $plan)
            {{ $plan->pivot->value }} <!-- That's the value in the pivot table -->
        @endforeach
    @endforeach
@endforeach

Hope that helps.

ftrillo left a reply on Laravel Transformers • 2 months ago

I'm going to format the code, for everyone's sake:

{ "id": 2, "name": "test", "datetime": "test", "status": "1", "sporslevels": [ { "id": 1, "sport_id": 3, "sports_level_id": 1, "created_at": null, "updated_at": null, "pivot": { "user_type_id": 2, "sports_sports_level_id": 1 }, "sports_club": { "id": 3, "name": "fb", }, "level_club": { "id": 1, "name": "5x5", } } ] }

And

{ "id": 2, "name": "test", "sporslevels": [ { "sports_club": { "id": 3, "name": "fb", }, "level_club": { "id": 1, "name": "5x5", } } ] }

ftrillo left a reply on Compere Migration Scheme To Db • 2 months ago

You can check the structure of a table by calling certain methods on Schema.

Like:

Schema::table('myTable')->getColumnListing(); // list of columns
Schema::table('myTable')->getColumnType('created_at') // Returns the type of a column. 'timestamp' in this case
Schema::table('myTable')->hasColumn('my_column'); // Checks column existence

You can see a complete list here: https://laravel.com/api/5.5/Illuminate/Database/Schema/MySqlBuilder.html

ftrillo left a reply on Submit Form With Multiple Values • 2 months ago

@Laravelephant

Try this logic:

foreach($request->answer as $key => $answer) {
    $model = new Answer();
    $model->answer = $answer;
    $model->list_id = $request->list_id[$key];
    $model->section_id = $request->section_id[$key];
    $model->question_id = $request->question_id[$key];
}

ftrillo left a reply on Submit Form With Multiple Values • 2 months ago

If all your questions in the view have those hidden inputs with the same name, then It's only natural they all end up with the same values.

Shouldn't you send them as an array? Like this:

<input type="hidden" name="list_id[]" value="{{$list->id}}">
<input type="hidden" name="section_id[]" value="{{$section->id}}">
<input type="hidden" name="question_id[]" value="{{$question->id}}">

That's assuming all questions have those inputs.

ftrillo left a reply on Get Nested Data (model Data + Parent Data) • 2 months ago

If you want the full related model to be included in the json, try this:

In Summary model:

protected $appends = ['degree'];

ftrillo left a reply on Dealing With Complexity In Controllers • 2 months ago

@kataklys The single responsability principle can be read as, 'every class should only have one reason changed'. Your User model will have to be changed if you alter your users table.

Adding a bulk insert method to the class, wont add any extra reasons to change the class, because It's still depending on the users table staying the same. At least that's how I see It.

If you really want it in separate places you should look into Repositories.

11th October, 2017

ftrillo left a reply on Queue Configuration In .env Not Considered • 2 months ago

Restart the server? If a worker is running that code you should restart it too.

ftrillo left a reply on Queue Configuration In .env Not Considered • 2 months ago

Try checking the current environment of the app. App::environment().

If, for some reason, It's running on testing environment that would explain the weird behaviour. I'm running out of ideas.

Edit Your Profile
Update

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