ftrillo

Experience

12,140

18 Best Reply Awards

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

18th October, 2017

ftrillo left a reply on Relation Not Working In FormRequest • 9 hours 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 • 14 hours 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 day 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 day 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 day 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 day 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 day 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 day 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 day 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 day 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 day 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 day 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 • 2 days 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 • 5 days 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 • 5 days 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 • 5 days 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 • 5 days 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 • 5 days 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 • 5 days 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 • 5 days 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 • 5 days 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 • 6 days ago

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

ftrillo left a reply on How To Improve This Code ^^' • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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 • 6 days 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) • 6 days 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 • 6 days 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 • 1 week 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 • 1 week 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.

ftrillo left a reply on Retrieve Data From Existing Same/different Table • 1 week ago

Your method signature doesn't really make sense to me. Are you sending a post id to store a post?

Most of the attributes of the post you're about to store should be in the request object.

You're getting a bunch of empty values in your query because your $post is probably a mostly empty Post model. Try doing a dd() of it and see.

ftrillo left a reply on Queue Configuration In .env Not Considered • 1 week ago

I've seen before cases where running those commands would not actually remove the files. Maybe because of permission issues, maybe another thing.

Try removing the cache files manually. They are in storage\cache and bootstrap\cache, I think, can't really recall the file paths.

ftrillo left a reply on A Form With User Details, Roles And Permissions • 1 week ago

You could just get only the user and mark the the checkboxes according to the related models' existence. Something like this.

$user = User::findOrFail();

// Is this user an admin ?
$user->roles->keyBy('name')->has('admin'); // Assuming roles have a name field.

// Does this user have level 3 clearance
$user->permissions->keyBy('name')->has('level 3 clearance'); // Assuming again, there's a name field.

You could do the keyBy in the controller if you want, as to not repeat the operation multiple times. And the code might be different depending on your model's structure. But you get the idea.

ftrillo left a reply on Queue Configuration In .env Not Considered • 1 week ago

@jack100

Last time this happened to me, I was clearing the cache of the wrong project.

Please, share with us whatever was wrong when you find out. I'm sure It's going to be funny.

(I don't see anything wrong in the code you're showing us)

ftrillo left a reply on I Want To Calculate The Total Total Bytes For Each Server.But Having Problem Dispalying It In My View.My Table Name Is Servers And Coumn Name Are Servers_name And Bytes. • 1 week ago

@gaan10 If all your servers have different names you could just do a normal query, Without any grouping or aggregation.

ftrillo left a reply on Get Nested Data (model Data + Parent Data) • 1 week ago

Try that.

$summaries = DriverDegreeSummary::with('degree')->where('foo' => 'bar')->get();
// $summaries is a collection of DriverDegreeSummary models, each related to a 'degree'

foreach($summaries as $summary) {
    $summary // DriverDegreeSummary model
    $summary->degree // DrivingDegree model
}

ftrillo left a reply on How Can I Set Relationships With Mass Insert? • 1 week ago

@PawelMysior @dimnks

createMany() won't do a mass insert. It'll run a query for each model.

You could just include the foreign key in the arrays that you're passing to insert().

ftrillo left a reply on I Want To Calculate The Total Total Bytes For Each Server.But Having Problem Dispalying It In My View.My Table Name Is Servers And Coumn Name Are Servers_name And Bytes. • 1 week ago

Try something like this:

$servers = DB::table("servers")->groupBy('server_name')->select('server_name', DB::raw('sum(bytes) AS total_bytes'))->get();

ftrillo left a reply on Laravel: Unable To Use Route Which Is Not Inside Group Prefix In Laravel • 1 week ago

Run php artisan route:list and show the results, please.

Edit Your Profile
Update

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