Cocoon

Cocoon

Member Since 5 Years Ago

Dresden, Germany

at Self-Employed

Experience Points 24,925
Experience Level 5

75 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
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 377
Lessons
Completed
Best Reply Awards 27
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

13 Jun
4 years ago

Cocoon left a reply on Please Tell Me The Logic For Particular Code

There is a limited number of possible results and each of these results has the same symbol. They change randomly to make this less obvious.

12 Jun
4 years ago

Cocoon left a reply on Built-in Method To Check Weather Parent Owns An Instance Of Child

The contains method would also work, but pmall's solution if more performant.

public function hasSubItem (SubItem $sub)
{
    return $this->subitems->contains($sub);
}

Cocoon left a reply on Where To Put Methods That Structure Json

You could just create a new class (ItemTransformer) and return the result of this in a JsonResponse.

return new JsonResponse(new ItemTransformer($item)->formatX());

You could also have a look at the Fractal package, which streamlines this process even further.

11 Jun
4 years ago

Cocoon left a reply on Saving A Slug

Additionally to what the others have said, I wouldn't do this kind of stuff in my controller and have to worry about updating the slug each time the Content model gets saved. Rather use model events and put that logic into your model.

class Content extends Eloquent {

    public static function boot()
    {
        parent::boot();
        
        static::saving(function ($content) {
            $content->slug = Str::slug($content->title);
        }
    }
}
21 Mar
4 years ago

Cocoon left a reply on Javascript Education Sites Like Laracasts

Yeah, egghead.io or watchmecode.net.

16 Feb
4 years ago

Cocoon left a reply on What Is The Best Way To Check Users Role? ( IsAdmin )

I think the best place is to store it in the user model.

public function hasRole($name)
{
    foreach ($this->roles as $role)
    {
        if ($role->name == $name) return true;
    }

    return false;
}

Then you can simply check for:

if( $user->hasRole('admin') )
{
    // ....
}

Or wrap it in its own function

public function isAdmin()
{
    return $this->hasRole('admin');
}
// $user->isAdmin();

Cocoon left a reply on L5 - Check If User Has Activated Account By Email

I think doing it in the validator is fine. The only problem might be if the is_activated field gets set back to false (maybe ban the user?). Then the user could stay logged in as long as the cookie is set. In that case a middleware might be better.

Cocoon left a reply on How Can I Achieve A "reverse Morph Relation"?

I don't like the database structure that the Eloquent's morph functionality forces and I am trying to do it "the opposite way".

I don't think Eloquent has a built-in mechanism for achieving this.

Any specific reason why you don't want to use polymorphic relationships? This is exactly when you would use it.

Cocoon left a reply on Why Have Database.php Config When You Are Using A .env File?

The .env file is not only a place that holds your database settings. You can store any kind of secret keys that you don't want to share publically (git). Your team members can also have their own .env file to specify their local settings (e.g. different db).

15 Feb
4 years ago

Cocoon left a reply on Request Ajax Not Detected

Sorry, but I am not sure what the problem is in your case. If you want an example, Jeffrey has a lesson here on Laracasts that deals with this exact topic: AJAX, jQuery and Laravel.

https://laracasts.com/lessons/javascript-conveniences

Hope it helps!

Cocoon left a reply on Lists() For Eager Loaded Data?

Will where('modulename', '=', $model) always return one result?

If so, you can do:

$module = Module::where('modulename', '=', $model)->with('imagecategories')->first();
$ids = $module->imagecategories->lists('id');

Otherwise do this:

$modules = Module::where('modulename', '=', $model)->with('imagecategories')->get();
    
$ids = $modules->map(function($module) {
    return $module->imagecategories->lists('id');
});

$ids = array_flatten($ids) // if necessary wrap with array_unique()

Cocoon left a reply on Request Ajax Not Detected

Hmm, so adding the line of code to your script didn't help? But you can see that a new request was made and the response is 'no'? (Chrome Dev Tools > Network)

The strange thing is that jQuery includes the necessary header content by default.

Cocoon left a reply on Request Ajax Not Detected

Laravel will check this condition to determine if it is an AJAX request.

return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');

If it always returns 'no' than I assume that the headers are not correct. Can you check in Chrome Dev Tools if the headers for this requests include X-Requested-With: XMLHttpRequest?

If it is not set, maybe try to add it to your script:

$.ajax({
    headers: { 'X-Requested-With': 'XMLHttpRequest' }
});

Cocoon left a reply on [Laravel 5] Modify Input Before Validation

@sdebacker Yes, it has been removed (it had been renamed to sanitize before).

It seems like Taylor tried to extend this feature, but finally removed it before releasing Laravel 5. Have a look at GitHub. Someone posted a solution there, but I am not sure if it will work.

https://github.com/laravel/framework/commit/924a7fcf21bbba4f4efc8e367f456cea5e4d25c1

13 Feb
4 years ago

Cocoon left a reply on Homestead DB Connection Problem

I stumbled upon this thread while looking for a solution for the same problem and finally added the following line to my database.php file, which solved the problem:

'mysql' => [
            // ...
            'host' => env('DB_HOST', 'localhost') . ('homestead' == gethostname() ? null : ':33060'),
            // ...
        ],
08 Feb
4 years ago

Cocoon left a reply on DD Laravel 5

Yeah, this has also bugged me recently. Maybe someone knows how to solve this?

Edit: I now also use Laravel Debugbar, which is pretty fantastic.

Instead of doing a dd() you can do the following:

Debugbar::info($this->user->findById(1));

It's easy to use and very helpful for working with Ajax calls.

02 Jan
4 years ago

Cocoon left a reply on Querying Models With Contains

I think you could either create a PostPresenter. There is a lesson here on Laracasts:

https://laracasts.com/lessons/view-presenters-from-scratch

Or you could create your own LikeCollection and have a specific method that will hold the logic for checking if a user is the owner of one of these likes. Then in your view you could have a method like so:

$post->likes->hasUser(Auth::user())

http://laravel.com/docs/4.2/eloquent#collections

22 Dec
4 years ago

Cocoon left a reply on Any Way To Achieve "belongsToManyThrough"?

You could eager load the permissions like so:

public function hasPermission(UserPermission $permission) 
{
    $roles = $this->roles;
    $roles->load('permissions');
    // or I guess this would also work:
    // $roles = $this->roles()->with('permissions')->get();

    $roles->each(function($role)
    {
        if($role->permissions->contains($permission))
        {
            return true;
        }
    }); 

    return false;
}
05 Dec
4 years ago

Cocoon left a reply on [L5] Date_default_timezone Error On Clear-compiled

It's the same for me: "~5.0".

Sorry, I also didn't understand what the issue was, but I can only report that following the latest 5 commits from https://github.com/laravel/laravel/commits/develop solved the issue for me.

I still have the same problem as reported here: https://laracasts.com/discuss/channels/general-discussion/l5-latest-commit-breaks-if-using-waygenerators-or-image-internvention

So I removed the packages and will wait for it to be fixed.

Cocoon left a reply on [L5] Date_default_timezone Error On Clear-compiled

Hmm, had the same problems, but I followed the latest commits and now it is working again. Not sure what was causing the problem, but deleting the 'local/app.php' was one of the changes.

25 Nov
4 years ago

Cocoon left a reply on What Data Type To Use In Eloquent For Price

I just read a long article that you should never use floats for money

I would be interested to read this article. Can you share it?

For an app I have used decimal as the data type. Haven't had any problems, but maybe I am doing it wrong...

04 Nov
4 years ago

Cocoon left a reply on [Help] When To Create A User Profile

For my project I have a UserObserver class.

class UserObserver {

