martinbean

martinbean

Senior Developer at Visualsoft Ltd

Member Since 5 Years Ago

Newcastle upon Tyne, UK

Experience Points
517,585
Total
Experience

0 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
531
Lessons
Completed
Best Reply Awards
692
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

Level 50
517,585 XP
Apr
02
12 hours ago
Activity icon

Replied to Stripe Elements Mounted Vs Method

@grahammorbydev Hey, I’ve been in the same boat as you! The default Stripe JavaScript SDK isn’t great to work with in that it’s asynchronous and not an NPM module you can install and import… unless React devs /sideeyes

How I’ve approached this in my own apps is to have a StripeCardElement element component that other components can use and interact with. The card element component is pretty “dumb”—all it does is initialise Stripe and the element:

<!-- resources/js/components/StripeCardElement.vue -->
<template>
  <div>
    <div id="card-element" ref="cardElement" />
    <div id="card-error" role="alert" if="error" v-text="error" />
  </div>
</template>

<script>
export default {
  created() {
    this.stripe = window.Stripe(this.publishableKey);

    this.cardElement = this.stripe.elements().create('card');
  },
  data() {
    return {
      cardElement: null,
      stripe: null
    };
  },
  mounted() {
    this.cardElement.mount(this.$refs.cardElement);
  },
  props: {
    error: {
      default: null,
      required: false,
      type: String
    },
    publishableKey: {
      required: true,
      type: String,
      validator: (key) => key.startsWith('pk_')
    }
  }
}
</script>

When the component is created, it initialises Stripe, and then when mounted actually mounts the card element.

So, in other components (say, a checkout component), you can import this component, give it a reference, and interact with it. Here’s how I do that:

<!-- resources/js/components/SimpleCheckout.vue -->
<template>
  <form method="POST" v-on:submit.prevent="onSubmit">
    <fieldset>
      <div class="form-group">
        <label>Cardholder name</label>
        <input type="text" name="cardholder_name" v-model.trim="cardholderName" autocomplete="cc-name" required />
      </div>
      <div class="form-group">
        <stripe-card-element
          ref="stripeCardElement"
          :error="cardError"
          :publishable-key="stripePublishableKey"
        />
      </div>
    </fieldset>
  </form>
</template>

<script>
import StripeCardElement from './StripeCardElement.vue';

export default {
  components: {
    StripeCardElement
  },
  data() {
    return {
      cardError: null,
      cardholderName: ''
    };
  },
  methods: {
    onSubmit() {
      // Interact with Stripe card element here
      const data = {
        payment_method: {
          billing_details: {
            name: this.cardholderName
          }
        }
      };

      this.$refs.stripeCardElement.confirmCardPayment(clientSecret, data).then((paymentIntent) => {
        console.log(paymentIntent);

        // Check PaymentIntent was successful
        // Show success message if it was
      }).catch((error) => {
        console.error(error);

        this.cardError = error.message;
      });
    }
  },
  props: {
    stripePublishableKey: {
      required: true,
      type: String
    }
  }
}
</script>

You may have noticed my confirmCardPayment intent looks a little different to the one in the Stripe documentation. That’s because I proxy it in the StripeCardElement component:

methods: {
  confirmCardPayment(clientSecret, data) {
    // Payment method can be either object or string (ID of existing payment method)
    // If is object, set reference to card element
    if (data.hasOwnProperty('payment_method') && typeof data.payment_method === 'object') {
      data.payment_method.card = this.cardElement;
    }

    return new Promise((resolve, reject) => {
      // Call the actual stripe.confirmCardPayment method
      // Returns a Promise that either:
      //  a. resolves with PaymentIntent
      //  b. rejects with error
      // Improvement on Stripe SDK, which just resolves and you have to check yourself
      // if result was error or successful
      this.stripe.confirmCardPayment(clientSecret, data).then((result) => {
        result.error ? reject(result.error) : resolve(result.paymentIntent);
      });
    });
  }
}

And that‘s pretty much it!

