martinbean

Senior Developer at MBL Solutions

Experience

402,955

573 Best Reply Awards

  • Member Since 3 Years Ago
  • 375 Lessons Completed
  • 1 Favorite

26th April, 2018

martinbean left a reply on I Have Two Dates That I Am Comparing In Validation To Check If User Is Old Enough, However The Validation Seems To Be Passing Over The Dates • 6 hours ago

@seamuswc You could use a combination of date validation and an after validation hook to check the age:

public function rules()
{
    return [
        'dob' => 'required|date',
    ];
}

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->userIsUnderage()) {
            $errors->add('dob', 'You must be 18 years or older to use this site.');
        }
    });
}

private function userIsUnderage()
{
    return Carbon::parse($this->dob)->age < 18;
}

martinbean left a reply on What Is The Proper Way To Store Stats Like Videos A User Has Started Watching And Completed Watching? I Am Looking For Your Opinions. • 7 hours ago

@aligajani So if your API endpoint is /api/user/videos, what happens if you want an API endpoint to show videos a user has uploaded…?

I run a video on demand site. For recording “views”, I have a VideoPlay model that records the start and end point a user watched a video. So if you wanted to see which videos a user has started watching, then you can have an endpoint that exposes those videos, i.e. /api/users/1/video-plays.

martinbean left a reply on How To Structure • 7 hours ago

@Aetrox On the other hand, it’s good that you are seeing opportunities to go back over your work and re-factor and opportunities to apply new knowledge as you gain it.

25th April, 2018

martinbean left a reply on Echo Is Not Defined • 1 day ago

@Galavant Without seeing more of your code…

  • Have you un-commented the Echo code from resources/assets/js/bootstrap.js?
  • Have you actually installed Echo via npm (and an appropriate driver, i.e. Pusher)?

If so, you’ll need to reference Echo as window.Echo, as I don’t think you’ll just be able to reference Echo in a Vue component and it know you actually mean Echo from the window object.

martinbean left a reply on How To Get The Second One? • 1 day ago

@haizone If your collection has numerical keys, then you could do:

$first = $collection->shift();
$second = $collection->shift();

This will modify the collection by removing the first two items, though.

martinbean left a reply on How To Structure • 1 day ago

The normal answer would be, you can normally do what you want, but for a beginner doing what i want ends mostly in chaos or worser.

@Aetrox Instead of running to the “cool” parts of the project, build it in phases. You need a good foundation before you can start hanging paintings.

I start off by defining my entities and creating models for them. I’ll then create resourceful controllers around my models, and Blade templates with “traditional” forms (i.e. that POST to the server). Once I have my application working like this, is when I’ll then look at adding any JavaScript-based functionality, such as Vue components.

Once you’ve got your application working without, you’ll find it’s easier to add enhancements such as AJAX.

24th April, 2018

martinbean left a reply on Why Model's $rule Is An Instance Variable ? • 2 days ago

@Cyrille37 Eloquent models don’t have a $rules property?

23rd April, 2018

martinbean left a reply on Suggestion On ERP Development • 3 days ago

i would suggest to use laravelfor your backend and VueJs as a frontend

@Rabie Why?

@marufalom Use the technology you’re team would be most productive with.

martinbean left a reply on Return Type For API Requests • 3 days ago

@devk Returning a JsonResource or Collection depends on whether you’re working with an endpoint that acts on a single resource, or multiple resources.

Authentication is acting on a single user resource, so shouldn’t return a collection.

22nd April, 2018

martinbean left a reply on Return Type For API Requests • 3 days ago

@devk What you’re doing is fine: you should return an appropriate object as JSON. It’s probably an idea to nest everything under a data key if returning a “raw” JSON response though, to make its “shape” consistent with Eloquent resources.

For logging in, you would normally use something like Passport to handle user authentication, which would return an access token and refresh token as a response.

20th April, 2018

martinbean left a reply on Restful Child Resources • 6 days ago

@RexT I’m a big fan of resource controllers, so use nested resources regularly.

If you have a group controller, then you’d have a group member controller which would receive the “parent” group as the first parameter of every method. The edit() method on the group member controller would edit an individual member within that group; the index() method on the group member controller would list all members within that group.

