# robjbrain

Member Since 4 Years Ago

7,610
Experience Level 2

2,390 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

• Complete a lesson — 100pts
• Create a forum thread — 50pts
61
Lessons
Completed
0
Awards

Earned once you have completed your first Laracasts lesson.

• #### First Thousand

Earned once you have earned your first 1000 experience points.

• #### One Year Member

Earned when you have been with Laracasts for 1 year.

• #### Two Year Member

Earned when you have been with Laracasts for 2 years.

• #### Three Year Member

Earned when you have been with Laracasts for 3 years.

• #### Four Year Member

Earned when you have been with Laracasts for 4 years.

• #### Five Year Member

Earned when you have been with Laracasts for 5 years.

• #### School In Session

Earned when at least one Laracasts series has been fully completed.

• #### Welcome To The Community

Earned after your first post on the Laracasts forum.

• #### Full Time Learner

Earned once 100 Laracasts lessons have been completed.

• #### Subscriber

Earned if you are a paying Laracasts subscriber.

• #### Lifer

Earned if you have a lifetime subscription to Laracasts.

• #### Chatty Cathy

Earned once you have achieved 500 forum replies.

• #### Laracasts Veteran

Earned once your experience points passes 100,000.

• #### Ten Thousand Strong

Earned once your experience points hits 10,000.

• #### Laracasts Master

Earned once 1000 Laracasts lessons have been completed.

• #### Laracasts Sensei

Earned once your experience points passes 1 million.

• #### Top 50

Earned once your experience points ranks in the top 50 of all Laracasts users.

29 Mar
3 weeks ago

robjbrain left a reply on Bind Posted Data To A Model In Laravel 5.4

I solved the issue differently by adding some methods to my FormRequest class

/**
* @var array
*/
protected $modelIds = []; /** * @var array */ protected$models = [];

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [];
}

/**
* Handle a failed authorization attempt.
*
* @return void
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function failedAuthorization()
{
throw new AuthorizationException($this->failedAuthorisationMessage); } /** * @param string$key
* @return \Illuminate\Database\Eloquent\Model|null
* @throws \Exception
*/
public function getModel(string $key): ?Model { return$this->models[$key] ??$this->findModel($key); } /** * @param string$key
* @return \Illuminate\Database\Eloquent\Model|null
* @throws \Exception
*/
protected function findModel(string $key): ?Model { if (!$this->modelIds[$key]) { throw new \Exception('Unknown model class for key: ' .$key);
}

$modelClass =$this->modelIds[$key]; return$this->modelIds[$key] = (new$modelClass)->resolveRouteBinding($this->input($key));
}



Then in my controller I can do:

protected $modelIds = [ 'user_id' => User::class, 'comment_id' => User::class, 'something_else_id' => Something::class ]; public function archive(Request$request){
$request->getModel('user_id')->doSomething():$request->getModel('user_id')->doAnotherThing():
}


And it will just do one query.

The benefit of this is that I can use this anywhere I have a request object, such as in the request objects authorise method.

public function authorize() {
$this->user()->can('ban',$this->getModel('user_id'));
}


If I then use $this->getModel('user_id') in my controller it won't make multiple requests! What's more I can add this method:  protected function modelExistsRule() { return function ($attribute, $value,$fail) {
return $this->getModel($attribute) ?: $fail(trans('validation.exists')); }; }  And instead of doing 'exists:user,id' and thus doing two queries (an exists query and a select query) it just uses the one select query. NOTE: This could all be improved in lots of ways but it works for all my use cases right now. 22 Mar 1 month ago robjbrain left a reply on All Problems With The New Laracasts Design Pagination is really annoying, this thread is a good example. If I click on it, it doesn't automatically take me to the latest reply, I have to scroll and load more. From a users profile if I click on a recent activity item (using the one from musa11971 above as an example). It takes me to a url that looks like this "https://laracasts.com/discuss/channels/site-improvements/all-problems-with-the-new-laracasts-design?page=5#reply-491275" But it just shows the start of the topic, not page 5 or the specific post I clicked to read 04 Dec 4 months ago robjbrain left a reply on Eloquent Relationship Clashing With Property Name Thanks for the reply @jlrdw While I haven't had an issue now, I might do in the future. Such as my example with using the clean() and dirty() Eloquent methods. I don't think the fact that I haven't noticed an error yet is enough to say there never will be one. I just did a little test and doing this in a controller is fine: return$this->changes->count();


Because changes is an Eloquent collection coming from the changes() method.

But this inside the model:

public function testChanges()
{
return $this->changes->count(); }  Throws an error "Call to a member function count() on array" Because it's happening within the class itself it has access to the protected property $changes on the HasAttributes trait which is an array.

It seems strange to me that I can't find anyone else who has encountered this.

It seems there should probably be warnings thrown if your attribute clashes with a protected property.

03 Dec
4 months ago