    public function created($user)
    {
        $profile = new Profile();
        $user->profile()->save($profile);
    }

}

You can register the observer in the user model

class User extends Model {

    public static function boot()
    {
        parent::boot();

        self::observe(new UserObserver);
    }
}

If you don't need an extra class, you can simply put the event in the boot method.

class User extends Model {

    public static function boot()
    {
        parent::boot();

        self::created(function($user)
        {
            $profile = new Profile();
            $user->profile()->save($profile);
        });
    }
}

http://laravel.com/docs/4.2/eloquent#model-events

Hope that it will help you.

Cocoon left a reply on Where Are You All From?

Dresden, Germany

Cocoon left a reply on [Help] When To Create A User Profile

I usually add a model event that creates a profile whenever a user is created and that associates the new profile with the user.

29 Oct
4 years ago

Cocoon left a reply on Cool Landing Page For Laracasts

Looks very good!

25 Oct
4 years ago

Cocoon left a reply on Controllers With Role Constraints

It looks alright to me. I guess you haven't set the fillable fields on the UserRole model?

Personally, I prefer to keep related models in one seed file.

$me = User::create([
    'first_name' => 'My first name',
    'last_name' => 'My last name',
    'email_address' => 'myemail@gmail.com',
    'password' => Hash::make('secret'),
]);

// I think Jeffrey created an method called assignRole() in the video
$me->assignRole(1);

// then for each User I assign them a role in the foreach loop
$user->assignRole($faker->randomElement($roleIds));

I think for things like this it is easier to keep it all in one seed file.

24 Oct
4 years ago

Cocoon left a reply on File Uploads

Hmm, not sure, but shouldn't the destination path just be like so:

$destinationPath = public_path(). '/upload/' .Input::get('folder');
// leave off . $file?

Cocoon left a reply on Eager Load Relationship For Authenticated User

@theshiftexchange It will be only one query because you call the count method of the collection.

22 Oct
4 years ago

Cocoon left a reply on CMS

Yeah, it is still alpha. You can create menus, but blog tags don't seem to be included yet. It definitely still takes time, before it is useable.

Cocoon left a reply on CMS

@keevitaja No, I haven't worked with OctoberCMS yet, but wanted to give it a try when I have the next more traditional 'content-heavy' project. I have to say that I often do multilingual websites and therefore need support for that, which OctoberCMS offers. So far I just watched a couple of videos from there website and I think it looks good.

In the past I often used Contao, but that feels dated now. Haven't done anything with Wordpress in years. Actually, I am looking for a good CMS that offers lots of flexibility.

http://www.pagekit.com/ (uses Symfony) looks also pretty good, but mulitlingual support is not included at the moment. I might give it a try when this feature becomes available (exp. Mid-2015).

Cocoon left a reply on CMS

I think October CMS looks very promising. It's build with Laravel 4 and it seems to be easy to extend. They also have a cool feature to easily implement AJAX. Have a look here:

https://octobercms.com

19 Oct
4 years ago

Cocoon left a reply on Podcasts For Web Developers

Thank you guys!

18 Oct
4 years ago

Cocoon left a reply on Laracasts Utilities Issues On Method Put Not Found

Not sure about the message in phpstorm, as I have only used it once. But I remember that it gave me this messages, too. As you reference a Facade this class won't have a put method, so the message shouldn't be that important. Laravel doesn't give you any error if you leave off use?

In the console, do you type Laracasts.firstname?

Cocoon left a reply on Laracasts Utilities Issues On Method Put Not Found

Okay, you are using Laravel 4? Then you don't have to use use at all in your controller. If you leave it off, you don't get any errors, do you?

Have you published the config file? By default, the variables are bound to the hello.php view. If you want to use another view, you can specify this in the config file. As described at Github, its best to bind them to a footer partial.

Cocoon left a reply on Laracasts Utilities Issues On Method Put Not Found

I think you just have to import it like so

use JavaScript;

Looking at the explanation that Jeff provided, I was wondering why he didn't include a line of code to set an alias, but he loads the alias in the boot method of the ServiceProvider:

AliasLoader::getInstance()->alias( 
    'JavaScript',
    'Laracasts\Utilities\JavaScript\Facades\JavaScript'
);

Didn't know that this was possible.

Cocoon started a new conversation Podcasts For Web Developers

From time to time, I like to listen to podcasts while coding or doing the dishes and I found the Laravel.io podcast to be very informative and entertaining.

Maybe you guys have some tips for other good podcasts related to PHP / Web Development?

17 Oct
4 years ago

Cocoon left a reply on Composer Update Error

No, I think the file is now permanently renamed. This means you will have to follow the commits on Github and update your files manually. For this fix you can do what @aliqsyed suggested.

Cocoon left a reply on How To Overwrite Link_to_route In Laravel 4?

I wouldn't overwrite link_to_route, but rather create my own helper function. All link_to_route does is this:

function link_to_route($name, $title = null, $parameters = array(), $attributes = array())
{
    return app('html')->linkRoute($name, $title, $parameters, $attributes);
}

So you could easily use this function and modify it to your needs.

Cocoon left a reply on Composer Update Error

Yeah, Laravel 5 is still in alpha (or beta?), so expect to see more of these changes. It should become stable in a month or so.

Cocoon left a reply on Start With Laravel 5?

Just be aware that Laravel 5 is currently pretty unstable. Any composer update can lead to your app being broken and you will have to follow the recent commits at Github to fix the issues. If it is an urgent project and for a client I would stick to Laravel 4.2, just to be safe.

16 Oct
4 years ago
15 Oct
4 years ago

Cocoon left a reply on Ordering By Related Model

You could use something along these lines:

$listings = Listing::with('comments')->get();

$listings = $listings->sortBy(function($listing)
{
    if( ! $listings->comments->isEmpty() )
    {
        return $listing->comments->sortByDesc('created_at')->first()->created_at;
    }
    return ???;
}

Depends on what you want to do if there are no comments. You could also create a filter, so that you only sort these listings that have comments.

Update

Another idea would be to touch the timestamp of the listing everytime a comment was published. Then you don't need the comments and you could just sort by the updated_at field.

Cocoon left a reply on L5: After Update No Controllers Are Found

Ahh, I should have read more carefully. Then yeah, should be fixed soon.

Cocoon left a reply on L5: After Update No Controllers Are Found

I think this is the new default. Controllers will now be only plain old php objects. This means they won't extend any BaseController or Controller.

You can still access the Controller by namespacing it or you could define an alias and everything should be as usual.

  // app.php

  'Controller' => 'Illuminate\Routing\Controller',

Cocoon left a reply on CSRF Token Middleware Issue

Has it updated the CsrfMiddleware in your app? It should look like so now:

https://github.com/laravel/laravel/blob/develop/app/Http/Middleware/CsrfMiddleware.php

This will avoid throwing a TokenMismatchException on GET routes.

Cocoon left a reply on How To Bind Requested Models With Route Annotation?

I think it is not different. @Resource should set up the same routes as doing $router->resource() in routes.php. Check if that is that case by doing php artisan route:list. You should see the routes with a wildcard of categories.

Prefixing the resource should work like so:

/**
 * @Resource("categories")
 * @Controller(prefix="admin")
 */

Cocoon left a reply on How Get Current Route In Middleware?

Your explanations are very helpful. It's a new concept in Laravel 5 and we all have to get used to it. I think I pretty much understand it now, but I am not sure what happens inbetween processing the stack and then processing the middleware and why we can't have access to the route when processing the stack.

Update: Of coure, the explanation can also be found in the AppServiceProvider.

 /**
  * Build the application stack based on the provider properties.
  *
  * @return void
  */
 public function stack()
 {
  $this->app->stack(function(Stack $stack, Router $router)
  {
   return $stack
    ->middleware($this->stack)->then(function($request) use ($router)
    {
     return $router->dispatch($request);
    });
   });
 }