t0ne

Experience

10,445

1 Best Reply Awards

  • Member Since 3 Years Ago
  • 129 Lessons Completed
  • 18 Favorites

18th September, 2018

t0ne left a reply on Need Advice About Model Relations • 3 days ago

@martinbean thanks a lot, exactly what I need!

17th September, 2018

t0ne started a new conversation Need Advice About Model Relations • 4 days ago

I need some about the following setup:

a 'User' can work for many 'Department'

For each 'Department' a 'User' has a 'Profile'

user hasMany department (manyToMany) user hasMany profile (oneToMany)

profile belongsTo 1 department AND belongsTo 1 user

department hasMany user (manyToMany) department hasMany profile (manyToMany)

so i could solve it like this:

table structure:

users

  • id

departments

  • id

user_department

  • department_id
  • user_id

profiles

  • id
  • user_id
  • department_id

Is there a better way to solve this? i feels like 'Department' should be polymorph: it can be used for 'users' and 'profiles'.

so instead of:

profiles

  • id
  • user_id
  • department_id

should i use something like this:

profiles

  • id

user_profile

  • user_id
  • department_id
  • profile_id

OR

departmentable (?) (polymorph)

  • department_id
  • departmentable_id
  • type (morph User / Department / Future Model )

20th September, 2017

t0ne left a reply on Need Some Advice On What's Best Solution To Implement Import Class For All Models • 1 year ago

@Parasoul thanks for your reply! Yes all tasks methods apply for all models

@martinbean i want to import data from an excel file to a database table, for example:

  • import 'companies' from excel to the 'companies' table
  • import 'employees' from excel to the 'employees' table
  • import 'whatever' from excel to the 'whatever' table

I want to 'extend/provide' future models with this Import functionality. so i want to get acces to my model from the Import class

For example the analyze method from Import class:


//returns json
//{
//  newRecords:{
//      amount, etc
//  },
//  updatedRecords:{},
//  deletedRecords:{}
//}
//compare excelDataCollection with modelCollection
function analyze(){
    
    $modelCollection = $this->model->all(); //!!?   
    
    $comparison =  new CompareSourceDataWithTargetData($excelCollection,'$modelCollection');    
    //  
    return $comparison->result();
}

'CompanyModelController','CompanyModelController', or 'WhateverModelController'

    function analyzeImportFile(){
        $this->import->analyze();
    }

hope this makes sense;)

19th September, 2017

t0ne started a new conversation Need Some Advice On What's Best Solution To Implement Import Class For All Models • 1 year ago

I want to create a Import class which provides functionality which i can use in all of my controllers.

I came up with some ideas, but I haven't figured it out yet. I might overcomplicate things and looking for the best solution

Option 1.

Import class

class Import{
    
    __construct(Model $model){
        //created in ModelController’s constructor:
        $this->model = $model; 
    }
    
    //get table name used by model
    
    //GOAL: access to model 
    function getTableName(){
        return $this->model->table; //or any other property
    }

    //tasks methods
    function validateRequest(){}
    
    function analyze(){}
    
    function synchronize(){}    

    function getSummary()

}

ModelController: (could be any controller)

use Import;

class ModelController extends Controller {
    __construct(){
        $this->import = new Import(Model $model); //'need model in import class!' use repository?
    }
    
    //GOAL: access to import object
    function analyzeImportFile(){
        $this->import->analyze();
    }
}

Option 2.

abstract Import class

abstract class Import extends Model{
    protected $table;

    __construct(){
        
    }

    abstract function getTableNameValue();  //contract 
    abstract function getPropertyValue();       //contract 

    //GOAL: access to model 
    function getTableName(){
        return $this->getModelTableName()   // exists in child class by contract;
    }

    //import tasks methods
    function analyzeImportFile(){}
}

Model

SomeModel extends Import{
    protected $table = ‘some_table_name’;
    
    private $property = ‘value’;
    
    //don’t want to put stuff in model..    
    //by contract…
    function getTableNameValue(){
        return $this->table;
    }
    
    function getPropertyValue(){
        return $this->property
    }
}