I appreciate this is a lot of code and a lot to get your head around, so if you do have any questions about the above or working with Stripe in Vue components, let me know and I’ll be happy to help!

Mar
28
5 days ago
Activity icon

Replied to $appends For A Collection And Avoiding Sticky Relations?

@jjk Why do you need the “next ID” when loading a customer? Surely you only need to know that ID when creating a new order…?

Mar
27
6 days ago
Activity icon

Replied to Multiple Traits - Best Practices

@appdezign Traits are supposed to be functionality that you’re able to “mix” into different classes. If you have traits that depend on methods in another a trait, then that sounds a bit like a design problem and you probably need to refactor. Traits should, ideally, be able to be used independently of each other.

Rails has a similar concept of “concerns”. It might be worthwhile to think of traits as as a concern: make a trait only concerned about one particular piece of functionality that needs to be shared amongst your controllers/models. A single trait shouldn’t be concerned about another piece of functionality. If it does, you’ve crossed a boundary and need to re-think.

Mar
16
2 weeks ago
Activity icon

Replied to Unit Test 2FA

@kalimeromk You would probably write an integration test for something like two-factor authentication.

Activity icon

Replied to How To Minimize Hardcoded Database Identifiers?

@sfsccn What do you mean by “database identifiers”? Do you mean table and column names? Or IDs of individual records?

Activity icon

Replied to Laravel Social Network Or Node?

@mmorgan86 Neither’s better than the other. Go with what you know.

Activity icon

Replied to Cashier - HandleCardSetup - Invalid API Key

@weathercaptain Well, the error’s pretty self-explanatory. You’re passing an invalid API key.

When you create the Stripe element, you should use the publishable key (the one beginning with pk_test_). But you should pass the client secret of the setup intent when calling handleCardSetup on the element.

Also, handleCardSetup as a method is deprecated: https://stripe.com/docs/js/deprecated/handle_card_setup

Activity icon

Replied to Passport Setup For Use With Mobile App

@msslgomez Read the documentation: https://laravel.com/docs/master/passport#password-grant-tokens

Create a Password Grant client, and you can then request tokens using the grant type.

Activity icon

Replied to PHP Code Base To IOS

@Ap3twe Web apps written in PHP are completely different to iOS apps written in Swift. You can’t just straight up convert one to the other. One runs in a browser, the other runs on mobile phone.

Is learning Swift comparable to PHP? Does it borrow some syntax Interoperability?

Not really. They’re both programming languages, but stem from different origins.

Activity icon

Replied to RESTful API

@cookie_good Yes. Lots of people will have built an API in Laravel to be consumed by mobile apps. You can then use something like Passport to authenticate users in your mobile app against your API.

Mar
12
3 weeks ago
Activity icon

Replied to Storing Images On Amazon S3 Instead Of Local Disk

@henryoladj And have you set the default filesystem driver to s3…?

Activity icon

Replied to Storing Images On Amazon S3 Instead Of Local Disk

@henryoladj You set the value of the FILESYSTEM_DRIVER environment variable to s3.

Also be sure to set values for the other S3-related environment variables (AWS_ACCESS_KEY_ID, etc).

Mar
07
3 weeks ago
Activity icon

Awarded Best Reply on Story On How I Screwed Up (and I Need Advice On How To Fix)

@zefex Well given you have a time constraint, you need to choose a route to go down:

  1. Generate thumbnails at pre-defined sizes that will serve their purpose.
  2. Learn about CDNs, and use a CDN to serve your dynamically-generate thumbnails.
  3. Stump up the cash and use a service like imgix or Cloudinary.

It sounds like you have a bit of knowledge gap, and unfortunately with the time constraint there isn’t really a shortcut that will magically solve your predicament.

You really should be using a CDN to each and serve your dynamically-generated thumbnails. I’d also imagine your potential investors would like your application to be able to handle a page with a small number of thumbnail images before parting with cash to grow your product and the number of images it’s serving.

Mar
06
3 weeks ago
Activity icon