Use Artisan to generate your resource controllers (i.e. php artisan make:controller GroupMemberController --model=GroupMember --parent=Group) and it’ll create a stub controller with methods and arguments that’ll be helpful to look at.

martinbean left a reply on Real Estate Website Option In Laravel • 6 days ago

@pkundariya Yes. Have you tried searching “laravel real estate” in Google? About 415,000 results.

18th April, 2018

martinbean left a reply on Create A Job To Run Every Second • 1 week ago

@gasparyanyur What’s your actual use case? As the minimum timeframe for a cron job (and therefore Laravel’s scheduler) is a minute.

martinbean left a reply on Laravel For A Multiplayer Game Server. Recommended? • 1 week ago

@moprocto We can’t answer without knowing the load, number of players etc.

You’ll need to work out your requirements (such as number of supported players, how much load each player will put on the server) and then make an informed decision as to whether a Laravel-based game server will be performant enough.

martinbean left a reply on How Many Queries Should $model->save() Run? • 1 week ago

@thebigk It should, but it depends on your code. As you haven’t posted any, we can’t say. But there may be things like relations or model accessors that run queries to calculate their values adding queries.

The Laravel debugbar will show you the source of each query for you to investigate.

17th April, 2018

martinbean left a reply on How To Use Local Filesystem For Development But S3 For Production • 1 week ago

@simioluwatomi If you look further up in the config/filesystems.php file, there’s a default key that points to an environment variable:

'default' => env('FILESYSTEM_DRIVER', 'local')

So you can set FILESYSTEM_DRIVER=local in your .env file when working locally, and set FILESYSTEM_DRIVER=s3 on your production server and it will use S3.

16th April, 2018

martinbean left a reply on Membership Site • 1 week ago

Is it possible to achieve with lets say a Vue/laravel setup.

@wildside Absolutely :)

And you’re on the right site: Laracasts has plenty of videos covering both topics that will help you on your way to developing the application you want.

martinbean left a reply on GDPR Package • 1 week ago

@votemike You can’t wrap legislation up into a “package”.

The term “application” can be used in two contexts, as the legislation is applied to your web application, so it’s up to each developer as to how it’s handled.

martinbean left a reply on Laravel Echo • 1 week ago

The documentation explains the difference:

The here callback will be executed immediately once the channel is joined successfully, and will receive an array containing the user information for all of the other users currently subscribed to the channel. The joining method will be executed when a new user joins a channel, while the leaving method will be executed when a user leaves the channel.

martinbean left a reply on Using Vue Variable In Blade @include • 1 week ago

@Jam0r You can’t access Vue variables in PHP. PHP is server-side, Vue is client-side. The PHP process has already finished by the time view is instantiated.

13th April, 2018

martinbean left a reply on Need Suggestions About Portfolio • 1 week ago

@ruvaifamasood How can we suggest projects? We don’t know what you’ve worked on or what you want to work on.

Instead, decide what projects you want to work on and which of your past projects best demonstrate similar skills.

12th April, 2018

martinbean left a reply on How Do Create A Database Query To Use On Both Web And Api? • 2 weeks ago

@verism You could move the query to a method on a class, and then use that method in both your API and web controllers:

class ActorRepository
{
    public function paginate($perPage = 24)
    {
        return User::whereHas('roles', function ($query) {
            $query->where('slug', '=', 'actor');
        })->with(['roles', 'actorAttributes'])->paginate($perPage)
    }
}

You can then inject the repository and use its method in your controllers:

class ActorController extends Controller
{
    private $actors;

    public function __construct(ActorRepository $actors)
    {
        $this->actors = $actors;
    }

    public function index()
    {
        $actors = $this->actors->paginate();

        return view('actor.index', compact('actors'));
    }
}

11th April, 2018

martinbean left a reply on How To Order Results Of Related Models? • 2 weeks ago

@ajitdas You can order the related models amongst themselves, but you can’t order the parent, product category query by its children in this way.

I’m not sure how you’re expecting it to work, either. Surely a category has many products? If you’re wanting to sort by product price, why are you querying categories and not the products themselves? Otherwise, you’re going to need to fetch the same multiple times for each product in that category.

martinbean left a reply on How Do Create A Database Query To Use On Both Web And Api? • 2 weeks ago

