martinbean

martinbean

Member Since 4 Years Ago

Newcastle upon Tyne, UK

Senior Developer at Visualsoft Ltd

Experience Points 489,605
Experience Level 50

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 467
Lessons
Completed
Best Reply Awards 668
Best Reply
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.

16 May
1 week ago

martinbean left a reply on Testing Gate Policies

@chrisblackwell If you look at a policy, they’re just plain ol’ PHP classes (“POPOs”), so you can just test their methods by passing a user and a model under test:

class ArticlePolicyTest extends TestCase
{
    use RefreshDatabase;

    protected $policy;

    protected function setUp()
    {
        parent::setUp();

        $this->policy = new ArticlePolicy;
    }

    public function testUpdate()
    {
        $user = factory(User::class)->create();
        $article = factory(Article::class)->create();

        // Assert whether user should or should not be able to update article
        $this->assertFalse($this->policy->update($user, $article));
    }
}
14 May
1 week ago

martinbean left a reply on In Axios Request I Got Has Been Blocked By CORS Policy Error

@mstdmstd The resource at example.com:9090/searchWeb needs to add the Access-Control-Allow-Origin header with the value of the domain where /website-blogs is hosted.

13 May
1 week ago

martinbean left a reply on PHP Vs Python- Which Is The Best Programming Language For Development?

@judi Given this is your first post on a PHP-related forum, I’m going to guess you’re trolling.

martinbean left a reply on How Do You Install A Vue.js Package Into Laravel?

@connecteev Read the install instructions for the package.

08 May
2 weeks ago

martinbean left a reply on Screen Reader Accessibility Inquery

I just want to be sure I'm using the right framework for the job

@stormdragon2976 Laravel is a server-side framework. It delivers HTML to an end user. What’s in that HTML, is up to you.

martinbean left a reply on ERP Open Source

@jmistani And you’re pretty salty if your first post is to write a comeback to a four year old post of mine.

07 May
2 weeks ago

martinbean left a reply on How To Set Two Isset In View Laravel?

@raviawasti The same way you would in raw PHP:

@if(isset($data['location']->name) && isset($data['subject']->subject_code))
    <!-- is set -->
@endif

The isset function can take multiple arguments though, so you could pass all your conditions and it will only return true if all arguments are set:

@if(isset($data['location']->name, $data['subject']->subject_code))
    <!-- is set -->
@endif

You can also use Blade’s shortcut @isset directive:

@isset($data['location']->name, $data['subject']->subject_code)
    <!-- is set -->
@endisset

martinbean left a reply on Quering A Ldapserver And Synchronize Laravel Database

@ottaviane Laravel’s auth providers and guards and created so that you shouldn’t need to modify your LoginController code to support a different authentication mechanism.

Reading your problem, it sounds like you want to create a new user provider that essentially authenticates using LDAP and synchronises users to a local database table.

I’d go down the route of treating your LDAP directory as a third-party user store, similar to authenticating via OAuth. So your local users might contain the ID of your user in the LDAP directory, name, but no authentication data such as email address and password (as these may change in your LDAP directory).

Laravel has some documentation on creating custom user providers, but I imagine someone will have already created an LDAP user provider for Laravel that you can add to your project, and configure for your installation.

03 May
3 weeks ago

martinbean left a reply on Referencing All Models At Once In A Controller?

@zaster No. You need to import the classes you need in each file.

If you’re needing to import a lot of classes, then it may be you’re trying to do too much need to break your file into smaller objects that have narrower responsibilities.

martinbean left a reply on Bulk Mailing With Laravel - Right Approach

@thebigk The best approach is to use something like MailChimp or Campaign Monitor. They have the infrastructure, white-listed IPs, and so on.

martinbean left a reply on How To Override Illuminate\Database\Connection Class

@pdm91 Check out Laravel Debugbar. It logs queries executed on your page, how long they’re taking, etc.

martinbean left a reply on Is There A Way To Dynamically Set A Guard Provider?

@alex29 Yeah, this is the very reason I don’t create multiple models to represent a user in my applications.

A user is a user. Use roles and authorization to determine what parts of your application a user can interact with. If a user has a “employer” role, then you can restrict them to only be able to view employer routes and resources.

