martinbean

martinbean

Senior Developer at Visualsoft Ltd

Newcastle upon Tyne, UK

Member Since 4 Years Ago

Experience Points 463,305
Experience
Level
Lessons Completed 451
Lessons
Completed
Best Reply Awards 634
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

17 Jan
1 day ago

martinbean left a reply on How To Keep Old Model's Data Until New Changes Are Approved ??

@Ranx99 You could create a new model, say SectionRevision. A Section would have many SectionRevisions. When a SectionRevision is approved, it could copy its changes to the related Section model, so you Section model always has the last-approved revision’s content.

martinbean left a reply on Can I Customize Laravel Auth Login?

@jlrdw is absolutely right.

16 Jan
2 days ago

martinbean left a reply on Triple Pivot Table

@insperio If a user can only have one role at a particular company, then just add role to your company_user pivot table, and the companies relationship on your User model.

class User extends Authenticatable
{
    public function companies()
    {
        return $this->belongsToMany(Company::class)
                    ->withPivot('role');
    }
}
@foreach ($user->companies as $company)
    <div>Company: {{ $company->name }}</div>
    <div>Role: {{ $company->pivot->role }}</div>
@endforeach

martinbean left a reply on Driver [shopify] Not Supported

@mukesh654 Sounds like you haven’t properly installed/registered the Shopify provider for Socialite.

15 Jan
3 days ago

martinbean left a reply on How Can I Host Storage On Different Source?

@malhayek There are literally thousands of services that will allow you to store assets. Amazon S3, Google Cloud Storage, Azure Storage etc.

martinbean left a reply on How Can I Add Queries To An Instance Of A Model Without Using It Right Away?

@EYALM - @eyalm Not sure how that differs from just building a query in that case? Might be better to type-hint the Query instance rather than a model:

$query = Model::query();

$query = someFunctionThatAddsWhereClause($query);

$results = $query->get();

martinbean left a reply on Create Modular System

@mdelshad Use namespaces to create “modules” in your code?

So if you have news articles, put news-related classes under a News namespace. If you have events, put event-related classes under a Event namespace, and so on.

martinbean left a reply on Eloquent Modeling

@danyal14 Eloquent doesn’t really have the notion of “child” models—an Eloquent model relates to a database table, and has relationships to other models.

If you have a recipe site that offers recipes in different “formats” (text and video) then you could have a polymorphic Recipe model, that morphs to either a TextRecipe or VideoRecipe model.

You can read more about polymorphic relationships in the Laravel documentation: https://laravel.com/docs/5.7/eloquent-relationships#one-to-one-polymorphic-relations

martinbean left a reply on How Can I Add Queries To An Instance Of A Model Without Using It Right Away?

@eyalm Sounds like what you’re doing is a bit around-the-houses and there could be a better way to achieve what it is you’re trying to do.

What is it you’re trying to do and we may be able to suggest an alternative approach?

martinbean left a reply on ES6 Import In Vue Components Or Globally In App.js?

do you import what you use in each component, or do you import all libraries you use to your app.js to have it globally available?

@schemeza Do you import all facades in a controller? Or do you only import the facades you need?

Only import what you need, when you need it.

martinbean left a reply on Create Modular System

@mdelshad Namespaces are “modules”. Your code will be modular in nature if you organise it such a manner.

08 Jan
1 week ago

martinbean left a reply on Difficult Polymorphic Relationships

@xtremer360 I don’t get what an “observation” is.

An observation is a term used to denote either a photo/test/comment.

What is a “test”? How do you “test” a room?

martinbean left a reply on A Wrapper To Contains All Eloquent Queries

@JLRDW - > Usually I'd prefer a fat controller rather than a fat model.

?

A model is where you logic goes, and then called by entry points in your application such as a HTTP controller, a CLI command, a queued job etc. Controllers should be one of the slimmest parts of the your app (simply calling methods on classes from the “core” of your application).

martinbean left a reply on Difficult Polymorphic Relationships

@xtremer360 Is it not a room can belong to many properties in this case, rather than it being polymorphic?

martinbean left a reply on Suggest Me A License For This CMS I Built Over Last 2 Years That I Plan To Open Source