@verism You could wrap the query up in a repository method that you use in both your web and API controllers.

For the filtering, I’d recommend watching this lesson: https://laracasts.com/series/eloquent-techniques/episodes/4

9th April, 2018

martinbean left a reply on Change Default Auth Controller Table To Another • 2 weeks ago

@wizjo Why do you need two models? Just use the users table and then use authorization to determine which parts of the application that user can view.

What happens if you need to introduce a third user type. Are you going to create a third user-like table, model, guard etc?

6th April, 2018

martinbean left a reply on Getting Preview Img From Embedded Video • 2 weeks ago

@jerauf A lot of video sites will implement a format called oEmbed. You’ll be able to call an API to retrieve details about a video, such as its thumbnail image URL.

martinbean left a reply on Route Model Binding - Optional RouteKeyName • 2 weeks ago

@rin4ik Feel free to use @rumm.an’s solution. I prefer to route requests based on parameters, and not “magic” happening in my models.

martinbean left a reply on Route Model Binding - Optional RouteKeyName • 2 weeks ago

@andyg1 Unfortunately not. You’ll need to define a second parameter name and use explicit route–model binding to resolve it, i.e.

// Use default key name for admin routes
Route::get('admin/articles/{article}/edit', 'Admin\[email protected]');

// Use a different slug-based parameter for front-end routes
Route::get('articles/{articleSlug}', '[email protected]');

// Create the binding for slug parameters
Route::bind('articleSlug', function ($slug) {
    return Article::whereSlug($slug)->firstOrFail();
});

5th April, 2018

martinbean left a reply on Does Lumen Offer Any Way To Call A Route Via Cli? • 3 weeks ago

@skunkbad Lumen is more for pure HTTP APIs, so doesn’t have support for Artisan commands out of the box. If you do need things like Artisan, scheduling etc, then it may be worth moving the application to Laravel.

4th April, 2018

martinbean left a reply on Authentication Issue With Admin & Front • 3 weeks ago

@muhammadjaved Why? An administrator is just a user with privileges. There’s no need to create a separate user model, controllers, views, auth guard etc.

What happens if you then need to add a third user type, say a moderator? Are you then going to create a third user model, controllers etc?

martinbean left a reply on Authentication Issue With Admin & Front • 3 weeks ago

@muhammadjaved A user is a user. Once authenticated, you should check they’re permissions to see if they can access the admin panel etc.

The Laravel documentation has a section on authorization: https://laravel.com/docs/master/authorization.

You could add middleware that you apply to your admin routes to check if your user is an administrator, and then policies to check the user’s permissions for each part of your admin panel.

martinbean left a reply on === Operator In Laravel • 3 weeks ago

@anoopmat24 As previously mentioned, === is a PHP language construct. It has nothing to do with Laravel. It simply checks two things are identical.

However, it may be that the versions of PHP on the two servers are configured differently, hence the different results.

So show us how and where you’re doing this comparison, and we may be able to point out why it’s not working as expected between environments.

2nd April, 2018

martinbean left a reply on What's The Easiest/best Way To Change Laravel To Use Php For .env ?? • 3 weeks ago

I want to dynamically switch the environment

@skunkbad Then use different .env files with these different environment settings.

martinbean left a reply on What's The Easiest/best Way To Change Laravel To Use Php For .env ?? • 3 weeks ago

[I] just had a few things that I wanted to change, like this .env file.

@skunkbad A lot of frameworks are starting to configure applications this way, because storing sensitive configuration values (like API keys and database credentials) should be done in environment variables. Parsing an .env file emulates this.

I know you've heard it before, but the Facades usage stinks to me.

Façades is a strongly-contested “feature”. But you don’t have to use them; you can inject your dependencies if you wish.

martinbean left a reply on Resource API • 3 weeks ago

It’s not really going to be possible.

If you have a route that returns 10 conversations for the authenticated user, how are you expecting to paginate the messages for the first conversation?

Instead, have a route that returns conversations for a user:

Route::get('conversations', '[email protected]');

And a route that returns the messages for a given conversations:

