martinbean

Freelance Developer & Consultant at MCB Web Design

Hire Me

Experience

261,775

387 Best Reply Awards

  • Member Since 2 Years Ago
  • 265 Lessons Completed
  • 1 Favorite

26th May, 2017

martinbean left a reply on Best Practice For HTTP Redirect • 2 days ago

@DrewRoberts Glad to have helped! :D

martinbean left a reply on Best Practice For HTTP Redirect • 2 days ago

@DrewRoberts I’d set up a regular expression pattern for the quote parameter. You’ll can then pass it along like this:

Route::get('quotes/{quote}', [email protected]')->name('quote.show');

Route::get('{quote}', function ($id) {
    return redirect()->route('quote.show', $id);
})->where('quote', '[0-9]{7,}');

martinbean left a reply on Deploying Laravel App To Both App And Back-end (queue) Servers Question • 2 days ago

@karni It’s going to be hard for any one to answer because we don’t know what your application does, how heavy it uses queues, your hosting provider, or budget.

martinbean left a reply on Sum Column • 2 days ago

@mayna Right? So use the format I posted above, but substitute the model and column names for yours.

martinbean left a reply on Polymorphism: Why Should I Violate Database Design? • 2 days ago

@ZetecVan Damn, just seen that. Wonder why @pedro.gaspar decided to reply to a year-old thread in that case :-/

martinbean left a reply on View Files Inside Public, Is It BIG Security Risk? • 2 days ago

@maxnb View files should be stored under resources/views, yes.

Why the package author decided to place them under public I don’t know, as I don’t know what package it is, not was I sat with the author when they made that decision.

martinbean left a reply on Update To Laravel 5.4, Class Mailer Does Not Exist • 2 days ago

@yagogak You’re probably calling app('mailer') or similar somewhere in your application. Your stack trace isn’t formatted nicely, so can’t really see where the issue is.

martinbean left a reply on Sum Column • 2 days ago

@mayna What’s not to understand? You call sum() with the name of the column you want to sum.

SomeModel::where('column', '=', 'value')->sum('column');

martinbean left a reply on Polymorphism: Why Should I Violate Database Design? • 2 days ago

@tylernathanreed Well you have a decision to make: go for the “perfect” database schema that will make queries more complicated and harder to implement in Eloquent models. Or just use polymorphism how it’s implemented in Eloquent and get on with building something of value to your client/employer.

Yes, the way polymorphism is implemented in Eloquent may not be the “best” way, but are the downsides really worth causing decision paralysis? Is your database going to explode if you use polymorphism? Are you really going to be changing model/table names? Are you really going to be changing the primary keys of records referenced in a polymorphic relationship (I hope not)? Are these issues so difficult that they can’t be solved with an UPDATE statement if you did change a model/table name or primary key?

martinbean left a reply on Sum Column • 2 days ago

martinbean left a reply on MVC Where Does The DB Logic Go? • 2 days ago

@Bartude Models are the “guts” of your application. They should represent something in your application, and have the methods to perform operations that thing can do. That’s why creating models from things is called modelling: as you’re modelling something in your application that exists in the “outside” world.

Take an order for example. You might cancel an order, or ship an order. So there would be methods named such on an Order model:

class Order extends Model
{
    public function cancel()
    {
        // Operation to cancel order
        // May be as simple as setting a column on the table like this:
        $this->update([
            'status' => 'cancelled',
        ]);
    }

    public function ship()
    {
        // Shipping an order may require creating a Shipment
        return $this->shipments()->create();
    }
}

Your controllers should then just be calling methods on your models:

Route::post('orders/{order}/ship', [email protected]');
class OrderShipmentController extends Controller
{
    public function create(Order $order)
    {
        $shipment = $order->ship();

        return view('order.shipment.show', compact('order', 'shipment'));
    }
}

Keeping logic in one place (models) also has the benefit that it can be re-used, in say multiple controllers or even multiple contexts.

If you imagine you could also ship an order from the command line, how would you do that if you put all the “logic” in a controller action? Copy and paste? What if two controller actions need to perform the same operation. Copy and paste again? No. By wrapping logic up in methods on the model class it belongs to, you can re-use them:

class ShipOrderCommand extends Command
{
    protected $signature = 'order:ship {order}';

    public function handle()
    {
        $order = Order::findOrFail($this->argument('order'));

        $order->ship();

        $this->info('Shipment has been created for order.');
    }
}

25th May, 2017

martinbean left a reply on Advice On Best Way To Store In Database • 3 days ago

@douglas_quaid You could make a pivot table, but I fail to see how that would save space? You’d have another table and twice as many rows!

Yes, you’d want to store the duration of a video in your table.

Popularity, the algorithm is up to you to implement. You’ll need to define the criteria as to what’s “popular” in your application.

martinbean left a reply on Advice On Best Way To Store In Database • 3 days ago

@douglas_quaid The only thing from that list that I can see would be stored against a video is difficulty. It’s just a limited set of values, so could either be a text field or an enum. Things like length and popularity would be query scopes.

For example, if you wanted to find all videos 0–10 minutes in length, this would translate to something like:

Video::whereBetween('duration', [0, 10])->get();

23rd May, 2017

martinbean left a reply on How Do I Start A Project With An Already Built Database? • 5 days ago

@omobo There’s no reason why you can’t create Eloquent models for an already-existing database schema.

martinbean left a reply on Best Practice Defining Table Columns • 5 days ago

@hariso Create a migration to rename the column, then find/replace in your application.

I fail to see what benefit abstracting column names behind a constant/variable would bring? If anything, it would add more confusion. You may as well add getter and setter methods to your models.

martinbean left a reply on Laravel Socialite • 5 days ago

@lars6 Yes. You can either have rows in the users table with no passwords, and users can continue to log in with their LinkedIn account (as it’ll have the same ID). Otherwise, when signing in with LinkedIn, you can prompt the user to instead create an account on your site, and fill in the missing information (such as password).

martinbean left a reply on Register Controller Redirect To Login On User Already Exists • 5 days ago

@murlidharfichadia@gmail.com I’m struggling to understand what you’re trying to do.

Do you just want users to be able to sign up with an email address ending in @organisation-name.com? If so, just create a validation rule for that and then register the user as normal once validation passes.

martinbean left a reply on Which Is A Better Way To Pass Function Parameters? • 5 days ago

@thecorp I’m not really au fait with the internals of PHP, but I think objects are passed by reference rather than copy.

In PHP 4, I remember having to explicitly pass by reference (using the &$var syntax), but think the default was changed to reference in PHP 5.

martinbean left a reply on Trying To Get A Post With Comments And User Name • 5 days ago

@WaleedIkhlaq The error message is telling you the problem: you have two comments() methods in your Post class.

martinbean left a reply on How To Use JWT Without Using Any Packages? • 5 days ago

@Hamelraj By implementing the RFC from scratch yourself: https://tools.ietf.org/html/rfc7519

Why you would want to, I don’t know though.

martinbean left a reply on Trying To Get A Post With Comments And User Name • 5 days ago

@WaleedIkhlaq You’ll have an easier time sticking to Laravel’s conventions for naming relationships.

A Post has many Comments, which belong to a User. Given this set up:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}
class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

You can then query a post’s comments and users like this:

$comments = $post->comments()->with('user')->get();

You could also eager-load the user relation on comments if you always wanted the user returned with a comment:

class Comment extends Model
{
    protected $with = ['user'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Then your query would be simplified:

$comments = $post->comments;

martinbean left a reply on Which Is A Better Way To Pass Function Parameters? • 5 days ago

@thecorp Can’t really comment without context.

Personally, I pass model objects as the benefits of type-hinting (and making sure a method gets what it’s expecting) far outweighs the microseconds—if any—passing an object over a primitive costs in terms of performance.

martinbean left a reply on Authentication For Multi-tenant Application In Laravel 5.4 • 5 days ago

@Damen You don’t need to create a new guard or modify Laravel’s authentication at all. All you really need to do is add a “where” clause to your login query.

Using Laravel’s LoginController, you can do this by overriding the credentials() method. This specifies the array that should be passed to Auth::attempt(). You can modify it to include the current company by doing something like:

protected function credentials(Request $request)
{
    return $request->only($this->username(), 'password') + [
        'tenant_id' => app(Tenant::class)->getKey(),
    ];
}

This means you can also use the in-built login routes:

Route::get('login', 'Auth\[email protected]')->name('login');
Route::post('login', 'Auth\[email protected]');
Route::post('logout', 'Auth\[email protected]')->name('logout');

martinbean left a reply on Upgrade Lumen App To Laravel 5.4 • 5 days ago

@doobz Lumen and Laravel are two different frameworks. How can you upgrade Lumen to Laravel?

21st May, 2017

martinbean left a reply on Advice For Laravel Beginner • 1 week ago

@Ic23 If you want to improve your skills, learn PHP itself. It’ll make you much more adept at learning frameworks (including Laravel) and also improve your skills with WordPress.

martinbean left a reply on How To? • 1 week ago

@gustav1105 I don’t understand what you mean. A controller would just retrieve a model instance, usually via route–model binding. So I’d have something like this:

class ArticleController extends Controller
{
    public function show(Article $article)
    {
        return view('article.show', compact('article'));
    }
}

If you wanted to retrieve models based on something other than a primary key, you can implement the getRouteKeyName() to change this:

class Article extends Model
{
    public function getRouteKeyName()
    {
        return 'slug';
    }
}

I think the use of repositories and services in this instance is just complicating things. I seldom use repositories in projects, and definitely not “services”.

20th May, 2017

martinbean left a reply on How To? • 1 week ago

@gustav1105 I’m really struggling to understand your question, especially:

these two models need to be used either as each or as a combination of the two, or where relevant only parts of one or the other or a combination of parts of each.

The idea of models is they’re supposed to represent something in your application. Therefore, I see modelling as one of the most important parts of creating an application. If you have weak or awkward-to-use models, then that problem’s going to be throughout your application.

Once you’ve defined your models as accurately as possible, you can then create resource controllers around them. Resource controllers have a set number of methods (index(), create(), store(), show(), edit(), update(), and destroy()). If you find yourself needing methods other than these, then chances are that’s another model waiting to be defined.

So my process is straightforward:

  1. Define a model.
  2. Create a resource controller for that model.

Most of my Laravel applications are structured in this way. I can’t remember the last time I created a controller method that wasn’t one of the resource ones defined above. My controllers work with one model at a time, and I know what model it is and don’t have to do any juggling that you would be doing with the user and profile models from the sounds of it.

19th May, 2017

martinbean left a reply on Customer, Services And Prices • 1 week ago

@jairo Looks fine to me too. It’s how I would have approached it if pricing for each service is unique to each customer.

You could also store a price against the service as a “base” price and make the price column in the pivot table nullable. If the customer has their own pricing for the service then use that, otherwise if it’s null you can fall back to the service’s base price.

18th May, 2017

martinbean left a reply on Forum And Comments Spam • 1 week ago

@noreason Why implement your own? This is just reinventing the wheel, and it means you’re going to have to create everything from scratch—including spam checking.

With third-parties services, they’ll usually already have these features nailed due to the volume of posts they process. If not, a community project like phpBB, if it doesn’t offer spam checking out of the box then there’s a good chance they’ll be a ready-made plugin to do what you need.

martinbean left a reply on Policy Methods Automatically Calling • 1 week ago

@s4uron How would you authorize the index() action? It’s a listing of many resources, not just one.

martinbean left a reply on Policy Methods Automatically Calling • 1 week ago

@s4uron You can already do this. If you look in the base controller class, you will see it imports a trait called AuthorizesRequests. This trait includes a method called authorizeResource() which will authorise all methods in a resource controller.

Example:

class ArticleController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(Article::class);
    }

    // Resource methods like index(), create(), store() etc.
}

The controller methods are mapped to policy methods like so:

  • show to view
  • create to create
  • store to create
  • edit to update
  • update to update
  • destroy to delete

martinbean left a reply on Delete Foreign Key With Migrate Reset? • 1 week ago

@kingsley What about it?

martinbean left a reply on IsEmpty () Method Does Not Work • 1 week ago

@vAlfred88 Well the problem is you’re trying to call a isEmpty() method on an Eloquent model

In the view, I guess you’re trying to check if there was an order model found but this is redundant as you’re retrieving the model with findOrFail(). If there isn’t a matching model, then this will throw an exception, so your view would never be rendered with an “empty” model.

martinbean left a reply on Optimize Slow Login On Website • 1 week ago

@samalapsy You need to find your bottleneck (the reason log ins can take up to 2 minutes). We don’t know anything about your application, what it does, how it’s structured etc so can’t make any suggestions.

If your login process is getting slower the more users you have, then that suggests maybe a N+1 problem somewhere.

17th May, 2017

martinbean left a reply on Testing With User Roles • 1 week ago

@rugavy No problem :)