@nikocraft I’d worry more about what’s different with your CMS and how it’ll be any better or different than WordPress, Statamic, OctoberCMS, PyroCMS et al before worrying about what licence to release it under.

martinbean left a reply on Factories & Testing With Multiple Objects

@NBENNETT - @nbennett No problem. Glad I could help :)

07 Jan
1 week ago

martinbean left a reply on Repository Vs Model?

@kaioin I’ve been writing PHP for over 10 years now, and the past five has been working on primarily Laravel applications. I seldom use repositories and not had the maintainability of an application suffer because of that decision.

Repositories tend to end up being classes that just repeat model logic. They then get complicated when you start introducing things like relationships. “I need to query X, but in this context I also need Y.” Repository classes get very unwieldily very quickly.

There’s also the contentious issue as to what exactly should the repository be responsible for? The original description of Repository as a pattern says they should be used to provide collection-like access to a group of objects (without caring about its underlying storage mechanism). From that description it’s inferred repositories should therefore be read-only, yet people put persisting methods like save, create, update etc in their repository classes. Repositories should be used in tandem with command classes to write data, and when you do you start going down the rabbit hole of other patterns such as domain-driven design (DDD) and command query responsibility segregation (CQRS).

In my experience, I’ve found if you stick to well-defined Eloquent models and corresponding resource controllers, policies, and form request classes; your Laravel applications remain easy to maintain, navigate, and iterate on. Controllers seldom have more than one line of logic (either reading or writing from a model). If you go down the path of adding things like repositories then it’s just additional layers you need to unpick when you need to update logic.

martinbean left a reply on Factories & Testing With Multiple Objects

@nbennett Tighten published a blog post last year where they cover the concept of class-based model factories: https://tighten.co/blog/tidy-up-your-tests-with-class-based-model-factories

Like you, they had lots of related models in an application, so use a fluent interface to create the required models.

martinbean left a reply on What Is A Good Way To Keep Track Of Cart Quantity Across Different Pages?

@JLRDW - @jlrdw Not if the user logs in/out, as the session is flushed.

@rotaercz Instead, you could create models for your cart and cart items, and then use a cookie to store the cart ID so you know which cart to pull from the database.

martinbean left a reply on Looking For Digital Template Like This

@davidboo You could instead do a little bit of research and create your own design for your website, instead of trying to copy another company’s?

martinbean left a reply on Oauth - How Do They Do It?

@mithrandir Atlassian will have a client for Jira, so there will be a Jira client ID and secret. Jira will redirect you, you’ll authenticate with Intercom, and Intercom will redirect back to Jira with an access token that Jira can use to authenticate with Intercom as you.

martinbean left a reply on Navbar: Vertical!! Why?

@trederusmaximus No one can really give you an answer unless you post a URL or some contextual code.

martinbean left a reply on Date/Age Validation

@lawkunchi Laravel has an “before” validation rule for dates: https://laravel.com/docs/master/validation#rule-before. From the docs:

The dates will be passed into the PHP strtotime function

Therefore, you can use this to test if a date is more than 18 years ago:

public function rules()
{
    return [
        'before:-18 years',
    ];
}

martinbean left a reply on Coding Efficient Jobs

@pilat The only thing I can suggest is: if you have a hypothesis, test it. If you’re concerned about memory usage then try and find some way of profiling that (there are various tools available to do so) and see if it actually is a problem.

14 Dec
1 month ago

martinbean left a reply on Best Practice (Service, Controller Or Something Else)

@janthoegersen Yeah, I like to use synchronous jobs for wrapping up logic like this, that can then be used in different contexts (HTTP, console).

I’m not sure it’s “standard” practice but I adopted it as jobs was borne out of the command bus pattern. They were known as commands in Laravel 5.0, but by Laravel 5.1 they were renamed to “jobs”.

The command bus pattern is a “standard” practice, and sync jobs (i.e. immediately dispatched) emulates that.

martinbean left a reply on Best Practice (Service, Controller Or Something Else)

@janthoegersen Create a job. You can then call it in both controllers and console commands.

class ProjectHealthCheck
{
    use Dispatchable;