Replied to Story On How I Screwed Up (and I Need Advice On How To Fix)

@zefex Well given you have a time constraint, you need to choose a route to go down:

  1. Generate thumbnails at pre-defined sizes that will serve their purpose.
  2. Learn about CDNs, and use a CDN to serve your dynamically-generate thumbnails.
  3. Stump up the cash and use a service like imgix or Cloudinary.

It sounds like you have a bit of knowledge gap, and unfortunately with the time constraint there isn’t really a shortcut that will magically solve your predicament.

You really should be using a CDN to each and serve your dynamically-generated thumbnails. I’d also imagine your potential investors would like your application to be able to handle a page with a small number of thumbnail images before parting with cash to grow your product and the number of images it’s serving.

Mar
05
4 weeks ago
Activity icon

Replied to Story On How I Screwed Up (and I Need Advice On How To Fix)

@zefex Generate a fixed-sized thumbnail when you upload the original image.

Mar
02
1 month ago
Activity icon

Replied to How To Use Package Views

which place i past that line?

@salomon022 Please read the Laravel docs more thoroughly: https://laravel.com/docs/master/packages#views

Feb
28
1 month ago
Activity icon

Replied to Like/Dislike System In Post ? Without Any Packages

@neeraj1005 It’s not that difficult. Create a table that stores a model idea, a user idea, and whether that user liked or disliked that model.

Feb
26
1 month ago
Activity icon

Replied to Is There An Easier Alternative To Stripe SDK

@gabotronix You’re going to have to deal with SCA no matter what payment processor you use.

I’d argue Stripe’s is probably one of the most easiest to use implementations. Stripe’s engineers are some pretty intelligent people who really sweat the details in their APIs and client libraries.

Feb
24
1 month ago
Activity icon

Replied to Default Route Parameters?

@afraz That’s just doing the same as what my answer is doing, but using a façade instead.

Feb
21
1 month ago
Activity icon

Replied to User Permissions On Single Attributes

@masaro If you’re validating using form requests, you could utilise those.

You can conditionally validate attributes based on the authenticated user. You can then access the attributes that were validated in your controller.

use Illuminate\Validation\Validator;

class UpdateArticleRequest extends FormRequest
{
    public function rules()
    {
        return [
            // All users can update headline and body
            'headline' => ['required', 'string', 'max:60'],
            'body' => ['required', 'string'],
        ];
    }

    public function withValidator(Validator $validator)
    {
        if ($this->user()->role == 'admin') {
            // Only administrators can update published attribute
            $validator->addRules([
                'published' => ['required', 'boolean'],
            ]);
        }
    }
}
public function update(UpdateArticleRequest $request, Article $article)
{
    $article->update(
        $request->validated() // Only pass validated attributes to Article model
    );
}
Activity icon

Replied to How To Use Cache-Control With Nginx

@chechogrom Well you’re not setting a max-age directive yourself, so I’m going to guess nginx will send a value of 0 by default.

This blog post by Harry Roberts is a good resource on cache control headers.

Activity icon

Replied to Payment System

stripe is for direct payments

@afrasiyabhaider …and more. Read the docs. You’ll see they have a solution for building a marketplace, too: https://stripe.com/docs/connect

Feb
20
1 month ago
Activity icon

Replied to I Need A Laravel Ready Project!!!! Plz If Some One Have It. Plzz I Really Need It Badly..

@abdulrafey38 Do you own homework.

Laracasts isn’t a place to get experienced, professional programmers to complete assignments for you.

Activity icon

Replied to How Contextual Binding In A Console Class?

@alex_storm How are you then trying to instantiate/use ExternalAPIContract in your FacebookCommand class?

Feb
17
1 month ago
Activity icon

Replied to Eloquent Vs. Custom Query

@kiasaty I don’t want to sound mean, but it sounds like you’re working with a bunch of absolute amateurs and you’re not going to learn anything in this company.

I lie. You will learn: bad habits.

Feb
16
1 month ago
Activity icon

Replied to Users And Categories Have Many Services

