martinbean

martinbean

Member Since 4 Years Ago

Newcastle upon Tyne, UK

Senior Developer at Visualsoft Ltd

Experience Points 483,495
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 458
Lessons
Completed
Best Reply Awards 662
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.

18 Apr
4 days 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
5 days 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();

martinbean left a reply on Checking Keys For An Associate Array Form Request

@xtremer360 Then you can use bail. That will stop validation when it encounters a failure. You can place it in between rules like this:

return [
    'price' => ['required', 'bail', 'integer', 'gt:0'],
];

In the above example, the required rule will be ran. Then any rules after bail will stop after the first failure. So if the integer rule fails, Laravel won’t bother evaluating the gt rule.

15 Apr
1 week ago

martinbean left a reply on Should Eloquent Be In My Controller Or Model

@garet Again, it’s a matter of personal preference.

If you’re passing data from the request to modify the query that’s executed, then this lesson may be of help: https://laracasts.com/series/eloquent-techniques/episodes/4

Your controller would then look like this:

public function index(CustomerFilters $filters)
{
    $customers = Customer::filter($filters)->paginate();

    return view('customer.index', compact('customers'));
}

martinbean left a reply on Laravel

@psychosocial227 I’d suggest updating the thread title. “Laravel” doesn’t really say anything to people browsing the forum.

martinbean left a reply on Laravel Custom Rule Dependent On Other Request Params

@RODRIGUESBRUNO - No problem! Glad I was able to point you in the right direction :)

martinbean left a reply on Checking Keys For An Associate Array Form Request

@xtremer360 You can define “after” validation hooks, that run additional validation after the initial rules have been evaluated: https://laravel.com/docs/master/validation#after-validation-hook

martinbean left a reply on Store Session For Reseting Password

@sasafister I’m still not following, I’m afraid. When someone requests a password reset email in a Laravel application, they are directed to a page with a flash message saying an email’s been sent.

martinbean left a reply on Different Users Profile And Roles

if the user is on the seller registration form I will need to assign the seller profile and also the seller role, right?

@zfdeveloper Right. But you wouldn’t be creating the role again; just assigning a previously-created one?

$role = Role::find('seller');

$user->attachRole($role);
14 Apr
1 week ago

martinbean left a reply on Checking Keys For An Associate Array Form Request

@xtremer360 If you’re wanting to check submitted competitors are valid wrestlers, can you not just do this?

return [
    'matches.*.competitors' => ['required', 'array'],
    'matches.*.competitors.*' => ['required', 'array', 'exists:wrestlers,id'], // Checks each competitor ID is a valid wrestler ID
];

martinbean left a reply on Displaying Text In Table With Text Transformation

@markzimmer It depends how you’re intending users to input formatting. You can either save the HTML (<br>, <strong> etc), or preferably some other form of mark-up (like Markdown) that’s then converted to HTML in your views.

The less HTML users can submit and is stored in your database, the better.

martinbean left a reply on Store Session For Reseting Password

@sasafister I’m not sure I follow. What is it you want to display on the screen?

martinbean left a reply on Different Users Profile And Roles

@zfdeveloper No, that’s how I would model it. A user is a user, so you should only have one user model. You can determine what a user can do in your application using authorisation (and roles).

For the implementation, you should only need to create the roles for the permission package once, right? Yes, you’ll need to create a profile for each user (based on the type of user they are), but if you’ve created a seller role once already then you just need to associate that role with any new users.

12 Apr
1 week ago

martinbean left a reply on Dealing With Huge Tables And Pagination

@spacedog4 ~15 seconds to pull a subset of records sounds far too long. Your table is either very poorly defined, or you have an unoptimised query/queries.

Try using either the Laravel Debugbar or Laravel Telescope to inspect the queries you’re running. You may have an N+1 problem. If you don’t, then you may need to look at your database schema and how to better optimise it.

martinbean left a reply on What's The User Of \App\Console\Kernel's Protected $commands Variable?

@schemeza Yeah, it’s for manually registering commands if you prefer to do so, rather than them being automatically loaded.

Documentation: https://laravel.com/docs/5.8/artisan#registering-commands

martinbean left a reply on Alias For Model?

@ahoi You could create a Customer model that extends your User, but applies a global scope to restrict queries to users with the customer role:

class Customer extends User
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('role', function ($builder) {
            $builder->where('role', '=', 'customer');
        });
    }
}

martinbean left a reply on Laravel Custom Rule Dependent On Other Request Params

@rodriguesbruno In that case, it sounds like you want to use an “after” hook. That’s where you can run additionally validation, after the initial rules have ran:

class SomeRequest extends FormRequest
{
    public function rules()
    {
        return [
            'price' => [],
            'volume' => [],
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function () {});
    }
}
11 Apr
1 week ago

martinbean left a reply on Run Composer Via Artisan Command Or Job?

@KAY899 - @kay899 If you’re installing a plugin, install it and run composer update then? You only need to do this once: when you’re installing the package.

You should not but updating packages on a schedule. For example, if a package changes location or is removed from its repository, the next time your scheduled tasks updates dependencies, it’s either going to error or remove that package from your server. Either way, your application is going to crash.