Route::get('conversations/{conversation}/messages, '[email protected]');

martinbean left a reply on Manage The Costs Of Projects (Digital Ocean + Forge + Envoyer) • 3 weeks ago

@leandromatos Maybe consider something like Heroku, which give you a number of hours a month free, so are perfect for hobby or staging apps.

Deployment to Heroku is as simple as git push, and you don’t have to worry about configuring and making server images as Heroku runs on a common Ubuntu 16-based stack and “build packs”, with PHP and Node.js build packs available.

martinbean left a reply on What's The Easiest/best Way To Change Laravel To Use Php For .env ?? • 3 weeks ago

@skunkbad Unfortunately Laravel uses .env files for configuration. The theory is, you’re supposed to use proper environment variables in your staging and production environments.

28th March, 2018

martinbean left a reply on What Happens If A Laravel "synchronous" Job Fails? • 4 weeks ago

@mathewparet Exactly the same as if the code was in your controller action itself.

martinbean left a reply on Fire Event When Vimeo Video Ended • 4 weeks ago

@abudo You’d be able to listen for the video ending using a native event:

document.getElementById('vimeo-player').addEventListener('ended', function (event) {
    // Video ended; do something
});

martinbean left a reply on Find All Instances In Model Where A Function Will Return True • 4 weeks ago

@moprocto As @Helmchen says, if you have your relations set up correctly you can query them using query builder methods. You could then wrap these queries up in scopes on your User model:

class User extends Authenticatable
{
    public function scopeCompletedGoalOne($query)
    {
        return $query->has('posts')->has('friends');
    }
}

You can then just use your scope to find users matching that criteria:

$users = User::completedGoalOne()->paginate();

martinbean left a reply on How To Use Default Guard For Login . • 4 weeks ago

@kfiroj236 Why are you making new login and register controllers? The whole point of guards is you can swap the authentication mechanism without touching those classes.

martinbean left a reply on Resource Routes, Route Model Binding, And Inheritance • 4 weeks ago

@andyg1 A resource controller doesn’t have to implement all methods.

For example, you say both the posts controller and user posts controller would have a delete() (actually it would be named destroy()) but would they? I can understand a user deleting their own posts so the UserPostController having a destroy() method, but who would be deleting the post if they accessed the PostController?

27th March, 2018

martinbean left a reply on Two Inter Dependency Repository Classes Causes Memory Leak • 4 weeks ago

@dniccum Yes, you have a circular dependency.

Your repositories shouldn’t really be interacting with each other. It’s the responsibility of client code to request the data it needs from multiple repositories, not for repositories themselves to be fetching data from other repositories.

Instead, create a service class that interacts with both repositories to fetch the data you need for a particular request.

martinbean left a reply on Display Content Based On Genre • 4 weeks ago

@splendidkeen Your genres table would contain all the available genres in your application, so would have columns like id and name.

When a user signs up a selects a genre, you would store the ID of the selected genre in the genre_id on the users table. You would then be able to use the genre relation on your User model to access the genre that user is associated with.

martinbean left a reply on Display Content Based On Genre • 4 weeks ago

@splendidkeen That’s really not how a belongs to relationship works. If a user chooses a genre, then the genre_id value for that user should be set to the id of the corresponding row in the genres table.

martinbean left a reply on Display Content Based On Genre • 4 weeks ago

@splendidkeen That doesn’t make sense. Why does a genres table have genre1 etc columns?

If there is a list of a genres, and a user can be associated with a genre, then you should have two tables: genres and users.

A User model would belong to a Genre model, therefore your users table would have a genre_id and your User model would have a genre relation:

<h1>{{ Auth::user()->genre->name }}</h1>

martinbean left a reply on Display Content Based On Genre • 4 weeks ago

@splendidkeen Why does your users table have genre1, genre2, genre3 etc columns if they can only belong to one genre, then?

martinbean left a reply on Relationship Betwen 4 Related Tables • 4 weeks ago

@khushbudadhania You’ll probably want to use the doesntHave() method on your contacts relation.

martinbean left a reply on I Want To Integrate Socialite And The Ability To Pay After The User Get The Data From Facebook And Google • 4 weeks ago

@Coffeework

  1. Register user via Socialite
  2. Use Cashier to handle a subscription to use your application.

martinbean left a reply on Display Content Based On Genre • 4 weeks ago

@splendidkeen Wouldn’t a many-to-many relation be more appropriate if a user can belong to many genres?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.