    public function handle()
    {
        // Do health check work here; return results
    }
}
class ProjectController extends Controller
{
    public function someAction()
    {
        $results = ProjectHealthCheck::dispatchNow($project);

        // Send results to view
    }
}
class SomeConsoleCommand extends Command
{
    public function handle()
    {
        $results = ProjectHealthCheck::dispatchNow($project);

        // Display results
    }
}
07 Dec
1 month ago

martinbean left a reply on Separate The Html From Vue Componente Use In Blade

@PETRITR - @petritr Yeah, it’s just the same as if you placed the template in a single-file component:

<your-component inline-template>
  <ul>
    <li v-for="(item, index) in items" v-bind:key="index">
      <!-- Item mark-up -->
    </li>
  </ul>
</your-component>

martinbean left a reply on Separate The Html From Vue Componente Use In Blade

@petritr I think you’re looking for inline templates: https://vuejs.org/v2/guide/components-edge-cases.html#Inline-Templates

This will allow you to write your component’s mark-up inline when using your component:

<your-component>
    <!-- Mark-up for your component -->
</your-component>
05 Dec
1 month ago

martinbean left a reply on Farewell NOVA

@bbarclay Nova—like everything—is not a silver bullet. Also, every one’s use case differs. Just because it’s not worked out for you doesn’t mean it’s not worth using.

I’ve trialed software in the past and some has not been suitable or I’ve not been able to get comfortable with. I don’t hop on to forums and wish it “farewell” and deter others from using it.

martinbean left a reply on Accounting In The Modern Age