Controller

class ModelController extends Controller {
    __construct(){

    }
    
    //GOAL: access to import object
    function analyzeImportFile(SomeModel $someModel){
        $someModel->analyzeImportFile();
    }
}

Option 3.

The right way..

Option 2 seems not right, Option 1 works fine, but it seems it could be better (should i refactor to repository pattern?)

Or should i take another approach?

i would really appreciate your advice and hope someone can point me in the right direction.

thanks in advance!

25th August, 2017

t0ne left a reply on Just Launched My Spark App: ZoneWatcher • 1 year ago

Thanks your reply, so spark is sufficient for this type of app?

t0ne left a reply on Just Launched My Spark App: ZoneWatcher • 1 year ago

Hi @tomschlick,

Saw your laraconus 2017 speech, very helpful!

I hope you will help me understand the following; How does your spark app relates to multi-tenancy? Spark teams can not be used as tenants, am i right?

Thanks in advance!

8th March, 2017

t0ne left a reply on Laravel-mix With Modules Or Packages • 1 year ago

I would also like to know...

23rd June, 2016

t0ne started a new conversation Valet Returns 404 On Tinymce.gzip.php • 2 years ago

Valet returns 404 on tinymce.gzip.php, the file is there but i guess it won't accept "gzip.php". Need some advice, thanks in advance!

4th June, 2016

t0ne started a new conversation Multiple Project Share Same Files. (git?) • 2 years ago

I've made a project, which includes a cms and client specific website. Now i want to create another project for another client: (the same) cms + client specific website. What is the best way to keep the cms code in sync, so that all my projects use the same version of the cms.

Should i use git for this? if so, what is the best setup.

hope it makes sense

2nd June, 2016

t0ne left a reply on What Is The Purpose Of Intervention ImageCache? • 2 years ago

Thanks for reply!

Example: when i upload an image from my cms i also create a thumbnail and use to create a list of images. /images/thumbnail/image.jpg

Or is better to just upload an image and when want to create a list of images, use imagecache, for example /imagecache/small/image.jpg

t0ne left a reply on What Is The Purpose Of Intervention ImageCache? • 2 years ago

Well.. I can see how to use it but i don't understand when to use it.

Can i upload an original image and use imagecache in my website to receive to right format or should i create and store different formats/sizes in the backend and call these images in my website.

t0ne started a new conversation What Is The Purpose Of Intervention ImageCache? • 2 years ago

What is the purpose of Intervention ImageCache? Why and when should i use it? When i upload an image i create and store multiple images with their own size, like small, medium, large and use them in my views. thanks in advance!

9th May, 2016

t0ne left a reply on Pattern For Media Library • 2 years ago

thanks for your time, much appreciated.

do you mean this topic: https://laracasts.com/discuss/channels/general-discussion/are-50-controllers-a-sign-of-code-smell

t0ne left a reply on Pattern For Media Library • 2 years ago

ah oke, it's mess indeed.

Just to be sure: every mediable type has it's own controller for updating and storing etc.

And if i really wanted to: in the MediaController i can make method which returns "one big list of media objects" only for this reason i have make use of polymorphic relation?

t0ne left a reply on Pattern For Media Library • 2 years ago

thanks again! why all this? good question, i try all this to learn about polymorphic... maybe not the best use case.

In this case i have my MediaController with an update() method which contains: "$media->mediable()->update($request->all());"

When update my Video or Image or File object, i can sent this request in all of these cases to MediaController->update().

This won't work inserting a Video,Image or File object, in this case need something like Video->media()->store().

And so i ask myself why am i doing all this. I already have it up and running with regular relations.

That's why this post is called "best pattern for media library", is polymorphic the right solution for this case?

6th May, 2016

t0ne left a reply on Pattern For Media Library • 2 years ago

When trying to update mediable types, i found one of the benefits of polymorphic relations i guess, Am i right?