As soon as you create another “user” model, you have to create additional auth guards, providers, controllers, views, etc and it just becomes a mess to authenticate a user.

02 May
3 weeks ago

martinbean left a reply on Can Anyone Give Example Of Confirm Password Validation?? I Am Using Following Way But Not Working Properlly.

@MUNAZZIL - @munazzil That won’t work. If you have the following rule:

return [
    'password_confirmation' => 'confirmed',
];

Then Laravel is going to check the value of password_confirmation matches the value of a field named password_confirmation_confirmation.

Docs: https://laravel.com/docs/master/validation#rule-confirmed

martinbean left a reply on Is There A Way To Dynamically Set A Guard Provider?

@alex29 How are you intending to select which guard is needed before actually authenticating the user?

martinbean left a reply on Auth Middleware In Routes Vs In Controller

@hal9k No. You only need to define middleware once—either in a route group, or in your controller’s constructor method.

martinbean left a reply on Process 10000 Of Jobs Per Minute.

@mehedi Well, if jobs take a second or so to process, and you need to process tens of thousands of them, then you need to scale horizontally, i.e. have lots of workers working at the same time like @devfrey says.

martinbean left a reply on Intercepting Laravel Login Error

@ottaviane What is it you’re wanting to do?

martinbean left a reply on Redirect To Intended Page After Login - Laravel 5.7

I don’t think you ever need to put url.intended to session manually. That’s exactly what intended() method does.

@roborobok Wrong. It either redirects to what’s in the session under the url.intended, or redirects to the URL given as the default.

Source: https://github.com/laravel/framework/blob/e6c8aa0e39d8f91068ad1c299546536e9f25ef63/src/Illuminate/Routing/Redirector.php#L98-L112

martinbean left a reply on I Can't Understand The Service Container!

@MohamedAladdin If you think of Laravel, it’s made up of components. So things like queuing, the filesystem, are all components that can have their implementations “swapped” (so for queueing, you can use SQS, Redis, etc).

To make these components available (and swappable), they’re placed in a container. A container is just a central registry of components that you can add things to, and request things from. So when you need to work with queues, you can say the container, “Hey, give me what’s registered for queues”.

To add things to the container, you use service providers. These are just classes that bind things to a key. So you can think of the the container as an array: you set a “key” using a service provider, and can then request a “key” elsewhere in your application.

martinbean left a reply on How To Get Only One Row Of One To Many With Condition?

@aarad You can use any query builder methods, including take():