robjbrain started a new conversation Eloquent Relationship Clashing With Property Name

I have a model called Change and a model called Submission and the Submission model has many Changes. I noticed when accessing $submission->changes my IDE flagged up that this was a protected property because the HasAttributes trait has the property$changes.

Does this mean there are certain keywords that we can't use for attributes and relationships in an Eloquent model?

Surprisingly my code has worked fine with a "changes" relationship so far, but I imagine there may be issues in some use cases, such as if an observer wanted to use the dirty() and clean() methods.

Has anyone had this issue before? Do you just have to rename the attribute/relationship? What happens if Laravel adds a new property to a trait in the future, do you have to refactor to not clash the names?

I'm surprised this hasn't come up more often. Has Laravel put something in place to prevent this being an issue?

20 Nov
5 months ago

I've found that tools such as debugbug, clockwork and telescope have a big affect on this.

I've attempted to get these to use something other than files such as redis, but that hasn't made a great deal of difference

19 Nov
5 months ago

robjbrain left a reply on Why Does Laracasts.com Use JQuery Over VueJS

@THYROSIS - Yeah I didn't actually realise that at the time. I just saw jquery and assumed.

I guess the question still stands, why jquery AND vuejs. What thing specifically required jquery? I haven't found a situation where I needed both yet.

robjbrain left a reply on Why Does Laracasts.com Use JQuery Over VueJS

@IANFAIN - Hence tagging him and asking if anyone else had heard it covered in any podcasts ;)

18 Nov
5 months ago

robjbrain left a reply on Why Does Laracasts.com Use JQuery Over VueJS

I guess that answer is kind of a given, the question is really, why was jQuery a better fit for laracasts than Vue (or react or angular or anything else)

robjbrain started a new conversation Why Does Laracasts.com Use JQuery Over VueJS

I don't really want to get into an argument with people over jQuery vs VueJS but I wandered if there was anywhere @jeffreyway has discussed his decision to use jQuery over VueJS for the new Laracasts? I don't listen to podcasts but often see reference to them so perhaps it has been explained there?

With all the guides for Vue on the site I was sure the new version was going to use Vue so I was surprised to see jQuery being used.

15 Nov
5 months ago

I've had this issue multiple times (often after restarting machine). Normally I go through the steps of installing the the nfs plugin for vagrant and it gets back to normal, but now its happened for 2 days and I can't get below 10-20 second load times.

Has anyone come up with any other solutions?

I've got the vagrant plugin installed and nfs-kernel-server installed on the vagrant machine.

I've got the following in my Homestead.yaml

- map: c:\my\code
to: /home/vagrant/code
type: nfs
mount_options: [nolock,vers=3,udp,noatime,actimeo=1]


and i've done vagrant reload --provision

But like I said i've still got 10-20 load times.

Surely there's got to be a better way? I can't believe everyone on Windows using vagrant is having these sorts of issues.

robjbrain left a reply on Route Model Binding With Soft Deleted Model

For anyone else finding this you can overwrite resolveRouteBinding() in your model.