class MediaController extends Controller{
    
    //one method which can update all the mediable types,
    public function update(Request $request, $id){
        $media = Media::find($id);
        $media->update($request->all());
        
        //updates mediable types (Image, Video etc)
        $media->mediable()->update($request->all());    //!!!!  
    }

}

t0ne left a reply on Pattern For Media Library • 2 years ago

@pmall thanks for your reply, now i know on the right track.

Another question: Instead of creating list of all mediable types as above, i need a list of a specific type: how should i do this? This is what i have so far:

get all Videos: option 1

//controller
    //polymorph relation
    $videoList = Video::with(['media'])->get();

    foreach ($videoList as $video) {
        //don't like this:
        dc($video->media);
    }

or

option 2

//model
class Media extends Model{

    public function video()
    {
        return $this->belongsTo('App\Video', 'mediable_id');
    }

}

//controller:
    //belongsTo relation
    $mediaVideoList = Media::with(['video'])->get();
    
    foreach ($mediaVideoList as $media) {
        //makes more sense to me:
        dc($media->video);
    }

t0ne left a reply on Pattern For Media Library • 2 years ago

@jekinney Thanks for your advice, i tried this before but it didn't make much sense at the time. I try it again. Media can morph into Image object, File Object, Video Object.

This is what i have so far: (thanks to @martinbean and @pmall)

class Media extends Model
{
    protected $fillable = [
        'title',
        'description',
        'path',
        'thumbnail_path',
        'etc...'
    ];
    
    public function mediable(){
        return $this->morphTo('mediable');
    }
}

class Image extends Model
{
    protected $fillable = [
        'height',
        'width',
        'orientation',
        'alt',
        'ratio'
    ];

    public function media()
    {
        return $this->morphOne('App\Media', 'mediable');
    }
}   

class File extends Model
{
    protected $fillable = [
        'orientation',
        'application',
        'etc..'
    ];

    public function media()
    {
        return $this->morphOne('App\Media', 'mediable');
    }
}

Now i can retrieve a collection with Media Objects which have a 'mediable' relationship which contain a 'Image' or 'Video' or 'File' Object.

So far so good (?)

First question:

$media->mediable morphs into Image,File or Video,
how to determine which object $media->mediable is?
Now i use switch statement, is this the right way to use this pattern?
    //get a mediaList with all Images, Videos and Files 
    $mediaList = Media::with('mediable')->get();
    foreach ($mediaList as $media){
            dc($media->mediable);
            
            //get media thumbnail
            //all mediable object share 'thumbnail' property (Media->thumbnail_path)
            dc($media->thumbnail_path);
            
            //display specific mediable object properties
            //example: 
            //  - 'Video' has 'length' property
            //  - 'Image' has 'ratio' property
            switch (class_basename($medium->mediable_type)) {
                case 'Image':
                    dc($media->mediable->ratio);
                    break;
                case 'File':
                    
                    break;
                case 'Video':
                    dc($media->mediable->length);
                    break;
            } 
            
            //view blade
            include('media.'.class_basename($medium->mediable_type).'',[$media=>$media->mediable])
    }

5th May, 2016

t0ne started a new conversation Pattern For Media Library • 2 years ago

I need the right pattern for a media library, this is my db setup: media table

  • id
  • path
  • size
  • etc. image table
  • id
  • media_id
  • orientation
  • width
  • height
  • etc. video table
  • id
  • media_id
  • duration

I want to use it like this: //controller: $media->store(new Image); $media->store(new File); or $media->image->store(); $media->video->store(); or ?? How should i setup my model structure? Models: Media - shared properties

  • Image
    • specific properties
  • File
    • specific properties
  • Video
    • specific properties

25th April, 2016

t0ne started a new conversation Sort And Paginate Eloquent Relationship • 2 years ago

best solution to sort collection with relationship

i sort and paginate eloquent objects with relationship like this:

$collection = Object::with(['relation'])->where('foo','bar')->get();
$collection = $collection->sortByDesc('relation.published_at');
$collection->values()->all();
$collection = $this->getPaginator($collection, $perPage);