martinbean left a reply on Route::get('foo'); Vs Route::get('/foo'); • 1 week ago

@ozmnow Just preference, as they’ll both resolve to example.com/foo as you’ve found. I prefer the non-prefixed version—one less character to type!

martinbean left a reply on Testing With User Roles • 1 week ago

@rugavy Yeah, I’d approach it in the similar way. In fact, I have done in one of my own applications.

It’s a video on demand site so there’s lots around what users can and can’t do based on various conditions. Is the user a guest? Has the user rented the title? Is the user subscribed to the channel the title belongs to? These have their own tests named as such, i.e.

  • test_guest_cannot_see_video
  • test_user_cannot_see_video
  • test_user_can_see_video_if_has_active_rental
  • test_user_cannot_see_video_if_rental_has_expired
  • test_user_can_see_video_if_subscribed_to_channel
  • test_user_cannot_see_video_if_subscription_has_expired

Under the hood, these use Laravel policies, but I prefer testing the logic in situ rather than writing unit tests for a policy class.

16th May, 2017

martinbean left a reply on Laravel Identity Providers And Single Sign On • 1 week ago

@allw You can authenticate users however you want by creating a custom user provider: https://laravel.com/docs/master/authentication#adding-custom-user-providers

martinbean left a reply on Laravel Cashier: Failed Registration Redirect? • 1 week ago