@mathewparet Stripe have a “balance transaction“ entity (https://stripe.com/docs/api/balance/balance_transaction) that records credits and debits for each account. So when moving money from one account to another, you’d create two balance transaction instances: one for the debit in account A, and one for the credit to account B.

You can wrap this up in a job, and you’ll also need to wrap it in a database transaction so either both the balance transactions are created, or none at all are created.

class MoveFunds
{
    use Dispatchable;

    public function __construct(int $amount, Account $source, Account $destination)
    {
        $this->amount = $amount;
        $this->source = $source;
        $this->destination = $destination;
    }

    public function handle()
    {
        // TODO: Check source has anough funds, but I would do that outside of
        // this class, as it is not this class’s responsibility

        DB::connection(function () {
            $this->createCredit();
            $this->createDebit();
        });
    }

    private function createCredit()
    {
        $this->destination->credit($this->amount);
    }

    private function createDebit()
    {
        $this->source->debit($this->amount);
    }
}
class Account extends Model
{
    public function balanceTransactions()
    {
        return $this->hasMany(BalanceTransaction::class);
    }

    public function credit(int $amount)
    {
        return $this->balanceTransactions()->create([
            'amount' => abs($amount),
        ]);
    }

    public function debit(int $amount)
    {
        return $this->balanceTransactions()->create([
            'amount' => abs($amount) * -1,
        ]);
    }
}

martinbean left a reply on Dynamically Create Different Tables For Same Model?

@ralphmorris Databases like MySQL can handle millions of rows—even billions if you use a `BIGI column for primary keys: https://stackoverflow.com/questions/2716232/maximum-number-of-records-in-a-mysql-database-table

martinbean left a reply on Dynamically Create Different Tables For Same Model?

@ralphmorris I wouldn’t create a table per site. I’d instead have a site_id column and foreign key in your sites table. You can then keep your logs relation in your Site model.

If you’re worried about the number of entries in the logs table then you could look at storing your logs using an alternative solution, such as Papertrail.

04 Dec
1 month ago

martinbean left a reply on Is Docker Good For A Real Time System?

@gthell Docker is just a way of running an application. It is not a performance “magic bullet”.

03 Dec
1 month ago

martinbean left a reply on New Column In Password_resets

@sguserface What have you actually tried so far?

martinbean left a reply on Need Advice About Optimization

@davidsprauel Without knowing your database structure or model relationships, I’d look at starting to add joins to your main query to include authorisation checks. So if a user is only able to view a specific set of topics, then query that and create a whereIn clause from that set.

martinbean left a reply on Making A Simple Quiz Application

@smartnathan What specifically is your question? If you want to get the option that’s the answer, just do a where condition:

$answer = $question->options()->where('is_answer', true)->first();
02 Dec
1 month ago

martinbean left a reply on Jobs Applications Board

@eso No problem. Glad to help :)

01 Dec
1 month ago

martinbean left a reply on Jobs Applications Board

@eso I’d have a dedicated model, say Application, that you can check exists for a user and job combination when checking if a user has applied for a particular job:

class Application extends Model
{
    public function job()
    {
        return $this->belongsTo(Job::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
class User extends Authenticatable
{
    public function applications()
    {
        return $this->hasMany(Application::class);
    }

    public function hasAppliedFor(Job $job)
    {
        return $this->applications()->where('job_id', $job->getKey())->exists();
    }
}
$job = Job::find($id);

$applied = $user->hasAppliedFor($job); // true or false
30 Nov
1 month ago

martinbean left a reply on Need To Get All Facebook Page Likes In Laravel

@HASAFTAB - > its Replying

@hasaftab And have you actually read the reply…?

The error message in the reply is telling you what the problem is. You’re trying to use an endpoint, but you need to be approved by Facebook first. It then gives you a link on how to do that.

29 Nov
1 month ago

martinbean left a reply on How Do I Create A Subdomain In Homestead That Points To A Different Directory?

@chrisf79 Just add two site definitions to your Homestead YAML file?

sites:
    -
        map: mysite.test
        to: /path/to/mysite/public
    -
        map: blog.mysite.test
        to: /path/to/mysiteblog/public
28 Nov
1 month ago

martinbean left a reply on Need Help For Facebook Fan Page Count

@hasaftab You need an access token to use Facebook’s Graph API. There’s no way around that.

martinbean left a reply on Mobile/ Phone Number Validation

@lalitesh You can use a service like Nexmo or Twilio if you need to properly validate phone numbers.

27 Nov
1 month ago

martinbean left a reply on Laravel Spark With Different Payment Gateway

@anas-k Spark is very tightly coupled with Stripe, so you’ll need to do a fair bit of development to implement another payment gateway.

martinbean left a reply on Do You Prefer Helper Functions Over Facades/DI?

@alchermd I prefer façades (and then type-hinting where it makes sense).

I’d rather method calls look like they’re being done on objects (even if they do look like static method calls) rather than global functions.

martinbean left a reply on Laravel Maintenance Mode

@CODINGPROGRESS - @codingprogress Cloudflare will proxy requests.

See this answer on Stack Overflow. $request->ip() will give you Cloudflare’s proxy IP address. The client’s IP address is sent as an additional HTTP header (CF-Connecting-IP).

26 Nov
1 month ago

martinbean left a reply on Laravel Maintenance Mode

@codingprogress Are you using a load balancer and if so, are you proxying the IP address correctly? Because the IP address your application is receiving might be that of the load balancer, and not your machine’s.

martinbean left a reply on 500 Internal Server Error When Deploying Project

@madmaxax You should still have access to PHP error logs, even on a 1&1 shared hosting account.

23 Nov
1 month ago

martinbean left a reply on How To Force Laravel To Fail A Job

@mikail10000000 It sounds like you just want to test a listener is dispatched when the JobFailed event is dispatched, so do just that:

namespace Tests\Feature;

use App\Exceptions\ExampleException;
use App\Jobs\ExampleJob;
use Illuminate\Queue\Events\JobFailed;

class ListenerTest extends TestCase
{
    public function testNotificationIsSentIfJobFails()
    {
        $connection = 'foo';
        $job = new ExampleJob;
        $exception = new ExampleException;

        event(new JobFailed($connection, $job, $exception));

        // Test your listener was fired here.
        // If you dispatch a notification, then use Notification fake:
        // https://laravel.com/docs/5.7/mocking#notification-fake
    }
}

martinbean left a reply on Why Isn't Laravel Core Still Type-hinted?

@RoboRobok Ask him? He’s going to know being the lead on the framework, that us here on a forum. All we can do is speculate.

martinbean left a reply on Why Isn't Laravel Core Still Type-hinted?

Because visual debt.

In all seriousness, I just think it’s a style choice of Taylor Otwell.