martinbean left a reply on Axios Set BaseURL

How are you currently sending requests? Can you post some code where this happens?

martinbean left a reply on More Useful Form Validation Feature Tests

@JBREUER95 - > I just thought it would be cool to make a test based on the database structure.

Not really, because you’re then not testing how your application actually behaves.

If you update your database schema but don’t update validation in a controller that writes rows to that table, then you’re going to end up with bugs because your validation is no longer in line with the database schema.

martinbean left a reply on Overriding Values In Model Factories

@hfalucas A short-hand way is to just add a factory as an array value, i.e.

$factory->define(Article::class, function () {
    return [
        'category_id' => factory(Category::class),
    ];
});

This will only evaluate if you don’t provide an overriding value, and will evaluate by creating and returning the primary key.

// New category is created and primary key set as category_id
factory(Article::class)->create();
// New category is NOT created; given value used instead
factory(Article::class)->create([
    'category_id' => 42,
]);

This stops your factories from looking message with closures all over if you have a lot of relationships in your models.

martinbean left a reply on Laravel Custom Rule Dependent On Other Request Params

@rodriguesbruno You can simply move the bail rule further inside your array:

'price' => ['required', 'bail', 'numeric', 'gt:0'],
'volume' => ['required', 'bail', 'integer', 'gt:0'],

So that will make both price and volume are required, and will stop validation when the first rule after that fails. So if the numeric rule fails, Laravel won’t move on to the gt:0 rule.

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

It sounds like you want to employ the Adapter pattern. Your various services will fetch events from third-parties in their format. Each service would have its own adapter class that allows you to pull the data using a consistent interface:

interface EventAdapter
{
    public function getId();
    public function getName();
    public function getStartDate();
    public function getLocationName();
}
class ServiceOneAdapter implements EventAdapter
{
    private $raw;

    public function __construct(array $raw)
    {
        $this->raw = $raw;
    }
}
$events = $serviceOne->getEvents();

foreach ($events as $event) {
    $adapter = new ServiceOneAdapter($event);

    // Use adapter to fetch attributes and insert into your database
    Event::create([
        'name' => $adapter->getName(),
        'start_date' => $adapter->getStartDate(),
        'end_date' => $adapter->getEndDate(),
        'location' => $adapter->getLocationName(),
    ]);
}

As you can see, no matter what third-party service you fetch an event from, if you also create an adapter class for it then you can use the same methods to access the event data.

martinbean left a reply on Run Composer Via Artisan Command Or Job?

@kay899 Why are you trying to run Composer like this? What happens if Composer updates a package to a version that’s incompatible with your application and introduces a bug?

martinbean left a reply on Implemented Field Component - Per Page Filter Not Working

Any hints will be much appreciated.

You’re going to have to give us some hints as well. Show us some code. We can only begin to guess what the problem may be.

martinbean left a reply on More Useful Form Validation Feature Tests

You aren't really testing your own code, you are testing the validation rules Laravel provides.

Well, no. You’re testing how your application applies the validation rules Laravel provides.

Yes, it comes in handy when you remove a validation rule unintended but how often would that happen?

But it might happen. Just today I’ve literally had a test pick up an instance where I somehow managed to add a typo to a parameter. You don’t get burgled every day but you still buy home insurance, right…?

For the “repetitive” tests, you can leverage PHPUnit data providers. This allows you to re-run the same test case with different parameters each time. I use them in the case you highlighted: lots of fields having a required validation rule:

class CreateArticleTest extends TestCase
{
    /**
     * @dataProvider requiredFieldsDataProvider
     */
    public function testFieldIsRequired($field)
    {
        $this->createArticle([$field => ''])
                 ->assertValidationError($field);
    }

    public function requiredFieldsDataProvider()
    {
        return [
            ['headline'],
            ['summary'],
            ['body'],
        ];
    }

    private function createArticle(array $overrides = [])
    {
        $defaults = [
            'headline' => 'Test Headline',
            'summary' => 'Test summary',
            'body' => 'Test body',
        ];

        return $this->post('/articles', array_merge($defaults, $overrides));
    }
}

This will run the testFieldIsRequired case three times, once with each of the items from the data provider. I simply set the specified key to be an empty string, and assert that I get a validation failure.

10 Apr
1 week ago

martinbean left a reply on Tools / IDE Plugins To Identify N+1 Issues?

@shawnyv I tend to install the Laravel Debugbar in all Laravel projects.

It has a tab for database queries that includes a badge with the count in, so if I see a higher number that expected when browsing locally, I can see what queries are being ran and see if that number can be reduced through any optimisations.

martinbean left a reply on Check If A Driver License Is A REAL Driver License

@MARCELLOPATO - I don’t know what “GED” is, but you need a real reason for handling sensitive information on citizens such as their driving license.

martinbean left a reply on Check If A Driver License Is A REAL Driver License

@marcellopato Then you get in the realm of data protection laws, which most country has.

You can’t just have scans of personal documents like driving licences going through and being stored by your application. If your application is compromised, you’re opening yourself up to a lot of trouble.

martinbean left a reply on How We Capture The Request Body Into Our Controller When Someone Uses This Api?