@dushaun That code isn’t very optimal. It’s checking if there’s an authenticated user twice: $request->user() and Auth::check() do the same thing.

Re-reading your problem:

how would you go about writing middleware to redirect the failed registered user to their account page to update their card information

I wouldn’t. This isn’t the job of middleware. Middleware is for taking in HTTP requests and optionally manipulating that request before sending a response. A payment failing is an application event. You should throw an exception if a payment fails, and redirect when catching that exception.

redirect a guest to the billing page if they try to access certain pages for subscribed users.

How would a guest be able to access the billing page? Surely the billing page would only be visible to logged in users?

martinbean left a reply on Laravel Cashier: Failed Registration Redirect? • 1 week ago

@dushaun That if() statement doesn’t look right. There’s no && or || in between ! $request->user()->subscribed('subscriber') and ! $request->user()->subscribed('premium').

15th May, 2017

martinbean left a reply on Method Parameters • 1 week ago

14th May, 2017

martinbean left a reply on How To Decrypt Hash Password In Laravel • 2 weeks ago

@ershakti If a user forgets their password they should reset it, not have their current one emailed to them. As mentioned, this is a really bad practice from a security point of view, as if someone gets access to one of your website users’ inbox, they can just request their password.

Lots of people use the same password for multiple services, so if they have a password for the user’s account on your website, then they may have used the same password for their online banking account or other sensitive services. So you can see why sending passwords in plain text is a bad idea.