@mmaged Well what have you tried so far…?

Activity icon

Replied to Eloquent Vs. Custom Query

they said that Eloquent queries are not efficient.

Eloquent uses the query builder under the hood…?

they said Eloquent is slow and there are a lot of joins in Eloquent queries.

Only if you write queries with joins.

Repository makes the sql query, then passes the result to Factory, then Factory maps the result to entity and returns the entity.

Well that’s wrong. A repository itself is supposed to return entities. Factories are being used entirely wrong there.

@kiasaty It sounds like your colleagues couldn’t be bothered to learn how to use Laravel/Lumen and Eloquent properly, and instead hand-rolling their own solutions with incorrectly-used design patterns.

Activity icon

Replied to Optional Route Generate Two Slashes URL

@joaohamerski Optional parameters can only occur at the end of a route URI.

Feb
14
1 month ago
Activity icon

Awarded Best Reply on Security Question

Now the question: if one knows the exact path to call, like http://<app_address>/storage/invoiceXXX.pdf could be able to download every document in there.

@giorg Right. So you need to use authorization.

Usually, you would store files in a non-public location, and then only return download responses if you have a logged-in user and you know that user has access to the file attempting to be downloaded:

class InvoiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only('show');
    }

    public function show(Invoice $invoice)
    {
        // Check user owns invoice using policy
        $this->authorize('view', $invoice);

        // User can view invoice; return download response
        return response()->download($invoice->path);
    }
}
Activity icon

Replied to Security Question

Now the question: if one knows the exact path to call, like http://<app_address>/storage/invoiceXXX.pdf could be able to download every document in there.

@giorg Right. So you need to use authorization.

Usually, you would store files in a non-public location, and then only return download responses if you have a logged-in user and you know that user has access to the file attempting to be downloaded:

class InvoiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only('show');
    }

    public function show(Invoice $invoice)
    {
        // Check user owns invoice using policy
        $this->authorize('view', $invoice);

        // User can view invoice; return download response
        return response()->download($invoice->path);
    }
}
Feb
13
1 month ago
Activity icon

Commented on Value Objects And Mutability

I love value objects. I blogged about them a little while ago: https://martinbean.co.uk/blog/2019/11/07/using-value-objects-in-projects/

Feb
12
1 month ago
Activity icon

Replied to Laravel Routes - Best Practices.

@pablot There’s no real concrete rules, but there are a handful of prevalent practices that make managing your routes easier in the long run.

With your example where you have a front-end marketing website and the application itself, a lot of businesses like that will have the marketing website on the www. subdomain (so www.radar.com) and then the application itself on an app. subdomain (i.e. app.radar.com). This allows you to separate your marketing website from the application itself, and scale both independently.

Other than that, the convention you’re following for businesses and offices is good. Use resource controllers (and nested resource controllers) as much as possible. If you build your application around resources as much as possible, it makes life so much easier!

Feb
05
1 month ago
Activity icon

Replied to Work With Model Data From Remote Source

@jjk If it’s just a case of a table in a remote database, then you could create an Eloquent model for that table and set the connection in that model class:

class RemoteCustomer extends Model
{
    protected $connection = 'remote';

    protected $fillable = [
        'id',
        'name',
        'address',
        'date_registered',
    ];
}
Jan
28
2 months ago
Activity icon

Replied to How To Create New Database For Every Session

@uksarkar Don’t create a database on demand like this unless you want your users to crash your server.

Instead, you could have interested customers create a demo account by clicking a button. You could have a server-side script then create a new database, migrate, and seed it using a queued job. When the queued job finishes, broadcast an event to the front-end and redirect the customer to their newly-configured demo account.

Make sure to have a scheduled task to clean up your created databases.

Activity icon

Replied to Laravel How To Get Currently Opened All Tabs In Browser ?

@ahkeravi You can’t have a PHP application read tabs from a browser running on a user’s computer. You definitely can’t take screenshots of what’s open in those tabs.