@ncltours If the client is sending the data as JSON, then you can get it like this:

$data = json_decode($request->getContent());

But your API endpoint should be tightly defined as to what format it accepts data in, as you’ll then be able to parse it easier if you know what you’re working with.

09 Apr
1 week ago

martinbean left a reply on Middleware Dependency/order

Middleware is executed in the order that it is applied. If you need to execute a middleware class after the auth middleware, then specify it after the auth middleware.

In later versions of Laravel, if you absolutely must ensure middleware is ran in a particular order, then you can define the order in a $middlewarePriority property in the HTTP Kernel class:

https://github.com/laravel/laravel/blob/005ec1301e3600c0a5d5a8355495d4333cab138b/app/Http/Kernel.php#L65-L79

martinbean left a reply on What Are The Different Between Laravel Shedule And Queues?

@rangana Yes, you should use a queue. You want the email to be delivered as soon as possible.

martinbean left a reply on What Are The Different Between Laravel Shedule And Queues?

@rangana The clue is in their names.

  • Schedules are jobs that are scheduled to be performed at a certain interval, i.e. daily, weekly, monthly, etc.
  • Queues are for executing jobs as and when there’s capacity. You add a job to a queue, the queue processes jobs as quickly as it can.
08 Apr
2 weeks ago

martinbean left a reply on What Controller Should Be Responsible For Static Pages?

I’m a fan of the StaticPageController, too :)

martinbean left a reply on How To Parse Array In Resource Collections

@EUSAPXAI - @eusapxai Thanks! Glad I was able to help :)

05 Apr
2 weeks ago

martinbean left a reply on How To Parse Array In Resource Collections

@eusapxai You can use resources in resources. So you could create a “rating resource” and then use that to format your ratings:

class ProductResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'product_id' => $this->prd_id,

            // Snipped

            'ratings' => RatingResource::collection($this->ratings),
        ];
    }
}
class RatingResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'rating_id' => $this->rating_id,

            // And so on
        ];
    }
}

martinbean left a reply on Send Email With Event/Listener, Or Job?

@pramanadiputra Use a listener. You’re wanting to do something off the back of something happening.

Jobs are for wrapping up chunks of work that you need to do asynchronously, and can be dispatched from either a controller or a console command.

04 Apr
2 weeks ago

martinbean left a reply on A Package With Jobs

@andreich1980 Yeah, it’s scenarios like this that I wish Composer supported “peer” dependencies (happy to be proven wrong if it does already though).

For example, your package itself doesn’t require the entire Laravel framework, but it should only be installed in a “parent” project that also requires Laravel.

In your case, the version numbers of illuminate packages are kept in line with the Laravel framework itself. So you’ll need to require illuminate/config=~5.8 (or whatever the minimum version of Laravel is that your package supports).

martinbean left a reply on Correct Way Of Calling Eloquent Methods

@garet Eloquent models cover a few design patterns, which is why you’re able to do the same thing in multiple ways.

If you’re wanting to fetch multiple models, then you can use all():

use App\Customer;

$customers = Customer::all();

If you need to add conditions, you’ll then need to use get() instead of all():

$customers = Customer::where('organization', '=', 'ACME')->get();

For fetching a single model, you can either retrieve it via its primary key using find:

$customer = Customer::find(1);

Or you can find a single customer using some conditions and first():

$customer = Customer::where('first_name', '=', 'John')->first();

martinbean left a reply on Error 500

@luisdev So check your error log.

martinbean left a reply on Prevent Laravel From Removing Trailing Zeros

@n1smo Yeah, SQLite does some funky things with “typed” columns, such as numbers and dates.

martinbean left a reply on WhereRaw Parameter Binding With Postgres Not Working

@tobz.nz You seem to be trying to combine both a “raw” expression and an expression with a binding. You can’t do this—you need to do one or the other.

If you look in the SQL, your statement ('INTERVAL ? minutes') is being parsed as exactly that. You’ll need to use your $minutes variable inline in your statement, i.e.

Device::whereRaw("last_seen_at < NOW() - INTERVAL '{$minutes} minutes'")->get();

Needless to say, using a user-provided value for $minutes is extremely risky, so make sure you cast it to a positive integer before using it in any SQL statement:

$minutes = (int) $minutes;

martinbean left a reply on Prevent Laravel From Removing Trailing Zeros

@n1smo An integer is a number without a “mantissa” (a number after a decimal point). You can not store a decimal number like 1234.10 as an integer—it’ll get converted to just 1234.

Unfortunately, if you want to store “floating point” numbers with trailing zeroes then you’ll need to update the database column to be a string (varchar if MySQL) type column. Even if you change it to be a decimal/float, any leading zeroes will be truncated because 1234.1 is the same as 1234.10 to a computer.

03 Apr
2 weeks ago

martinbean left a reply on DB Design For Twitter Like Private Messaging System

This doesn't seem to be working for me.

@thebigk I can’t see where you’re actually querying the conversations? You’ve posted migrations and models, but no controller code?

Also, on a side-note: the table for your Conversation model should be named just conversations, not “conversations_master”.