(i prefer this because of returned object '$collection->relation->column_names')

But i was wondering how this solution compares to the 'join sql' solution.

$collection = Object::join('relation')
    ->orderBy('relation.published_at', 'desc')
    ->where('foo','bar')
    ->paginate($perPage);

this returns $collection->column_names which i don't like.

I mean which solution has the better performance?

t0ne left a reply on Collection - OrderBy / SortBy • 2 years ago

i also use @zachleigh suggested solution to sort collections like this: (because of returned object '$collection->relation->column_names')

$collection = Object::with(['relation])->where('foo','bar')->get();
$collection = $collection->sortByDesc('relation.published_at');
$collection->values()->all();
$collection = $this->getPaginator($collection, $perPage);

But i was wondering how this solution compares to the 'join sql' solution.

$collection = Object::join('relation')->orderBy('relation.published_at', 'desc')->where('foo','bar')->paginate($perPage);

this returns $collection->column_names which i don't like.

I mean which solution has the better performance?

28th January, 2016

t0ne left a reply on UserRoles Vs MiddleWare And Policy • 2 years ago

thanks for your reply! makes sense, and that is what i need.

BUT... How can i use this in a controller or blade, for example:

//controller:
if (Gate::allows('view.user',$user)) {}
//blade:
@can('view.user',$user)

Or do i also have to create a policy to make this work?

routes.php uses MiddleWare and controller/view uses Policy?

t0ne left a reply on Best Way To Overwrite Option Method From Laravel 5 FormBuilder Class? • 2 years ago

thanks to @chrisrebacz, thanks!!

    /**
     * Register the form builder instance.
     */
    protected function registerFormBuilder()
    {
        //bindShared
        $this->app->singleton('form', function($app)
        {
            $form = new FormBuilder($app['html'], $app['url'], $app ['view'], $app['session.store']->getToken());

            return $form->setSessionStore($app['session.store']);
        });
    }

    /**
     * Register the html builder instance.
     */
    protected function registerHtmlBuilder()
    {
        $this->app->singleton('html', function($app)
        {
            return new HtmlBuilder($app['url'],$app['view']);
        });
    }

27th January, 2016

t0ne left a reply on Best Way To Overwrite Option Method From Laravel 5 FormBuilder Class? • 2 years ago

try to use this in laravel 5.2, but get error:

ErrorException in HtmlServiceProvider.php line 47: Fatal error: Call to undefined method Illuminate\Foundation\Application::bindShared()

changed "$this->app->bindShared" to "$this->app->singleton"

now i get:

ErrorException in HtmlBuilder.php line 39: Type error: Argument 2 passed to Collective\Html\HtmlBuilder::__construct() must implement interface Illuminate\Contracts\View\Factory, none given,

t0ne left a reply on UserRoles Vs MiddleWare And Policy • 2 years ago

thanks for your reply!

I still don't fully understand, hope you can help me out: i created 'App\Policies\RolePolicy'

class RolePolicy
{ 
    public function editProfile(User $auth_user, User $edit_user){
       return false;
    }
}

edited AuthServiceProvider:

    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
         User::class => UserPolicy::class
    ];

And now i can use it in my controller and blade files

//controller:
if (Gate::allows('editProfile',$user)) {}
//blade:
@can('editProfile',$user)

That's fine i guess;)

BUT: I also want to do check in the routes.php file, like:

Route::put('user/editProfile/{id}', ['middleware' => 'role:manager', function ($id) {

How can i RoleMiddleware make use of the RolePolicy?

t0ne started a new conversation UserRoles Vs MiddleWare And Policy • 2 years ago

I want to use UserRoles to protect my routes.

For example: only managers can add a user.

So i can create a RoleMiddleware and use "middleware' => 'role:manager" in my routes.php.

But also want to use Roles in blade (or a Model) so i can disable/hide a link if (manager) {}

Now i need Authorization and create something like RolePolicy.

So i want to protect my routes and blade with the rule.

Do i need to create a MiddleWare AND a Policy, is this good practice?

3rd November, 2015

t0ne left a reply on Why Use Polymorphic Relation Here • 2 years ago

check, thanks for your effort!

t0ne left a reply on Why Use Polymorphic Relation Here • 2 years ago

aha! so you can retrieve a collection of different objects yes?

t0ne left a reply on Why Use Polymorphic Relation Here • 2 years ago

@pmall oke, have some patience with me please;) almost get it...

but i can get the related objects by $media->images or $media->videos

Class Media{
    public function videos(){
        $this->hasMany('App\Video')
    }
}

Class Video{
    public function media(){
        $this->belongsTo('App\Media')
    }
}

t0ne left a reply on Polymorphism? • 2 years ago

@cristian9509 exactly what i would like to know! i feel like i can solve everything with foreign keys and pivot tables, what do i miss here!?

t0ne started a new conversation Why Use Polymorphic Relation Here • 2 years ago

I've got a question about @martinbean 's best answer: https://laracasts.com/discuss/channels/general-discussion/hasmany-but-hasmany-could-contain-different-models?page=1#reply-111744

Why use a polymorphic relation for the Media, Image and Video models. What is the benefit over a normal db relation (FK) in this case: Image.media_id(fk) an Video.media_id(fk).

t0ne left a reply on HasMany But HasMany Could Contain Different Models • 2 years ago

Why use a polymorphic relation for the Media, Image and Video models. What is the benefit over a normal db relation (FK): Image.media_id(fk) an Video.media_id(fk). ($game->media->images and $game->media->videos)

t0ne left a reply on Polymorphics Relations Or Regular? • 2 years ago

i also would like to know

2nd November, 2015

t0ne left a reply on Repo Pattern • 2 years ago

oke thank you both!

t0ne left a reply on Repo Pattern • 2 years ago

@pmall you agree with @zachleigh's answer?

t0ne left a reply on Repo Pattern • 2 years ago

@zachleigh thanks! And "because we bound the interface to a concrete class" it's not polymorphism? When the interface is not bound to a concrete class (no service provider register) it can be polymorphism?

t0ne left a reply on Repo Pattern • 2 years ago

good question, makes me think

interface IUserRepository 

class UserRepo implements IUserRepository

class UserMockRepo implements IUserRepository

class UserRedisRepo implements IUserRepository
class UserController extends BaseController {
    // IUserRepository is the interface
    public function __construct(IUserRepository $user) //Dependency Injection, polymorph can be an object which implements IUserRepository
    {
        $this->user = $user; //program to an interface
    }

in general: is this a repository pattern?

about the constructor:

  1. That's called de Dependency Injection right?
  2. Is this polymorphism? It can be any (different) object which implements IUserRepository
  3. $this->user is an interface which we can program to (?)

t0ne started a new conversation Repo Pattern • 2 years ago

To be sure: does the repository pattern fit in the program to interface, polymorphism principle?

thanks in advance!

t0ne left a reply on Different Models Based On Table Column, All Extending A Base Model • 2 years ago

understood sir!

30th October, 2015

t0ne left a reply on Different Models Based On Table Column, All Extending A Base Model • 2 years ago

@pmall you mean one media db table? how about specific properties like pixel_width etc?

t0ne left a reply on Different Models Based On Table Column, All Extending A Base Model • 2 years ago

Gonna try this, thanks for your effort

20th October, 2015

t0ne left a reply on Retrieve Related And Non Related Items ManyToMany • 2 years ago

oke;) what would you do?

t0ne left a reply on Retrieve Related And Non Related Items ManyToMany • 2 years ago

It works, thanks a lot!

I now use the '$unrelated_components' part my controller. How should i refactor this? Should i add a unrelatedComponents method to my Template model?

trying to be a good developer here;)

t0ne started a new conversation Retrieve Related And Non Related Items ManyToMany • 2 years ago

DB::tables:

Templates (table) -id -etc

Components (table) -id -etc

component_template (pivot table) -template_id (FK) -component_id (FK) -order_by_number

Class Template extends Model{

    public function components(){
        return $this->belongsToMany('App\Component')->withPivot('order_by_number')->orderBy('order_by_number','ASC');
    }
}

Class Component extends Model
{
    public function templates(){
        return $this->belongsToMany('App\Template');
    }
}

TemplateController:

$templates = Template::with(['components' => function($q) {
}])->get();//->get()

dd($templates);

returns:

Template Collection with -> related Component Collection

How do retrieve a TemplateCollection with related ComponentCollection AND a NON RELATED ComponentCollection:

Template Collection with -> related Component Collection (exists in pivot table) -> related Component Collection (does not exists in pivot table)

Is there something like belongsNotToMany?

19th October, 2015

t0ne left a reply on Need Advice On Eloquent Relationship • 2 years ago

what @CImrie said, very important. check the sql that's generated by your methods. I use barry's debugbar a lot for debugging.

16th October, 2015

t0ne left a reply on Relationship Advice (no Pun Intended :-P) • 2 years ago

shouldn't it be belongsTo relation? because player_deck_id, opponent_deck_id are foreign keys

t0ne left a reply on Need Advice On Eloquent Relationship • 2 years ago

I'm just learning laravel (so keep that in mind;))

But this is my solution:

Class Leaves extends Model{

    public function user(){
        return $this->belongsTo('App\User');//user_id = FK, inverse of hasOne
    }
    
    public function leaveType(){
        return $this->belongsTo('App\LeaveType');//leave_type_id = FK, inverse of hasOne
    }
}

class LeaveType extends Model{  
    public function leave(){
        return $this->hasMany('App\Leaves');//one to many
    }

}

class User extends Model{   
    public function leave(){
        return $this->hasMany('App\Leaves');//one to many
    }

}

In your controller:

Use eager nested(!) loading:

$user = Users::with('leave.leaveType')->find(1);

$user returns a 
User Collection with 
    -> nested Leave Collection with 
        -> nested LeaveType Collection

dd($user);

$user->leave[0]->leaveType->name

$sitemap = Users::with(['leave' => function($q) {  // 1 query for leaves with...
    $q->whereHas('leaveType', function ($q) { // ...1 subquery to filter the leaveTypes by related type name
        $q->where('name', 'foo');
    });
}])->paginate(30);//->get()

P.S. the relations that SLow Loris uses in the Leave Model don't make any sense to me, could be me ofcourse..

14th October, 2015

t0ne started a new conversation Set The Request Value • 2 years ago

ParameterBag {#329 ▼ #parameters: array:8 [▼ "_token" => "ythP0e9YfLlO0ZJHoLy3gnwiqUIt3tgBiHr28VhA" "system_name" => "asdfasdff" "parent_id" => "10" "online" => "1" "active_language_tab" => "nl" "translations" => array:5 [▼ "nl" => array:5 [▼ "id" => "" "sitemap_id" => "" "locale_id" => "" "name" => "asdf" "slug" => "sadf" ] "en" => array:5 [▶] "de" => array:5 [▶] "fr" => array:5 [▶] "es" => array:5 [▶] ] "created_by_user_id" => 1 "updated_by_user_id" => 1 ] }

how do i (re)set the request value of "translations > nl > id"? for example this works: $request->request->set('online',10000);

but something like this won't: $request->request->set('translations.'.$key.'.locale_id',$created_sitemap->translations[$key]->locale_id);

when i do: $request->translations[$key]['nl'] = insertID; i get "Indirect modification of overloaded property App\Http\Requests\SitemapRequest::$translations has no effect"

10th October, 2015

t0ne left a reply on Break, Continue, Return In Blade Template • 2 years ago

why do we use blade again?

8th October, 2015

t0ne left a reply on Update User: Allow Blank Password • 2 years ago

big miscommunication from my part sorry!

Edit Your Profile
Update

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