That would be a huge security vulnerability if any website could read your open tabs’ URLs and take screenshots of their contents, don’t you think…?

Activity icon

Replied to Upgrade Laravel 5.5 To 5.5.42

@sigalz https://laravel.com/docs/5.5/upgrade#upgrade-5.5.42

To upgrade the actual framework version, so long as you have "laravel/framework": "5.5*" in your composer.json file, it should just be a case of running composer update laravel/framework from the command line.

Activity icon

Replied to Domain Verification

@phpmuhammed What do you mean by, “a Twitter profile with the domain name”? Twitter profiles are made up of up to 15 alphanumeric or underscore characters; not domain names.

Activity icon

Replied to Is Service Pattern And Repository Pattern The Same?

@PyaeSone No, they’re not the same.

A repository is for accessing objects in a collection-like manner.

A service is a class with methods for executing business logic, that may be coordinate various other services (such as multiple repositories) to perform a single action or get a single result.

Jan
26
2 months ago
Activity icon

Replied to Change IP Address On Each Request To Avoid Ban While Scrape

@christopher Have you actually checked to see if you’re allowed to scrape Amazon? As I imagine you won’t be and it’s against their terms of use. Most websites prohibit scraping of their content due to copyright.

The fact that Amazon is banning your IP address suggests that Amazon doesn’t really want people scraping data en masse.

Activity icon

Replied to How To Avoid Duplication Of Code

@naveedali Mobile apps use APIs to communicate with web apps. You can’t embed a PHP application in an iOS or Android app that shares its codebase with an actual web app.

Jan
20
2 months ago
Activity icon

Replied to What Are You Using Laravel For?

I’ve worked with Laravel for about six years now (since the 4.0 beta) and have used it for applications big and small.

Present-day, I’m using Laravel for a large RESTful API that will be slowly replacing a legacy (15+ year) monolithic e-commerce platform. In my spare time, I use Laravel for a “proper” SaaS (a self-service video on demand platform) and a multi-tenant CMS (think Squarespace or Wix, but for a really niche market).

Jan
19
2 months ago
Jan
13
2 months ago
Activity icon

Replied to Slightly Different Versions Of PHP And Laravel.

@swimmer Use something like Homestead so that you have the same version of PHP (and other software) in a self-contained environment on each of your computers.

Ideally, you should have the same version of PHP (and things like MySQL) in your development environment as you do on your production server.

Jan
06
2 months ago
Activity icon

Replied to How To Secure Front-end And Back-end Project ?

@browniecoffee Security in what context? Application security? Server security?

You can never be too secure. There’s no magical threshold you can cross where your application goes from being “not secure” to “secure”.

Activity icon

Replied to Put File Into Storage Directly From The Content

@osukono Files are just bytes. If you’re getting an audio file from Google’s API, then you’ll be able to get the contents as a string and stream that to a file in your own application’s storage.

However, I’d check with Google first to see if you’re actually allowed to store their data on your servers.

Activity icon

Replied to How Can I Lock A Laravel Template?

We must be able to add a key and the template should work only if it has a legit key.

@hardbyte How do you expect that to work? PHP is just code executed by a server. Whatever “restrictions” you put on it, if you’re giving the code to a customer then there’s nothing stopping them just removing your license key-checking code.

Laravel products like Spark and Nova don’t ship with a notion of “license keys”. You need a purchase a license to be able to download the source code, but once downloaded there’s nothing stopping a nefarious user from just installing it in multiple projects on multiple servers.

Whatever limitation you put in, someone will crack it.

Activity icon

Replied to GetRouteKeyName Is Not Working

@oxbir If you’re getting a, “Trying to get property of non-object” error message, then it’ll also give you a file and a line number. That’s where your problem is.

Jan
04
2 months ago
Activity icon

Replied to How Would You Create A File On Amazon S3 And Write The Contents To It?

@vardhan_kspl I’m not sure what the problem is?

Create a file and keep a handle to it, then you’ll be able to stream contents to it: https://laravel.com/docs/6.x/filesystem#storing-files