$products = Product::with(['inventories' => function ($query) {
    $query->where('count', '>', 0)->orderBy('id')->take(1);
}])->orderBy('inventories.price'')->get();

Although I’m not sure the orderBy('inventories.price') will work, as you’ll still have a collection of Inventory models (even though they’ll only be one), as unfortunately that’s just how a has-many relationship works.

martinbean left a reply on Redirect To Intended Page After Login - Laravel 5.7

@nasirnobin You need to set the intended URL before redirecting to login.

$request->session()->put('url.intended', url('/intended-url'));

martinbean left a reply on Catching Wildcards In Routes

@MattB You need to decide how you’re serving images. You can’t upload them to your public directory, but then access the image via a Laravel route.

The server checks if the requested URL is a file. If it is, it just returns that file. If not, then it passes the request through Laravel.

So if you upload a file to /public/images/test.jpg, and then request example.com/images/test.jpg, then the server’s just going to return the test.jpg file without invoking Laravel.

30 Apr
3 weeks ago

martinbean left a reply on Get Comments On My Company Facebook Page And Display Them On My Laravel Application

@mariomacedo You’ll need to authenticate with Facebook to allow a user to link their Facebook Page with your application. You’ll then get a token that you can make Graph API requests as that Page.

As for comments, comments on what? Everything in the Graph API has an object ID, so you’d need to know the ID of a particular object (i.e. a Post, Photo) before you could fetch photos from it. You can’t just say, “Give me all comments on anything on my Page”. I imagine because it goes against the core functionality of Facebook’s Page Manager.

martinbean left a reply on Catching Wildcards In Routes

@mattb I don’t really follow. What do you mean by “so it can be updated in the db”. So what can be updated in the database? What is it you’re trying to do?

martinbean left a reply on Catching Wildcards In Routes

@mattb If the image actually exists on disk in your public directory, i.e. you’re requesting site.test/images/test.jpg and a file exists at /public/images/test.jpg, then Apache/nginx will just serve that image directly without passing the request through Laravel.

If you don’t want users to be able to access images by their filename then don’t put them in your public directory.

martinbean left a reply on Catching Wildcards In Routes

@mattb What route did you use, what URL did you try, and what response did you get?

29 Apr
3 weeks ago

martinbean left a reply on Interfaces Again

@Mindexperiment You can’t bind multiple classes to a single interface. Laravel isn’t clairvoyant.

Given this code…

class PublishableController
{
    public function __construct(Publishable $model)
    {
        $this->model = $model;
    }
}

…how is Laravel supposed to know what “publishable” model you want to inject?

26 Apr
4 weeks ago

martinbean left a reply on I Need Structural Advices For A Complex Logic To Create A Calendar With Events

@leisure_webdev It sounds like you have a similar problem as I’ve been working on the past couple of weeks :D

So, you’d have one entity in your application: Event. This represents an event in your application. When fetching “events” from other data sources (Eventbrite, etc) you’ll convert their representations into an instance of your application’s Event entity. To do this, you’d use a data mapper to convert to/from your Event entity instance to a representation Eventbrite expects.

I don’t really know what your controllers are doing as to what operations you‘re performing but you’d have a DAO class for each service; a data mapper for each service; and one, single Event entity.

$eventbriteDao = new EventbriteDAO;

// Fetch event from Eventbrite.
// DAO will return event in Eventbrite representation.
$eventbriteEvent = $eventbriteDao->find($eventbriteEventId);

// Map the Eventbrite event to Event entity
$mapper = new EventbriteDataMapper;
$event = $mapper->toEvent($eventbriteEvent);

// You now have an Event entity, which you can call methods on
$event->getId();
$event->getName();
$event->getStartDate();

You can then do the reverse to persist the event to Eventbrite again:

$mapper = new EventbriteDataMapper;

// The mapper can convert Event entities to Eventbrite event instances again
$eventbriteEvent = $mapper->fromEvent($event);

// Use the DAO to save the Eventbrite event back to Eventbrite
$eventbriteDao->save($eventbriteEvent);

martinbean left a reply on Statelessness In REST - Not Keeping Sessions On The Server

@frumentius I don’t know your application, but when talking about “state” in terms of an API and it being “statement”, it means that one API request should have no knowledge of any API request that came before it.

So every time you make an API request, you need to tell that server who you are. Each and every time. The usual way to do this is with some form of token (be it a simple token stored against the user in the server’s database; an OAuth token; a JWT; and so on). You pass the authentication will your requests, and each time the server will look up the user that corresponds with that token and will go either, “Yes, that’s a valid user” or, “No, that token’s invalid. You’re unauthorised to perform this request.”

So…

  1. No, storing a token in a database is not making your API “stateful” if the user has to pass their token with every HTTP request they make to the API for authentication purposes.

  2. I don’t think so. A user would be able to pass the same token from multiple clients, would they not?

23 Apr
1 month ago

martinbean left a reply on What Is Your Laravel Design Pattern?

@lizeshakya I’m not sure what you mean by “design pattern” in your context. If you mean approach to Laravel projects, then I take a “DDD-lite” approach. I group models into directories based on the “part” of the application they’re in, and then create resource controllers around those models. Validation is put in form request classes and authorisation is handled by policies. Sticking to these conventions leads to slim controllers and easy-to-manage applications for me.

For me, it is being very difficult to implement SOLID design principle in Laravel application.

SOLID is just a way of approaching code. Laravel is very much open to using solid principles if you choose to.

How do you achieve SOLID principle in the existing project?

Well, that’s a difficult question to answer because it doesn’t have one, single answer. It depends on the project and what you’re trying to do with it. No one could possibly tell you how to implement SOLID in a project without knowing anything about the project itself or the current state of that project’s code.

My rough approach would be to whip models into shape. Models are the very core of your application; they are what your application is. If you have “bad” models, then all code you write from there is going to suffer. Define your models, and then go from there.

I’d then look at re-factoring any bad practices. Re-factor things to interfaces. Inject dependencies in classes. Bind things to the container. DRY out any code repeated in the codebase. Move logic from controllers to models. This steps should lead to a leaner, easier-to-manage codebase.

martinbean left a reply on Creating A Contact Form Without Controllers And Migrations

I'll need to run migrations then.. Am I right?

@roottech No. Why? What table do you think you would need to create?

Your store method would just take the submitted data and send it in an email: https://laravel.com/docs/master/mail

martinbean left a reply on Register With Either Phone Or Email

I have checked google and there are so many options I just need a simple and good one.

@successdav No one can choose for you. You’ll need to take a look at each service’s API and pricing and find which one feels the best fit for you and your project.

secondly cant I use a single input field for the process?

I never said you had to. You would have two separate fields for the email and phone number, and some way of hiding/showing them with JavaScript depending on which method of registration they choose.

martinbean left a reply on Register With Either Phone Or Email

@successdav Your form will have two inputs: one for the email address and one for their phone number. You’ll probably have some way of allowing the user to choose how they’re signing up (i.e. radio inputs for “email” and “phone”). In your register controller, you can then see what data you have and persist the data accordingly:

public function register(Request $request)
{
    if ($request->has('email')) {
        $user = User::createFromEmail($request->all());
    } else if ($request->has('phone')) {
        $user = User::createFromPhoneNumber($request->all());
    }

    $user->requestConfirmation();
}

You can add a requestConfirmation method to your User model that sends the confirmation, either by email or SMS, depending on what field is populated:

class User extends Authenticatable
{
    public function requestConfirmation()
    {
        if ($this->email) {
            // Send email asking to confirm account
        } elseif ($this->phone_number) {
            // Send SMS asking to confirm account
        }
    }
}

martinbean left a reply on Creating A Contact Form Without Controllers And Migrations

I have a contact blade, I want it to directly be sent to my email once the submit button is click.

@roottech You can’t do that without something server-side.

I was thinking if it would be possible to use a mailto: action directly from the blade file

You could start composing an email using a form, but you wouldn’t be able to have it automatically send.

martinbean left a reply on I Need Structural Advices For A Complex Logic To Create A Calendar With Events

@leisure_webdev The adapter was suggested as in your original post, you say you were consuming third-party APIs. So if you had an Event model in your application, you would have some code that fetches data from a third-party API (say, Eventbrite or Meetup), and then an adapter for each of those services to access properties using the interface of your event model:

class Event extends Model
{
    protected $fillable = [
        'name',
        'start_date',
        'location',
    ];
}
interface EventInterface
{
    public function getName();
    public function getStartDate();
    public function getLocation();
}
/**
 * @see https://www.eventbrite.com/platform/api#/reference/event
 */
class EventbriteAdapter implements EventInterface
{
    private $raw;

    public function __construct(array $raw)
    {
        $this->raw = $raw;
    }
 
    public function getName()
    {
        return $this->raw['name'];
    }

    public function getStartDate()
    {
        return $this->raw['start'];
    }

    public function getLocation()
    {
        return $this->raw['venue']['name'].' '.$this->raw['venue']['address'];
    }
}
// Fetch event from Eventbrite (or other third-party)
$result = fetchEventFromEventbrite();

// Wrap event in adapter
$adapter = new EventbriteAdapter($result);

// Pull out properties using interface
$event = Event::create([
    'name' => $adapter->getName(),
    'start_date' => $adapter->getStartDate(),
    'location' => $adapter->getLocation(),
]);

martinbean left a reply on Best Practices For Admin/Member Zone (controllers/models/prefix/roles, Etc)

@ankaroo If you’re creating “protected” sections of your website for different members, then you could just simply have a “role” property on your users and then use middleware/authorisation to restrict access to specific roles.

So for a members-only section, you could check if a user is a member or admin. For the admin panel, you would check the user has the admin role.

By default, after logging in a user is redirected to either the previous URL, or just the home page.

martinbean left a reply on Prerequisites Before Learning Laravel?

@michalis Just a basic knowledge of PHP, really. A knowledge of MVC would be handy, too.

For things like the service container, you should be able to find resources that explain what a container is and how it fits into applications, and then watch videos on Laravel’s implementation to see how it’s used in a Laravel application.

martinbean left a reply on How Much Of Code Syntax You Guys Remember?

@kuns25 It’s difficult to quantify, but as with anything, you’ll remember more the things you do often, versus things you don’t do as often.

Things like language syntax (i.e. placement of brackets) become second nature the more you work with it. What a class looks like, a function/method looks like, what a variable looks like, and so on.

Obviously things like learning a framework, you need to dig into to see what libraries of classes and functions/methods it provides, but I’m not thinking about PHP syntax if I’m looking into a framework/library. I’m looking at the class structure; its public API rather than syntax.

martinbean left a reply on How Do E-commerce Orders Process Work When Checkout?

Is this how it works for e-commerce?

There is no one way on how “e-commerce” works. How and when an order is created depends on your business rules. Some businesses (and software) create the order before payment is taken (so the order is “open”). Other create the order after payment has been taken (i.e. in a callback from a payment gateway).

22 Apr
1 month ago

martinbean left a reply on I Need Structural Advices For A Complex Logic To Create A Calendar With Events

@LEISURE_WEBDEV - > The problem is most of service methods returns multi dimensional arrays and it is tricky to validate all the returned data

Well, that’s why you would use Adapters, and adapt each third party’s representing to match what your application is expecting.

So you would define what an event looks like in your application (fields etc), and then create an adapter for each third-party service to access the data you need in a common format, no matter how the event is represented in the response from the third-party.

18 Apr
1 month ago

martinbean left a reply on Best Practice To Handle Integrity Violation Error For Unique Field

@psychosocial227 You could use an after validation hook to check if the post slug will clash with an existing one, and add an error message if so:

class StorePostRequest extends FormRequest
{
    public function rules()
    {
        return [
            // Your validation rules
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $this->ensureSlugIsUnique($validator);
        });
    }

    private function ensureSlugIsUnique($validator)
    {
        $slug = Str::slug($this->title); // Or however you generate slug for a post

        $count = DB::table('posts')->whereSlug($slug)->count();

        if ($count > 0) {
            $validator->errors()->add('title', 'Slug exists. Please use a different title.');
        }
    }
}

