CodeX

CodeX

Member Since 3 Years Ago

Experience Points 3,015
Experience Level 1

1,985 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 2
Lessons
Completed
Best Reply Awards 2
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.

26 May
1 month ago

CodeX left a reply on Pay After Taking A Commission In Paypal?

See paypal adaptive payment or chained payment.

24 May
1 month ago

CodeX left a reply on Relation Not Working

Found this: https://github.com/topclaudy/compoships

Eloquent doesn't support composite keys. As a consequence, there is no way to define a relationship from one model to another by matching more than one column. Trying to use where clauses (like in the example below) won't work when eager loading the relationship because at the time the relationship is processed $this->l2 is null.

CodeX left a reply on Fast Auto-Complete

@diegodss maybe now we can use Laravel Scout instead... (yes, it's still using Algolia anyway)

CodeX left a reply on Single Code Base - Multiple Projects

I agreed to modular code approach which means you need to split your code in packages like snez1983 said. Laravel (as well as other frameworks) provides a way to do it, please take a look at Service Provider, Service Container and Package Development in the documentation.

As for multi tenancy, I don't think it's about managing our code, instead it's about separating data to keep separate users to have their own "isolated" data.

About using git branches, while it looks possible, things will become cumbersome to maintain as sooner or later there will be lots of difference for each branch. Git is version control so the best way is using git for versioning your packages, not for maintaining the raw code base for several projects.

26 Feb
3 years ago

CodeX left a reply on Inject Class Based On Route Parameters

Thanks all for your helps, I appreciate it.

CodeX left a reply on Inject Class Based On Route Parameters

@pmall Thanks a lot, looks good. I'll try it. Yes, those processors are for formatting (okay, they are presenters :)) but there are also some different process (like retrieving additional data) for each type, so I'm thinking to have different presenter classes.

CodeX left a reply on Inject Class Based On Route Parameters

@Pendo Thanks for your reply. But I think router binding like that is for replacing the parameter with an object/class instance? It's different than what I need here, I still need the post_type parameter as is, and I want to select "processor" class based on post_type parameter that will be injected to controller.

24 Feb
3 years ago

CodeX started a new conversation Inject Class Based On Route Parameters

Hi,

I want to inject a class to a controller, but the class that needs to be injected is determined by route parameters.

So, the route is something like this:

Route::get('posts/{type}', 'PostController@listPosts');

PostController:

class PostController
{
    public function listPosts($type)
    {
        $posts = Post::where('type', $type)->get();

        // currently the code is like below
        switch($type)
        {
            case 'typeone': 
                $processor = new TypeOneProcessor($type); break;
            case 'typetwo': 
                $processor = new TypeTwoProcessor($type); break;
            case 'typethree': 
                $processor = new TypeThreeProcessor($type); break;
        }
        $processedPosts = $processor->process($posts);

        // send to view
}

So, I want to get rid of switch statement and inject the class instead. I know I can use something like App::bind to bind an interface to concrete class, but I'm not sure about these:

  1. Where to put the App::bind in this case (because it needs to know what route is being accessed and only run for that specific route - /posts/{type} in this example).
  2. How to get the type parameter from the route that is required by "processor" class.

Please advise, thank you.

27 Nov
3 years ago

CodeX left a reply on Vue Components With Different Templates

Thanks for the reply. I got the solution from Vue.js forum, basically it's as simple as this:

// shared stuff
var List = Vue.extend({ ... })

var List1 = List.extend({
  template: '...'
})

var List2 = List.extend({
  template: '...'
})

CodeX started a new conversation Prevent Eloquent From Adding A Related Model In The Collection

Hi,

I need to retrieve some data with specific columns only. Let's say I have a Task model and TaskDetails model, the relation is using one-to-one, from Task model I need only id, name, info and from TaskDetails only id, description (just an example, we won't be arguing about merging Task and TaskDetails here :)).

So my code is like this:

$result = Task::with(['taskdetails', function($query) {
    $query->select('id', 'description');
})
->select(['id', 'name', 'info'])
->get();

It works fine at first, I got some data like this:

{
    id: 1,
    name: "task1",
    info: "task1 short info",
    taskdetails: {
        id: 1,
        description: "task1 description"
    }
}

then I added an accessor in TaskDetails for description column to get the task->info if the taskdetails->description is null.

class TaskDetails extends Model
{
    public function getDescriptionAttribute($value)
    {
        return $value?: $this->task->info;
    }
}

Now, for a TaskDetails row where description is null, Eloquent adds the Task model in the result like this:

{
    id: 1,
    name: "task1",
    info: "task1 short info",
    taskdetails: {
        id: 1,
        description: "task1 short info",
        task: {
            id: 1,
            name: "task1",
            info: "task1 short info",
            user_id: 1,
            // and all columns in Task
        }
    }
}

So, how to prevent Eloquent from adding the related Task data? because it's exposing all columns from the Task table which I don't want to.

23 Nov
3 years ago

CodeX left a reply on Vue Components With Different Templates

Thanks for your reply. Yes, that's one option, but there are quite some differences in both templates, so I'm afraid there would be a lot of v-if's.

Still looking for a neat way to do this... or maybe the question is, how to inherit a component?

CodeX started a new conversation Vue Components With Different Templates

Hi,

I have 2 lists on my web page, both lists have different templates, but they both have the same behaviors (such as: loading list items, count the items etc).

Here is what my web page basically looks like:

<template id="list1-template">
   <div v-for="item in items">
        <h3>{{ item.name }}</h3>
        <p>some contents for list1</p>
   </div>
</div>

<template id="list2-template">
   <div v-for="item in items">
        <h3>{{ item.name }}</h3>
        <p>this part looks different than list1</p>
        <p>let's say I have this additional html here</p>
        <ul><li>or anything else</li></ul>
   </div>
</div>

<div id="app">
    <list1></list1>

   <list2></list2>

   <div id="summary">
        {{ list1.countItems }} - {{ list2.countItems}}
  </div>
</div>

So I think I need a component for the list but I'm still confused how to write things all together. The code below just to show what I want to achieve, it doesn't work as expected, there is no error but Vue doesn't load the items either when I check it on Vue devtools.

var listing = Vue.extend({
   data: function() {
       items: [],
       countItems: 0
   },

   ready: function() {
        this.loadItems(); 

       this.countItems();
   },

   methods: {
      loadItems: function() {
         // load items from server
      },

      countItems: function() {
          // count loaded items
       } 
});

var list1 = new listing({   
   template: '#list1-template'
});

var list2 = new listing({
   template: '#list2-template'
});

Vue.component('list1',  list1);
Vue.component('list2', list2);

var app = new Vue({
   el: "#app"
});

Am I going to right direction here or is there any other way to do it? Any help would be much appreciated, thanks!

28 Oct
3 years ago

CodeX started a new conversation Handling Failed Queue Jobs

Hi everyone,

When the app got some failed jobs, I think it's too technical to let user of the app open CLI and run commands to push the jobs back onto the queue (artisan queue:failed to get the list of failed jobs and artisan queue:retry <ID>).

Could you please share how you handle it in your app? Any response would be greatly appreciated.

Thanks!

15 Sep
3 years ago

CodeX left a reply on Maintaining 2 Similar Projects In Git

Thanks for your reply @helmerdavila

I still have some doubt about using branch in this case. I'd like to have separated repositories, my further consideration is each repo can have its own access rights in Github (I'm not sure if this is possible using branch). Also, if using branch, these branches will never merge into one branch.

I'm thinking to cherry-picking between repos, I took a glance at http://stackoverflow.com/questions/5120038/is-it-possible-to-cherry-pick-a-commit-from-another-git-repository, but I'm open for any idea.

14 Sep
3 years ago

CodeX left a reply on Call Function On Defining Protected Property.

I think you can assign it in model constructor?

public function __construct(array $attributes = [])
{
    $this->table = config('forum.database.prefix').'conversation'; 

    parent::__construct($attributes);
}

PS. the $attributes parameter should be specified to make Model::create works. IIRC.

CodeX started a new conversation Maintaining 2 Similar Projects In Git

Hi,

I want to create a demo site of my web app, the code of the demo app is obviously derived from the main app with some minor differences (eg. some submt buttons won't do the actual process). We need to maintain the code base, which means when the common code is changed, we should be able to "commit" it to both main app and demo app. I'm thinking to create separated Git repos, but I'm not sure how everything works.

Please illuminate me! Thanks!

05 Sep
3 years ago

CodeX left a reply on Repository Injection And Model Binding In The Controller

@EHLOVader Thanks! I use this and it works like a charm:

Route::bind('post', function($id, $route)) {
    $post = app()->make(PostRepository::class);

    return $post->find($id);
}
04 Sep
3 years ago

CodeX left a reply on Repository Injection And Model Binding In The Controller

@olimorris Thanks for your response. Sorry, I should have been more clear in my question. In terms of model binding, what I mean is something like this:

Route::model('post', 'App\Models\Post');

so Laravel will provide the model instance to the controller whenever it finds {post} parameter in a route. It was the code from Laravel 4.2, strangely, I couldn't find it in Laravel 5.1 documentation, but it does work. Now, I'm wondering how to use Repository and Model binding. I have tried to pass the repository class like this:

Route::model('post', 'App\Repositories\PostRepository');

and got this error: FatalErrorException in Router.php line 945: Call to undefined method App\Repositories\PostRepository::where()

CodeX started a new conversation Repository Injection And Model Binding In The Controller

Well, this is a follow up question related to my previous question. In the controller, we usually inject the Repository, but at the same time we also use Model binding in some other methods. I don't know but I don't feel it's the correct way to have access to the model when the controller has already had Repository injected. The code is like this:

class PostController
{
    public function __construct(PostRepository $post)
    {
        $this->post = $post;
    }

    public function index()
    {
        $posts = $this->post->all();

        view(...);
    }

    public function edit(Post $post)
    {
        view('post.edit', compact('post'));
    }

    public function update(Post $post, PostRequest $request)
    {
        $post->fill($request->all());
        $post->save();
    }

Should we use only Repository in this controller? If the answer is yes, how to do the model binding?

CodeX left a reply on Add __call Method To Repository Class

@martinbean Thanks a lot for your explanation.

Well, I have another question related to this one, maybe in another thread. Thanks again.

CodeX left a reply on Add __call Method To Repository Class

@cloud4bpm Thanks, what you wrote is something that I'm after.

@martinbean Thanks for your explanation. Yes, I know that Repository pattern is for abstraction. What I asked was, is it fine to use the __call magic method which passes any call directly to the model? because I usually see that the repository has many methods which are just like duplicating the model's methods.

In case I need to use another ORM, I think I can write another repository which has its own methods like find() and all(), so it won't be called via __call magic method, like this:

class PostAnyORMRepository extends BaseRepository
{
    public function find($id)
    {
        return $this->model->findPk($id);
    }

    public function all()
    {
        return $this->model->getAll();
    }
}

CodeX started a new conversation Add __call Method To Repository Class

Hi,

I'd like add __call method to Repository class so we can directly call model's method like find(), all() etc. The code is like this:

class PostRepository
{
    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    public function __call($method, $parameters)
    {
        call_user_func_array([$this->model, $method], $parameters);
    }

    // repository methods
}

Maybe I will put it in the abstract class later. What do you think, is it good or bad?

CodeX left a reply on TO Upgrade Or Not To Upgrade

I did have a L4 app when L5 came out. Seeing the difference between L4 and L5 and having some my own libraries like in your situation, made me think many times to upgrade to L5. I read many developers said that they only needed couple hours to upgrade their apps from L4 to L5, I don't know how they did that but I don't think it was possible for my app.

But in the end, I decided to upgrade it to L5 anyway, because of these reasons:

  • L5 offers many new features (yeah it's worth to mention this)
  • when I had a problem and tried to find the solution, people are all talking about the solution in L5
  • I find lots of new shiny packages are only for L5 (sure you can make it work for L4 if you want, in exchange for pulling some hairs)
  • when there is a new developer who wants to join us, he/she knows the default Laravel functionalities instead of our custom libraries which some of them actually do similar functions with default ones in the new version.
  • L5.1 has LTS which gives benefits as explained above by bobbybouwman. Found a bug in an old unsupported version is not cool at all.

With some bloody efforts (well it's a bit exaggerated :)), I think I'm satisfied with my decision now.

01 Sep
3 years ago

CodeX left a reply on Fire Some Code Everytime A Line Gets Written To Log

@stefr Hmm... it's interesting to see how the log is configured in Laravel. All exceptions are handled by App\Exceptions\Handler class (that's what the doc says http://laravel.com/docs/5.1/errors#the-exception-handler). It has a report method that simply calls the parent method which is:

    public function report(Exception $e)
    {
        if ($this->shouldReport($e)) {
            $this->log->error($e);
        }
    }

$this->log comes from LoggerInterface dependency in the contructor, it's resolved in \Illuminate\Foundation\Bootstrap\ConfigureLogging:

        $app->bind('Psr\Log\LoggerInterface', function ($app) {
            return $app['log']->getMonolog();
        });

I don't know why it's resolved to getMonolog() instead of the $app['log'] itself, that's why there is no event got triggered. If it's resolved to $app['log'], then it will use the Illuminate\Log\Writer which triggers the log events.

I'm curious to test it, so I put this binding in App\Providers\AppServiceProvider:

public function boot()
{
        $this->app->bind('Psr\Log\LoggerInterface', function ($app) {
            return $app['log'];
        });

    \Event::listen('illuminate.log', function() {
        dd('got you!');
    });
}

then I created a bug to raise an exception (yeah, it feels weird when I intentionally created a bug even my username says so, lol), and the event was caught.

TBH, I'm not sure what further effect of this approach, so if you want to use it, use it at your own risk ;-)

31 Aug
3 years ago

CodeX left a reply on Laravel Collective Forms

If the form fields are the same for all Types, except the label and form submit, you can just add an id attribute and change the text accordingly to the Type using jquery.

{!! Form::select('type', ['Task' => 'Task', 'Booking' => 'Booking'], null, ['class' => 'form-control', 'id' => 'type_select']) !!}
{!! Form::label('name', 'Booking', ['class' => 'col-md-4 control-label', 'id' => 'name_label']) !!}

jquery:

$(function() {
    $('#type_select').on('change', function() {
        $('#name_label').html(this.value);
    });
})

If the form fields are different, you can wrap each form in a div, and use jquery to show/hide appropriate form.

<div id="Booking_form" class="the_form">

<put form code here>

</div>

jquery:

$(function() {
    $('#type_select').on('change', function() {
        $('.the_form').hide(); // hide all first
        $('#'+this.value+'_form').show(); // show appropriate form
    });
})

(untested code)

CodeX left a reply on Fire Some Code Everytime A Line Gets Written To Log

@stefr please try:

protected $listen = [
        'illuminate.log' => [
            'App\Listeners\InformAdminOfChangedLog',
        ],
    ];

CodeX left a reply on Fire Some Code Everytime A Line Gets Written To Log

Hi,

It looks like you can listen to the log event. in Illuminate\Log\Writer:

protected function fireLogEvent($level, $message, array $context = [])
    {
        // If the event dispatcher is set, we will pass along the parameters to the
        // log listeners. These are useful for building profilers or other tools
        // that aggregate all of the log messages for a given "request" cycle.
        if (isset($this->dispatcher)) {
            $this->dispatcher->fire('illuminate.log', compact('level', 'message', 'context'));
        }
    }

CodeX left a reply on Add Foreign Key To Form Submit Without Being Fillable

Hi,

You can just assign it after the fill, like this:

...
$article->fill($request->all());
$article->club_id = Auth::user()->club_id;

$article->save();

or you can utilize model events http://laravel.com/docs/5.1/eloquent#events

29 Aug
3 years ago

CodeX left a reply on Proble In Get Controller And Method From Url?

You can check what "artisan route:list" is doing behind the scene.

CodeX left a reply on Is It A Good Practice To Use Model::create?

@thomaskin @willvincent @Snapey Hi guys, thank you for all your response, I really appreciate it.

@Snapey if I don't set the column in $fillable, then Post::create won't work, yeah unless we use save() like you did. Okay, I understand I shouldn't worry about one extra SQL write, but if we can write once why twice? as we're using save() method, it can be like this:

$post = new Post;
$post->title = 'The title';
$post->date = date();
$post->other = 'something else';
$post->status = 'unpublished'; // it doesn't always default to 'unpublished', we might have dynamic assignment if we need it, let's say we set it to 'published' for approved publishers

$post->save();

and it would be better if we still use fill() without including 'status' (this is what I usually do):

// in the model
protected $fillable = ['title', 'post_date', 'other', 'attributes']; // no 'status' here

// in the controller
$post = new Post;
$post->fill($request->all());
$post->status = 'unpublished';

$post->save();

Here there is no double SQL write, and we will never worry about writing $request->except(['status']) in every other forms like when we use Post::create.

Please agree :D

28 Aug
3 years ago

CodeX left a reply on Is It A Good Practice To Use Model::create?

@Snapey That's one workaround, but if it's frequent, I think db updates are quite a load for the server.

@willvincent Like I said in my first post, the issue is we have to to maintain another form so there is no unexpected parameter (in this case the status) from malicious user (using $request->except()). Imagine that you will have additional column later, then you just add it to $fillable, then in another form somebody can just modify (hijack) it in the request to update the column if you don't add it in the $request->except. The column can be anything that cannot be initialized in DB structure, let's say it needs some calculation or whatever.

CodeX left a reply on Is It A Good Practice To Use Model::create?

@willvincent @thomaskim Yeah, that's just an example, the point is we have a column that should not be updated by the user.

CodeX left a reply on Is It A Good Practice To Use Model::create?

Hi Jeffrey,

It's an honor to get a reply from you :)

As far as I know, if we don't include an attribute in $fillable then the Post::create won't save it, but if we include it then it raised an issue like in my first post. Or is there something that I don't see?

CodeX started a new conversation Is It A Good Practice To Use Model::create?

Hi,

My concern is when we're using Model::create($data), we need to specify all attributes in $data as $fillable attributes. From what I learn, $fillable is used for protecting attributes from unexpected parameter in mass assignment. Let's say we have a Post model, one of the attributes is the post status where at first the value should be 'unpublished', so we write code like this:

$data = $request->all();
$data['status'] = 'unpublished';

Post::create($data);

in the code above we have to set $fillable = ['title', 'post_date', 'other', 'attributes', 'status'] in the Post model, thus Post:;create can create the data correctly, and we assigned status manually to protect the status value from malicious user who wants to change it. Everything works fine except the status value is protected in this code only!. Let's say we have another form that allows a user to update the post title and some other attributes except the status, like the following:

$data = $request->all(); 

$post = Post::find(1);
$post->update($data);

then the malicious user can pass a status in the request to change its value. Of course we can use $request->except(['status']) but it makes $fillable kind of useless, instead of let Laravel check what are fillable, we control it by ourselves.

What do you think about this?