martinbean left a reply on Laravel Mutators Error Using Carbon:now • 2 weeks ago

@d3cypher That’s the right place to set the timezone, but as mentioned twice above, you need to use forward slashes, i.e. Asia/Manila.

12th May, 2017

martinbean left a reply on How To Decrypt Hash Password In Laravel • 2 weeks ago

@ershakti Passwords are hashed, not encrypted. That means they can’t be reversed into their plain text form. This is for security reasons.

If someone downloads your database, they shouldn’t be able to reverse each of your users’ passwords.

martinbean left a reply on Internal Server Error 500 • 2 weeks ago

they must be avoided, or avoided.

@closer01 They’re not giving you much choice! ?

11th May, 2017

martinbean left a reply on Internal Server Error 500 • 2 weeks ago

what do you recommend?

@closer01 Check your server’s error logs. It’ll be a PHP error or server misconfiguration. Whatever the cause, it’ll be written to your error logs.

martinbean left a reply on Return Value From Function Inside Controller To Another Function Inside Another Controller • 2 weeks ago

@ehab.aboshehab If you tells us what you’re trying to do rather than how you’re trying to do something, then we’ll be able to offer better solutions.

I can’t make any suggestions because you’ve named everything “first” and “second”, so I don’t actually know what your intent is.

martinbean left a reply on Validation 'same' Rule Not Working Like I Think It Should. • 2 weeks ago

@roerjo I think you’re looking for the exists rule instead.

If you have data coming in from a form, then you can just do this:

$this->validate($request, [
    'machine_code' => 'required|exists:codes,machine_code',
]);

martinbean left a reply on Return Value From Function Inside Controller To Another Function Inside Another Controller • 2 weeks ago

@ehab.aboshehab You should not be controller one controller from another.

Edit Your Profile
Update

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