martinbean left a reply on Google Places Autocomplete Force Selection

@SEDI - @sedi No problem, happy to help :)

Do you know how can I get both country components, short_name and also long_name ?

You seem to looping over the address components returned from Google, and then “plucking” a value. From memory, I think it’s similar to the code in Google’s documentation.

You’ll need to tweak the loop so that when it hits the country component, you fill in both of your fields:

for (var i = 0; I < place.address_components.length; I++) {
    var addressType = place.address_components[I].types[0];

    if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];

        // This should set country short name to input with id=country
        document.getElementById(addressType).value = val;

        if (addressType == 'country') {
            // Set value of another input to country long name
            document.getElementById('id-of-country-long-name-input').value = place.address_components[I].long_name;
        }
    }
}
17 Apr
1 month ago

martinbean left a reply on Laravel 5.8 Call To Undefined Method Illuminate\Events\Dispatcher::fire()

@hmkoyan The error will have a stack trace that includes the file and line number.

martinbean left a reply on Would Like To Know Developers Experience(Coding) And Age?

@MUNAZZIL - > My question is that i would like to know this forum members age and experiences

@munazzil Why?

martinbean left a reply on Google Places Autocomplete Force Selection

@sedi You could have a “location” field that you bind the autocomplete component to, and then individual inputs for each address component (street, postal code, etc).

The location field’s value isn’t saved to the database, but each component input’s value is. This is what I do in an app of mine.

martinbean left a reply on Vue Component

@faizaltkl It could be a multitude of reasons. We can only guess unless you show us some code/

martinbean left a reply on Use Statement Without Laravel

@megaman Composer has its own autoloader. When you install a package using Composer, that package will specific how it should be auto-loaded (usually via the PSR-4 or older PSR-0 standard). So to get autoloading, you need to include Composer’s autoload file:

require 'path/to/vendor/autoload.php';

After that, you can then bring in the namespaces and classes you need:

require 'path/to/vendor/autoload.php';

use Carbon\Carbon;

$today = Carbon::today();