public function resolveRouteBinding($value) {$this->withTrashed();
return parent::resolveRouteBinding($value); }  12 Sep 7 months ago robjbrain started a new conversation If You Want Multiple Models From Your API, Do You Make Multiple Http Requests Or Just One? I've been trying to Google this to find past experiences and best practices without much luck. So I thought i'd ask here. When you have a page which requires lots of bits of data, do you make one request or multiple? For instance, imagine you have a dashboard which has four cards which list the 5 most recent categories, posts, comments and users Do you do one request which knows what to return from the controller: created () { axios.get('/api/dashboard').then(response => { this.categories = response.data.categories; this.posts = response.data.posts; this.comments = response.data.comments; this.users = response.data.users; } }  Or do you do 4 separate requests? created () { axios.get('/api/categories?limit=5&orderBy=recent').then(response => { this.categories = response.data; } axios.get('/api/posts?limit=5&orderBy=recent').then(response => { this.posts = response.data; } axios.get('/api/comments?limit=5&orderBy=recent').then(response => { this.commments = response.data; } axios.get('/api/users?limit=5&orderBy=recent').then(response => { this.users = response.data; } }  The latter seems more in line with how Laravel is setup with its resource controllers. However it's also likely to be slower and more resource intensive. If you have auth and guards and other such things they need to be run 4 times for each request. I only say slower because presumably the lag, if there is any, is between the client and the server, rather than the server and its db. I guess the second example could also be faster. So how do you do it and why? If there are predefined best practices could someone suggest some terminology that makes it easier to research through Google? 31 Aug 7 months ago robjbrain left a reply on VueJS Resets Numeric Keys @click that creates a whole host of problems in the backend. If it's a string then I need to ensure that they're all unique and in the form_fields table I would have to use the string instead of the ID and make sure that it was updated should the string ever be updated. robjbrain left a reply on VueJS Resets Numeric Keys Ah it seems to be because i'm using Laravel's API Resource. FieldResource::collection($fields->keyBy('id'));


Since it's a collection (an object) I would have hoped it would return an object, but I guess not.

I've clicked through this method in PHPStorm and in classical Laravel function it's jumping through alot of classes where it's difficult to find where the rendering is actually happening.

Illuminate\Http\Resources\Json\JsonResource
Illuminate\Http\Resources\Json\AnonymouseResourceCollection
Illuminate\Http\Resources\Json\ResourceCollection
Illuminate\Http\Resources\CollectsResources
// and more...



Interestingly this does return an object

FieldResource::collection($fields)->keyBy('id');  But that doesn't feel right? robjbrain started a new conversation VueJS Resets Numeric Keys I have a dynamic form that can have multiple fields. Not all fields necessarily appear on a form but I still want to access them. In PHP it would look something like this: $fields = [
1 => $fieldObject1, 2 =>$fieldObject2,
3 => $fieldObject3, 4 =>$fieldObject4,
5 => $fieldObject5, 6 =>$fieldObject6,
];

$form = [ 'name' => 'My Form', 'fields' => [1,2,4,6] ]; foreach($form->fields as $field_id) { echo$fields[$field_id]->renderHtml(); }  Or something like that (realistically I would probably use a collection or something, but this was a simpler example). However when I return$fields and $form from Laravel into a VueJS component, the id's are not retained and it looks like this: fields: Array[6] 0: Object, 1: Object, 2: Object, 3: Object, 4: Object, 5: Object <div v-for="field_id in form.fields"> // Just an example, this is not what i'm actually doing // This would return undefined once I got to 6 and would show incorrect elements for the other {{ fields[field_id].html }} </div>  The numerical ID's are reset to an incremental 0,1,2,3,4,5 etc so 6 would be undefined. What's the proper way to handle this in JS/VueJS? 22 Aug 8 months ago robjbrain left a reply on Homestead TTFB > 2sec Issue .. Help Thanks for the reply @bashy Laravel debug bar says each query takes 20-60ms. The DB is just the standard MySQL database that comes with Homestead on Vagrant, with nothing done to it. The slowness also happens if I cache the queries and thus do zero queries. robjbrain left a reply on Homestead TTFB > 2sec Issue .. Help I'm replying to this old thread because it's the first one that appears on Google when searching this issue. I've tried the solutions from mabasic and followed this guide: https://websanova.com/blog/laravel/speeding-up-homestead-on-windows-using-nfs Which basically involves installing and adding the nfs type flag vagrant plugin install vagrant-winnfsd folders: - map: c:\path\to\code to: /home/vagrant/code type: nfs  But with no luck. My TTFB is regularly 2 seconds or more. It seems particularly bad via AJAX, although since it's an SPA it's pretty much all AJAX. Some artisan commands such as make:migration are very slow as well. The artisan command speeds up if I move the code directory to another area within vagrant that is not synced. However speed of Chrome connecting is still slow in that instance (so it's possible that slow artisan commands and bad TTFB are not related?) Pretty much every guide i've found says to use NFS but that doesn't appear to have helped. Is there a way to confirm whether the virtual machine it is definitely using NFS? Perhaps it's just wrongly configured still. 13 Aug 8 months ago Hi Martin yes I'm aware of that, I was trying to keep my examples simple, perhaps they were too simple. My point was that it would be better to wrap the axios logic in a class rather than repeating it everywhere. Similarly if you had a class it might know how to paginate through comments something which might happen in multiple different components. That's definitely preferable to repeating code in each component right? This is pretty basic stuff for any app whether php or JavaScript, I was just asking how different people approached it since there didn't seem to be a standard among the people I've seen using vuejs with Laravel robjbrain started a new conversation What Techniques Are People Using To Work With Eloquent Objects In VueJS? I've been going through alot of examples of using VueJS with Laravel and i'm constantly seeing things like this:  axios .post('/api/post' + this.postId, { foo: 'foo', bar: 'bar' }) .then(response => { // yay success }) .catch(error => { // oh no, an error });  And you can imagine this happening in more than one place across a site. It seems it would be far nicer to have. class Post extends Model { method save() {} }  post.save()  But all the packages and libraries i've found that try to replicate this sort of thing barely seem maintained. It definitely doesn't seem to be the norm to use one. There's also more advanced stuff like eloquent relationships. e.g: for (comment of post.comments) { // You probably want this to be a Comment class? comment.someMethod(); }  Writing all that functionality yourself could get really complicated really quickly. So I wandered what approaches people are taking to replicate their laravel models on the JS side? 08 Jun 10 months ago Hmm I seem to have gotten it working. I'll be very extensive in everything I tried incase anyone else finds this, since i'm not sure which commands where the correct way to do things and i'm not sure which exact step was the issue. Updated node/npm: sudo npm cache clean -f sudo npm install -g n sudo n stable exit vagrant provision --reload Update npm modules (included a security fix, probably unrelated) npm install npm audit fix npm update // Was told I need to update sass, this might have been a cause? npm rebuild node-sass --force // Doesn't work for me? npm run watch // Does work for me... npm run watch-poll Updated webpack.mix.js as per previous comment mix .js('resources/assets/js/app.js', 'public/js/bundle.js') .sass('resources/assets/sass/app.scss', 'public/css/bundle.css') .browserSync({ open: 'external', host: 'todo.local', proxy: 'todo.local' });  // Try in browser todo.local didn't have hot reloading // Needed to use http://todo.local:3000 I'm not sure how that works for sub routes etc, I haven't got that far yet :) Yep there's definitely some assumed setup or environment here that i'm missing http://localhost:3001 and http://localhost just return ERR_CONNECTION_REFUSED Presumably I need to setup localhost in some way to point at something? I'm just running default MacOS High Sierra. Running homestead with .local domains under /etc/hosts has been working fine for some time now. 07 Jun 10 months ago I'm following Jeffrey's Vue JS series however i'm having alot of issues getting automatic reloading going. 1. It's confusing whether to use browserSync or Hot Module Replacement, it seems like the official docs say browserSync now although Jeffrey used Hot Module Replacement in his videos. 2. I've tried both and can't get either to work. # Hot Module Replacement mix .js('resources/assets/js/app.js', 'public/js/bundle.js') .sass('resources/assets/sass/app.scss', 'public/css/bundle.css');  // Use the mix helper <script src="{{ mix('js/bundle.js') }}"></script> // Returns <script src="/js/bundle.js"></script>  npm run hot // DONE Compiled successfully in 982ms  Then I edit app.scss and app.js and nothing happens? Not only does it not reload the browser but it doesn't build new bundle.css or bundle.js files? The terminal window doesn't change at all. # browserSync mix .js('resources/assets/js/app.js', 'public/js/bundle.js') .sass('resources/assets/sass/app.scss', 'public/css/bundle.css') .browserSync({ proxy: 'todo.local' });  I also tried: .browserSync('todo.local');   DONE Compiled successfully in 2461ms 19:51:46 Asset Size Chunks Chunk Names /js/bundle.js 897 kB 0 [emitted] [big] /js/bundle /css/bundle.css 162 bytes 0, 0 [emitted] /js/bundle, /js/bundle [Browsersync] Reloading Browsers... (buffered 3 events)  It compiles once and then nothing, no reloading? I notice it also said: [Browsersync] Proxying: http://todo.local [Browsersync] Access URLs: ---------------------------------- Local: http://localhost:3000 External: http://10.0.2.15:3000 ---------------------------------- UI: http://localhost:3001 UI External: http://10.0.2.15:3001 ----------------------------------  I'm not sure if i'm meant to be doing something with these ports or something, they're not accessible via the web browser so maybe that's why it's not working? But i've found absolutely no documentation or forum posts on setting this up and it's not covered in any of Jeffrey's videos. I'm accessing the site via todo.local using laravel homstead. 19 Feb 1 year ago It seems to be, a few errors due to changes in php 7.2 but I don't think it's a homestead issue at this point. Thanks for the help! It was the same as before, although I found on another forum that you can do vagrant global-status --prune that seems to have resolved most of my issues as far as I can tell. I opened up virtual box and found one homestead-7 and deleted all files as you suggested. Now in terminal I can still see it: vagrant global-status id name provider state directory 65a464b homestead-7 virtualbox poweroff /Users/rob/Homestead and vagrant destroy 131fdfb and vagrant destroy 131fdfb --force both return an error: The machine with the name '131fdfb' was not found configured for this Vagrant environment. So now i'm in a position where I have one called "homestead-7" but I can't actually destroy it anymore? I've been fighting with Homestead all day, initially I was trying to update it due to Laravel's 5.6 updated php version, but I couldn't get the new php versions to be included. I spent way too long trying and eventually decided to try and delete everything and re-install homestead but for some reason I can't seem to do that, when it looks like it's all gone I can't vagrant up because I get the error that "A VirtualBox machine with the name 'homestead-7' already exists." It would take too long to list every single thing i've tried, but the gist of the stage i'm at now is this: First make sure everything is deleted, the folder structure has changed a few times so i've had to delete folders in a few different places. rm -rf ~/Vagrant/Homestead rm -rf ~/Homestead rm -rf ~/.homestead Now double check that there's nothing listed in vagrant global-status. Earlier in the day there where things listed so I destroyed them all manually using vagrant destroy <theid>. So now i'm at a position where vagrant global-status says there are absolutely no Vagrant environments and all the above listed directories are deleted. I then follow the instructions in the docs: 1. vagrant box add laravel/homestead 2. git clone https://github.com/laravel/homestead.git ~/Homestead 3. cd ~/Homestead 4. bash init.sh 5. Make some changes to Homestead.yaml adding a custom domain and the folder mapping. 6. vagrant up This is when I get the error: Robs-MacBook-Pro:Homestead rob$ nano Homestead.yaml Robs-MacBook-Pro:Homestead rob$vagrant up Bringing machine 'homestead-7' up with 'virtualbox' provider... ==> homestead-7: Importing base box 'laravel/homestead'... ==> homestead-7: Matching MAC address for NAT networking... ==> homestead-7: Checking if box 'laravel/homestead' is up to date... A VirtualBox machine with the name 'homestead-7' already exists. Please use another name or delete the machine with the existing name, and try again. and if I do vagrant global-status then sure enough one does exist, but it's exactly the location i'm in and exactly the box I am trying to bring up! ## id name provider state directory 4fa8fae homestead-7 virtualbox poweroff /Users/rob/Homestead I have no idea what's going at this point. I've tried 3 times to destroy that box and do the steps again but every single time the same thing happens. I can't seem to access the box that supposedly exists and I can't seem to add a new box. Can anyone help? What's the correct way to completely wipe everything and start again with homestead? 16 Jan 1 year ago robjbrain started a new conversation Why Does Casting To A Collection Happen More Than Once? This has bugged me numerous times and i've never found a satisfactory answer via Google. Why when casting an attribute on Eloquent does it cast every single time? There seems to be absolutely no point to it and what you get is something like this: $user->settings->merge(['foo'->'bar']);

// Does not contain 'foo'=>'bar' because a new collection has been created
dump($user->settings);  Is this expected behaviour for most people? I can't think of a single instance when I would want it to be casted more than once. In most of my projects I extend my own base model and create a$casts_cache variable and cache it the first time and return the cached version then after.

I just got confused for ages on a new project before realising I hadn't set that up this time around yet.

So:

1. Why has this behaviour been chosen? I'm genuinely interested because like I said I can't think of any instances when this would be preferable off the top of my head.

2. What approaches do other people take? Just accept it? Or work around it somehow?

I am replicating something like this (https://laracasts.com/lessons/managing-mass-user-settings-part-2) and figured a Settings object would be the best way and there didn't seem any point accessing via ->settings() as opposed to ->settingsor confusingly, having a collection under ->settings and the settings object under ->settings() (as would be the case in Jeffrey's example.

29 Dec
1 year ago

No mention of homestead box update at all

27 Dec
1 year ago

robjbrain left a reply on MySQL/Eloquent: Grouping By Date In Users Timezone

Actually i've just discovered if you load the timezones into mysql then you don't need to work out the offest and can just do:

// $user->timezone = 'Australia/Brisbane'$results = DB::table('social_forum_comments')
->select(DB::raw("DATE(CONVERT_TZ(created_at,'UTC','" . $user->timezone . "') as date, count(*) as count")) ->groupBy('date') ->get();$stats = collect($results)->pluck('count', 'date');  robjbrain left a reply on MySQL/Eloquent: Grouping By Date In Users Timezone Well if you're in Australia and you say I want to know to how many XXX happened on November 7th, you care about your November 7th not British, French or American November 7th right, they mean nothing to you. I'm not sure if i've misunderstood you or you've misunderstood me on that last paragraph :) Thanks for the link, that works perfectly actually, albeit not that attractive to look at. select DATE(CONVERT_TZ(created_at,'+00:00','+10:00') as date, count(*) as count from social_forum_comments group by date  In Laravel it seems like I can do this: $results = DB::table('social_forum_comments')
->select(DB::raw("DATE(CONVERT_TZ(created_at,'+00:00'," . $user->getTimezoneOffset() . ") as date, count(*) as count")) ->groupBy('date') ->get();$stats = collect($results)->pluck('count', 'date'); // And in the user class // Timezone is a user defined column on the user table //$timezone = "Australia/Brisbane"
class User {
public function getTimezoneOffset() {
return Carbon::now()->setTimezone($this->timezone)->format('P'); } }  I'm not sure if that's actually the best way to do it, it's certainly not the most 'eloquent' but it works. I couldn't figure out a better function for getting the offset and there's probably no need to use Carbon instead of just DateTime but i'm just used to using Carbon by default now. 26 Dec 1 year ago robjbrain started a new conversation MySQL/Eloquent: Grouping By Date In Users Timezone This may be able to be answered simply as a MySQL rather than a Laravel specific answer, although of course I am using Laravel and Eloquent so if there's a method within Laravel\Eloquent to do this that would be awesome. My database is in UTC. I want to get a count of how many comments where posted each day so show on a graph, so I do something like this: select DATE(created_at) as date, count(*) as count from social_forum_comments group by date  Very simple, this works perfectly for me. However, if someone is in Australia, the counts won't accurately reflect a day in THEIR timezone, but a day in UTC. I'll try and re-iterate: What I want is the count between these dates: "2017-11-05 00:00:00" and "2017-11-05 23:59:59" in the users local timezone. With the above query if an Australian is on the site, it will be showing a count from "2017-11-05 10:00:00" and "2017-11-06 09:59:59" (where the users timezone is UTC +10) If it was just one query that may be easier to do, but since I want it grouped by day and showing a whole month (for a graph) i'm not sure how that would be possible? Is there a way to do this via Eloquent? perhaps setting the timezone on connection or something like that? 18 Sep 1 year ago @Indemnity83 i've tried to do the same however flysystem V2 requires aws/aws-sdk-php ~2.7 and V3 requires ^3.0.0 so the two are not compatible (you could not use dream and aws together in the same app for instance). Did you find a way around this or just not encounter it? 29 Aug 1 year ago I know this is a year old now but i've having the exact same problem, did you manage to resolve this? @robs 27 Jun 1 year ago Are you suggesting something like this: class Team { public function setPlayersTeam() {$this->players->each(function ($player) use ($team) {
$player->team =$team;
});
}
}

$team = Team::with('players')->find(1);$team->setPlayersTeam();

@foreach($team->players as$player)
//etc
@endforeach


That way you'd have to do it every single you were going to use the players, and imagine a situation like this:

class Team {
public function setPlayersTeam() {
$this->players->each(function ($player) use ($team) {$player->team = $team; }); } public function setCoachesTeam() {$this->coaches->each(function ($coach) use ($team) {
$coach->team =$team;
});
}

public function setScoutsTeam() {
$this->scouts->each(function ($scout) use ($team) {$scout->team = $team; }); } public function setPhysiosTeam() {$this->physios->each(function ($physio) use ($team) {
$physio->team =$team;
});
}
}

$team = Team::with(['players','coaches','scouts','physios'])->find(1);$team->setPlayersTeam();
@foreach($team->players as$player)
//etc
@endforeach

$team->setCoachesTeam(); @foreach($team->coaches as $coach) //etc @endforeach$team->setPhysiosTeam();
@foreach($team->scouts as$scout)
//etc
@endforeach

$team->setScoutsTeam(); @foreach($team->physios as $physio) //etc @endforeach  That's alot of code which is why I suggested it might be better to make the parent model accessible from the child model and asked whether other people had attempted it? It's difficult to give an example without actually putting in all the hours to build something because the code behind the eager loading in Laravel is quite complex (hence why I asked if anyone else had), but imagine something like this: class Model { public function loadRelations($model) {
// Do existing stuff and then
foreach($relations as$relation) {
$relation->setParent($model, $model->getClassName()); } } } class Player { public function team() { // Check if is the parent if ($this->hasParent($relationship)) { return$this->getParent($relationship); } // Nope then just behave normally return$this->getRelationshipNormally();
}
}


Complete pseudo code that doesn't work obviously, just as an example.

This way all the magic would happen automatically irrespective of relationship types or adding extra code into the controllers or wherever that each() was meant to happen.

This may work for the given example, but isn't a more general solution. Imagine doing this every time you got the team. Or what if you wanted to change the URL to include nation or league which might involve $player->team->league->nation->name you'd have to go through and find every instance where you got the team and change it to add leagues and nations. It may not even be a URL, it might be a table with multiple columns where you want to list the players team, league and nation amongst other things. I wasn't trying to get a solution to the exact example I was trying to discuss the +1 problem in general and figured an example would be a good start. Sorry if that was confusing. Perhaps +1 isn't the right term. More just duplicate queries, when you already have the team. I was trying to find out if anyone had extended eloquent to allow children to access parent objects such as the player object knowing it was set on a team object. 26 Jun 1 year ago robjbrain started a new conversation Has Anyone Found A Good Solution To This +1 Problem In Laravel/Eloquent? (getting Parent Model) I regularly encounter this +1 problem in Eloquent and wandered if anyone had come up with a smart solution to it. // Get a team and all its players$team = Team::with('players')->find(1);

// List the team and all its players
<h2>{{ $team->name }}</h2> @foreach($team->players as $player) <a href="{{$player->url }}">{{ $player->name }}</a> @endforeach  This looks simple enough right, however what if the url looks like this: domain.com/team-name/player-name In order to build the url we'll probably have a method like this: public function getUrlAttribute() { return URL::to($player->team->name . '/' . $player->name); }  However now what happens is that every time we want to list the players we also have to load the team again in order for it to be accessible to the$player model. This creates a +1 problem.

$team = Team::with('players.team')->find(1);  But that seems pointless? We could also do something like this: $player->url($team)  But that assumes we always have the$team, which might not always be true, it's also a bit messier.

I was thinking a better way might be to set the inverse relationship wherever possible when you eager load a model. However this is problematic, since you might only load some of a relationship, not all of it.

Another option might be to set some sort of "parents" array when eager loading a model, so when we do $player->team we see if $team is set within the parents array first before trying to load it.

All of these have complications though, not least with the variety of different relationships a model might have.

Has anyone sought to handle this situation? I'd be interested in your solutions or just for a good discussion :)

09 Mar
2 years ago

robjbrain left a reply on Who Designed The Laracasts Website?

Thanks for the link, do you happen to know if he used a css framework? Looking through the classes I don't recognise them, but it seems strange to roll your own grid system these days

robjbrain started a new conversation Who Designed The Laracasts Website?

Hi, I really like the latest look of Laracasts (i've been away a little while so i'm not sure how new it is).

There's no info in the footer or anything, can I ask who made the design? Or was it Jeffrey himself?

06 Jul
2 years ago

Seems like it may have been a Digital Ocean issue

Thanks for the reply, how would I go about using a different mirror?

I'm trying to use Forge because I don't really know how to do this myself :)

robjbrain started a new conversation Manual Forge Installation On VPS: Failed To Fetch Libmcrypt4_2.5.8-3.1ubuntu1_amd64.deb

I'm trying to use the provided ssh file to manually setup forge on a VPS. But I keep getting stuck at this line:

apt-get install -y --force-yes build-essential curl fail2ban gcc git libmcrypt4 libpcre3-dev \

Which throws this error:

Failed to fetch http://mirrors.digitalocean.com/ubuntu/pool/universe/libm/libmcrypt/libmcrypt4_2.5.8-3.1ubuntu1_amd64.deb 403 Forbidden [IP: 95.85.0.50 80]

Googling hasn't turned up an obvious issue.

I've attempted to use

apt-get update and --fix-missing

but the error persists.

I haven't attempted to get any further than this, since presumably i'll hit problems eventually without mcrypt

There are various other things I don't understand about this manual installation file, but for now this is my stumbling block.

Any suggestions?

09 May
2 years ago

robjbrain started a new conversation Edit Php-fpm Settings In Laravel Forge

Is it possible to modify the php-fpm config through forge? I can find nginx, php and a blank "environment" option for editing files. But nothing for php-fpm (unless it is this environment option)?

Is it possible to do through forge or do you just have to go through the terminal and use vi like normal?

24 Nov
3 years ago

Also in regards 3, the name of the file in the build directory is going to change everytime, so you'll have to remember to keep committing that file.

At the moment i've opted to avoid elixer versioning and just use

echo $file.'?cachetime='.filemtime($file)

Using filemtime twice for the minified css and js,doesn't seem like a big hit compared to using file_get_contents() once to get rev-manifest.json.

Still generally bemused by incorporating elixer in general though, can't help but feel i'm missing something blindly obvious, certainly seems less intuitive than the rest of Laravel.

1. Not massively keen on this, causes obvious problems if ever moving things around

2. Yeah that's fair not that big a deal

3. Not ideal like you say. Interested to know if there's a better 'standard' practice out there.

20 Nov
3 years ago

robjbrain started a new conversation First Time With Elixir, Still Confused About Relative Paths And Updating In Dev/pushing To Live

So i've watched the tutorial videos on Elixir and got it working okay. But there are still three issues i'm having.

1. When you version files they are placed in the "build" directory, but the images aren't in there. Haven't found much on google beyond one reference to using gulp to copy across all the images to the build directory, essentially duplicated them. This isn't mentioned in the docs or in the videos and seems a bit excessive. Is duplicating all your images genuinely the right way?

2. When editing the dev site, what's the best practice for recompiling your less and js. In the past i've used phpstorm with a filewatcher which recreates the css file everytime I edit a less file, this is great and I don't think twice about it. Now it seems I have to constantly have a terminal window open running "gulp watch" and remember to open that everytime I boot up the vm. Not that much more work, but wanted to check that this is genuinely the right way?

3. When pushing live what do I want to push? Just the resources/assets directory and then run gulp? And asking git to ignore the build directory? If my views reference a file that isn't in "rev-manifest.json" the site is going to show an error while it's compiling right? At the moment the gulp task is taking about 30 seconds, so for 30 seconds my entire site is going to crash out and log errors? What's the alternative? Take the site down for 1 minute just to recompile the less and js? This doesn't make sense either. What's the right way to update the css and js when doing a git pull?

Essentially on all 3 questions it seems there is a kind of obvious solution, but none of them sit right with me and have me screaming out for a better way, but I can't find one in Jeffrey's tutorials or on Google.

Any suggestions would be much appreciated.

10 Nov
3 years ago

robjbrain started a new conversation Text Losing Whitespace Between MySQL And Textarea

I have a textarea that a user can fill in, much like the textarea on this forum. When I try to repopulate that textarea from the database for editing, multiple new lines are lost.

The database shows this:

[b]some text[/b]\r\n A: More text\r\n \r\n [b]other text[/b]\r\n A: More other text\r\n

When I put it back in a textarea input it still has new lines, but double new lines are lost:

[b]some text[/b] A: More text [b]other text[/b] A: More other text

I have tried this without using the blade escape syntax (just a plain echo) with the same result.

Infact I can't tell when it is losing the whitepace at all. Here are some examples of when I can see the string having multiple whitespace and when I can't.

dd($model); // This shows with whitespace (/r/n) in both the attributes and originals array  dd($model->column);
// This shows the multiple new lines \r\n

var_dump($model->column); // This shows no new lines  return$model->column;
// simple return from the controller removes multiple white lines

return Response::make($model->column); // again just outputting the plain string, shows multiple white lines removed  <textarea>{!!$model->column !!}</textarea>
// of course the actual problem in a blade file, no extra spaces between lines are displayed in the textarea


What's more confusing is that in vagrant the whitelines are retained just fine, only on my centos server are they lost. The code is identical which made me think it might be a mysql/php/server setting, but then dd() on the model shows the correct whitespace so it's obviously coming out of the database just fine, something is happening to the string when it's echo'd or var_dump'd (i'm not sure what dd() uses I assumed it was var_dump, perhaps not).

It does seem to be related to the database in some way though, because a form with a validation error repopulates the textarea just fine with the multiple new lines. It's only when repopulating the textarea from the database that a problem occurs.

Every result i've found trying to google this error references using nl2br, which obviously isn't helpful in this instance. I'm not trying to display the text in html, i'm trying to let a user submit a form using the textarea and then refill that textarea to let them edit the data they've submitted later on. So to be very clear, nl2br is not a solution in this instance.

27 Oct
3 years ago

Sorry for the delayed reply, it seems I stopped getting email notifications for some reason.

It seems the recommended solution is to set timezone manually each you want to display a date?

Obviously this is time consuming so we want a helper function such as:

Time Published: {{ show_date($article->time_published, 'd-m-Y H:i:s') }} show_date($date, $format) { return$date->setTimezone(Auth::user()->timezone)->format($format); }  Or even better to handle all possibilities: show_date($date, $format) { if(!($date instanceof Carbon)) {
if(is_numeric($date)) { // Assume Timestamp$date = Carbon::createFromTimestamp($date); } else {$date = Carbon::parse($date); } } return$date->setTimezone(Auth::user()->timezone)->format($format); }  Is that generally the best implementation then? Possibly a blade syntax such as @date() might be better, but I haven't had the time to look into extending blade yet. 23 Oct 3 years ago I don't understand what you mean? It says on the second line the users timezone is stored in the database. Any other storing of dates would be things like comment->time_added so i'm not sure what you're suggesting to store in a field in the database? If you do mean store the users timezone in the users table, as I am doing, then the answer "store it in the database and use that" is literally just a rephrasing of my question which is "I have the users timezone stored, how do I use it", but not actually an instructive answer. I'm not sure if i've misunderstood you or if you're reply has no relevance because as you said you didn't actually read my post. Either way i'm confused by your reply. robjbrain started a new conversation Eloquent Carbon And Displaying Dates In A Users Local Timezone I want to be able to display dates in the users local timezone, so if someone submits a comment in the UK at 2pm someone viewing that comment in Italy will see the time showing as 3pm. If the Italian user then submitted a reply 5 minutes later it would show as 3.05pm for him and 2.05pm for the user in the UK... fairly elementary. I have the users timezone saved in the database accessible via Auth::user()->timezone In the past I always saved dates as integer timestamps in the database and used date_default_timezone_set() when getting the user object and then date(d-m-Y H:i:s,$model->timestamp) would display in the users local timezone.

But now that i've tried to follow Laravel "standard" practice, use carbon and save as timestamps in the DB, I can't figure out how to get the date displaying relative to the users local timezone.

So lets say I have a model with the timestamp saved in the database like this: "2015-10-17 13:56:26"

I am using date mutators in Eloquent so this column will be converted to a carbon instance.

Now if I use:

date_default_timezone_set(Auth::user()->timezone);

\$model->timestamp->format('d-m-Y H:i:s')

It will always display the exact same date, exactly what it says in the database, no matter what was set in the timezone.

But it does have an effect when saving dates e.g.

Model::create(array(['timestamp'=>Carbon::now()]);

This will save the date in the database itself as 3pm for the Italian and 2pm for the guy in the UK, even when they're both saving at the exact same time. This is exactly the opposite of what I wanted!!!! If I did this I would be saving dates in the database in all kinds of different timezones, horrendous, I definitely want to avoid that.

I've given a bit of detail in the hope someone will see my current train of thought and tell me why i'm being an idiot, but the question is simple:

Using Eloquent Date Mutators and Carbon, how can I save all dates in the database in Europe/London time, but whenever i'm displaying dates use a custom timezone set in the Users model?

05 Oct
3 years ago

3. vboxmanage list runningvms
5. vboxmanage controlvm homestead keyboardputscancode 1c