martinbean

martinbean

Member Since 4 Years Ago

Newcastle upon Tyne, UK

Senior Developer at Visualsoft Ltd

Experience Points 473,545
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 456
Lessons
Completed
Best Reply Awards 648
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.

22 Mar
6 hours ago

martinbean left a reply on Convert To Gate Or Policy?

@BEHNAMPMDG3 - @behnampmdg3 Because it would be done in a policy method:

if ($request->user()->cannot('view', $course)) {
    // User does not have permission
}

This will call a view() method on a CoursePolicy class (https://laravel.com/docs/master/authorization#writing-policies). That’s where you’d check if the course’s user ID matches the currently authenticated user’s ID:

class CoursePolicy
{
    public function view(User $user, Course $course)
    {
        return $user->id == $course->user_id;
    }
}
21 Mar
1 day ago

martinbean left a reply on Laravel Training

Hi, my name is Martin and I once ate a quesadilla.

martinbean left a reply on Need To Edit Auth::routes() Default Roots.

@femi You can put the auth routes in a route group if you want to prefix it with /admin:

Route::prefix('/admin')->group(function () {
    Auth::routes();
    // Will register routes as /admin/login, /admin/register etc.
});

If it’s for an admin panel and you don’t want users to be able to register, you can disable the register routes like this:

Route::prefix('/admin')->group(function () {
    Auth::routes(['register' => false]);
});

martinbean left a reply on Is It Possible To Check For Model Relation In Where Clause?

@mrvnk Maybe have a read over the “Querying Relationship Existing” section of the Laravel documentation on Eloquent: https://laravel.com/docs/master/eloquent-relationships#querying-relationship-existence

I think it might be what you’re after if I‘ve understood your problem correctly.

martinbean left a reply on Custom Database Queries Not Linked To Any Model - Where To Put

@appyapp The time you spend writing raw SQL queries and littering your controllers with them, could be time spent just creating models for your database’s tables and then getting the power of Eloquent…

If you really want to encapsulate some SQL queries then you can do just that, by wrapping them in a class:

class SomeStats
{
    public static function run($categoryId)
    {
        // Build SQL

        return DB::select($sql);
    }
}
class SomeController extends Controller
{
    public function someAction()
    {
        $stats = SomeStats::run($categoryId);
    }
}

But again, if you’re creating classes for queries to be re-used, then you may as well just create an Eloquent model class and get the power of the query builder.

martinbean left a reply on Passing Variables Between Two Observer/event Methods

An observer should be a self-contained class and not be manipulating things in the framework (i.e. the HTTP request) or passing state to other observers.

If you only want to do something if the value of a particular field has changed, check if it is “dirty”:

class SubjectObserver
{
    public function updated(Subject $subject)
    {
        if ($subject->isDirty('teacher_id')) {
            // Update threads
        }
    }
}

martinbean left a reply on Convert To Gate Or Policy?

@behnampmdg3 I literally give you an example in an earlier post.

martinbean left a reply on Authorize In Crud Controller

@sguserface If you have a controller for a model, then you could create a policy for that model and automatically authorise all actions in your controller like this:

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

    public function create()
    {
        // Will automatically check user can create products
    }

    public function store(StoreProductRequest $request)
    {
        // Will automatically check user can create products
    }

    public function show(Product $product)
    {
        // Will check if user can view product
    }

    public function edit(Product $product)
    {
        // Will check if user can update product
    }

    public function update(UpdateProductRequest $request, Product $product)
    {
        // Will check if user can update product
    }

    public function destroy(Product $product)
    {
        // Will check if user can delete product
    }
}

martinbean left a reply on Real Time Activity Feed

@gbdematos Ah, yeah! Good spot! Glad it worked for you :)

20 Mar
2 days ago

martinbean left a reply on Convert To Gate Or Policy?

if … get redirected

Work out where you want to redirect a user, first. Then, it’s simple to do in your course controller:

class CourseController extends Controller
{
    public function show(Request $request, Course $course)
    {
        if ($request->user()->cannot('view', $course)) {
            // Redirect if user does not have permission to view course
        }
    }
}

martinbean left a reply on Use UUID Vs Auto Increment ID

@packy Well yes, UUIDs have the advantages you describe. If you expose your database’s primary keys in API responses and an API endpoint is paginated, then it’s rudimentary to write a script to loop over each page and grab your data. I know of a local start-up who had to close a few years ago because a competitor did this to them.

The disadvantages are, UUIDs are a little more complicated to work with at the storage level. They’re fine to store as text if you have a small/medium app, but if you have a heavily-used application serving lots of requests, then you may need to look at serialising UUID values.

19 Mar
3 days ago

martinbean left a reply on Get Values With A Specified Prefix From The Table

@mdelshad You could create query scopes:

class Setting extends Model
{
    public function scopeGeneral($query)
    {
        return $query->where('name', 'like', 'general.%');
    }
}
$generalSettings = Setting::general()->get();

martinbean left a reply on Delete Please.

@phpmick It depends when your service class is instantiated, but the session exists on the Request object, so it’s probably better to pass the request instance to your service class, and have your service class pull out the session values it needs:

class FooController extends Controller
{
    public function fooAction(Request $request)
    {
        $service = new FooService($request);

        $value = $service->fooMethod();
    }
}
class FooService
{
    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function fooMethod()
    {
        return $this->request->session()->get('some.key');
    }
}

martinbean left a reply on Morph One With View Specific

@xtremer360 In the past, on the morphed classes themselves I’ve added an interface and a getView() method:

interface QuestionType
{
    public function getView();
}
class TextQuestion extends Model implements QuestionType
{
    public function getView()
    {
        return view('questions.text');
    }
}
class MultipleChoiceQuestion extends Model implements QuestionType
{
    public function getView()
    {
        return view('questions.multiple-choices', ['choices' => $this->choices]);
    }
}

Hope that helps!

martinbean left a reply on Laravel Form: Use More Submit Buttons In Form

@frankyj You could add two submit buttons with the same name attribute value, but different value attributes values:

<button type="submit" name="action" value="save">Save</button>
<button type="submit" name="action" value="save_and_new">Save and new</button> 

These will be passed to your controller as if they were inputs:

// Save model

if ($request->input('action') == 'save_and_new') {
    // Redirect back to create form
}

// Redirect to overview page

martinbean left a reply on Passing Data To Broadcasted Event Authorization Callback

@nickdavies07 I don’t think that will work, because if you broadcast to a generic assets channel and have all users subscribe to that, all users are going to receive messages sent to that channel (even if you don’t update your UI with it).

If you’re dealing with schools then I imagine there’s the potential for sensitive data to be sent to your assets channel, and could be a security risk if you’re sending every one’s sensitive information to the same channel.

martinbean left a reply on Check If Config Item Exists

@rkrite You were nearly there. There’s a has method you can use:

if (config()->has('some.key')) {
    // Use configuration value from config file
} else {
    // Fetch configuration value from database
}

martinbean left a reply on It's Possible To Pass An Extra Parameter To The Create View?

@FRANZAG - I think you’re wanting to use query string parameters:

@foreach($rubros as $rubber)
    <option {{ request()->query('rubro_id') == $rubro->id ? ' selected' : '' }}>{{ $rubro->nombre }}</option>
@endforeach

You’d need to add ?rubro_id=[selected_id] to the end of your create URL, i.e. http://example.com/rubros/create?rubro_id=123

martinbean left a reply on Disable Email Notification Globally For User Laravel

@dronax Have you read the documentation? https://laravel.com/docs/master/notifications#customizing-the-recipient

I’ve literally given you an example of what you need to do.

Define a method for the channel; check if your setting is enabled for the channel and return the appropriate value if so. If the setting is not enabled, you don’t want to return anything.

18 Mar
4 days ago

martinbean left a reply on Disable Email Notification Globally For User Laravel

@DRONAX - @dronax I did. Above. You would just change the method name, i.e. routeNotificationForDatabase() for the database channel, and so on.

martinbean left a reply on Testing Model Observer Events - Laravel 5.6

@clemblanco No problem. Glad I was able to help :)

martinbean left a reply on Disable Email Notification Globally For User Laravel

@DRONAX - Then you implement a method for that channel like I’ve done for mail.

martinbean left a reply on Testing Model Observer Events - Laravel 5.6

@clemblanco I’m not sure what re-calculation you’re doing but yeah, you’d be able to dispatch a job in the trait:

class FooTrait
{
    public static function bootFooTrait()
    {
        static::created(function ($model) {
            RecalculateStuff::dispatch($model);
        });
    }
}

martinbean left a reply on Is This Suitable For A Progressive Web App Or Should I Use A Native App?

@devedge You’d be able to do this as a web app. You’ll need to look into Service Workers and localStorage.

Service Workers would allow your “app” to run offline. If there is no Internet connection, your app could store room reports in localStorage and when the web app detects it has an Internet connection again, upload any room reports in localStorage to the server.

If you built a native app, you’d still need to do the same (store anything in a cache if no Internet connection is available, and upload when it next connects).

martinbean left a reply on Real Time Activity Feed

@gbdematos There are a couple of ways you could tackle this.

When you post an item, you could broadcast it to the feed of the user’s followers:

broadcast(new PostPublished($post))

martinbean left a reply on Testing Model Observer Events - Laravel 5.6

@clemblanco If you’re wanting to do something in relation to events on multiple models, then you could create a trait that you apply to those models:

trait FooTrait
{
    public static function bootFooTrait()
    {
        static::creating(function ($model) {
            // Do something when this model is created
        });
    }
}
class FooModel extends Model
{
    use FooTrait;
}
class BarModel extends Model
{
    use FooTrait;
}

martinbean left a reply on Cashier - Pausing Subscription

@yan014 You won’t be able to do this, as Stripe (the payment processor) does not support “pausing” subscriptions.

Your user will need to cancel their subscription if they don’t want to be billed, and re-subscribe at a later date.

martinbean left a reply on Two Laravel Projects, API And Front (Web). How To "login" The User?

@luddinus Laravel Passport: https://laravel.com/docs/master/passport

But I’d not split your project into two separate applications/repositories unless you have the capacity to continually maintain two applications, update framework versions etc.

martinbean left a reply on Disable Email Notification Globally For User Laravel

@dronax You could add an routeNotificationForMail() method to your User model:

public function routeNotificationForMail($notification = null)
{
    // Only return email address if email notifications is enabled
    if (config('enable.userEmailNotifications')) {
        return $user->email;
    }

    return null;
}

martinbean left a reply on Kernel Class Differences?

@terreporter Contracts are just interfaces. Many classes in Laravel are bound to interfaces so that you can “swap” them out in tests, or bind an alternative implementation in the container.

You should type-hint interfaces as much as possible, rather than the actual class. You‘d then be able to “mock” the interface in tests and add expectations:

$mock = Mockery::mock('Illuminate\Contracts\Http\Kernel');

$mock
    ->shouldReceive('pushMiddleware')
    ->once()
    ->with('Mrcore\Modules\Wiki\Http\Middleware\AnalyzeRoute');

app('Illuminate\Contracts\Http\Kernel')->pushMiddleware('Mrcore\Modules\Wiki\Http\Middleware\AnalyzeRoute');

// Mockery should report that the pushMiddleware() was called with your middleware class’s name

martinbean left a reply on Is There A Way To Get The Swift_Message Instance From The Mailable Class?

@aschorr A Mailable is a representation of an email message. It’s when a Mailable is “built” (at the point of sending) that a Swift_Message instance is created, so you would need to hook into that process to get the message as a Swift_Message instance.

martinbean left a reply on Socialite With Google Complete Security

@stevebelanger I think we’d need to see some actual code, but you would authenticate against any Google APIs using an access token, not user IDs.

martinbean left a reply on Collection In Laravel And ES6

Hi, Dario. It’s not exactly functional programming but it Laravel’s collection methods do take concepts from functional programming. The idea being, a collection method manipulates a collection in some way and returns a new collection, so you can keep chaining methods.

Functional programming, like its name suggests, would be based around global functions that take an input and return an output, so you would wrap functions rather than “chain” them.

Hi Boys :)

I imagine there are girls on this forum, too. Don’t discount them in your posts.

martinbean left a reply on Testing Model Observer Events - Laravel 5.6

@clemblanco What is it you’re actually trying to do? As “FooEvent” doesn’t really explain your intention well. It seems a bit weird to be dispatched events in observers (which are essentially listeners on pre-defined model events).

Personally, I’d just do what you’re doing in your listener, in the observer method:

class UserObserver
{
    public function created(User $user)
    {
        // Do what you were doing in your listener here instead
    }
}
15 Mar
1 week ago

martinbean left a reply on Load More Than One Environment File

@Raphomee I imagine Dotenv will just load values into environment variables (and not unset any, as that could be dangerous). Therefore, in a service provider, you could load your domain-specific environment variables:

class DomainServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Load domain-specific settings
    }
}
11 Mar
1 week ago

martinbean left a reply on Is It Good Practice For Controller To Save To The Database?

@JOSEFELIPETTO - > Take a look at the Repository Pattern, which is a great start point to that.

@josefelipetto A repository does not help organise code into “services”. A repository merely fetches (and, contentiously, persists) objects to a data store. If @algae14 used repositories, then the code would look the same, it would just be more verbose, i.e.

$firm = $this->firms->save(new Firm([
    'name' => $request->name,
    'type' => $request->type,
]));

martinbean left a reply on Is It Good Practice For Controller To Save To The Database?

@algae14 There’s nothing “wrong” with what you’re doing, but when my controller actions start to grow like that, I tend to move the code to a synchronous job and dispatch it from the controller:

public function store(StoreSubscriptionRequest $request)
{
    $subscription = CreateSubscription::dispatchNow($request);

    return new SubscriptionResource($subscription);
}
use Illuminate\Foundation\Bus\Dispatchable;

class CreateSubscription
{
    public $data;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        return DB::transaction(function () {
            $firm = $this->createFirm();

            $contact = $this->createContact($firm);

            return $this->createSubscription($contact);
        });
    }

    private function createFirm()
    {
        return Firm::create([
            'name' => $this->data['name'],
            'type' => $this->data['type'],
        ]);
    }

    private function createContact(Firm $firm)
    {
        return $firm->contacts()->create([
            'first_name' => $this->data['first_name'],
            'last_name' => $this->data['last_name'],
            'email' => $this->data['email'],
            'phone' => $this->data['phone'],
        ]);
    }

    private function createSubscription(Contact $contact)
    {
        return $contact->subscriptions()->create([
            'name' => $this->data['name'],
            'aum' => $this->data['aum'],
            'first_name' => $this->data['first_name'],
            'last_name' => $this->data['last_name'],
            'email' => $this->data['email'],
            'phone' => $this->data['phone'],
            'starts_on' => $this->data['starts_on'],
            'ends_on' => $this->data['ends_on'],
            'plan_Id' => $this->data['plan_id'],
        ]);
    }
}

The logic is also wrapped up in a transaction as mentioned by @tykus. I’ll do this as well if I’m inserting a number of related records in one request.

martinbean left a reply on Laracasts Web Site

It’s also using Cloudflare, which will cache responses somewhat.

martinbean left a reply on Migrating From Stripe Soures To Stripe Payment Intent

@agandrass Stripe has a step-by-step guide for using PaymentIntents on their website: https://stripe.com/docs/payments/payment-intents/quickstart

05 Mar
2 weeks ago

martinbean left a reply on Laravel Queue Using SQS + Behind The Load Balancer

@labib47 A load balancer doesn’t stop you using an SQS queue. Laravel pushes/retrieves jobs using SQS’s API.

01 Mar
3 weeks ago

martinbean left a reply on Controllers Structure For API And "regular" Routes

@demers94 I create separate controllers, in an Api namespace.

I update the mapApiRoutes() method in my RouteServiceProvider class to automatically load files from that namespace:

protected function mapApiRoutes()
{
    Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace.'\Api')
            ->group(base_path('routes/api.php'));
}

Then I can just create controllers as normal:

namespace App\Http\Controllers\Api;

use App\Offer;
use App\Http\Controllers\Controller;

class OfferController extends Controller
{
    public function show(Offer $offer)
    {
        return new OfferResource($offer);
    }
}

martinbean left a reply on Extending Package Model To Your Own

@oliverbusk I think we need to see more of the error stack trace. If you’ve extended the original model, then your model should just inherit its methods and properties.

martinbean left a reply on Spark With CRM Admin?

what admin will work with spark I'm thinking Nova is it supported

@andylee Nova and Spark are just Laravel packages. You can install Nova into a Laravel application that also uses Spark.

can you get it cheaper as a package is anyone aware?

@andylee Spark is sold in one place (from Taylor). Its price is its price.

martinbean left a reply on Why Laravel Calls My Model In Plural Instead Of Singular?

@andersonmichel You should really read up on—and follow—Laravel’s conventions. There are few issues in your code.

Controllers should have a Controller suffix in both its filename and class name. This should also be “study” case. So it would be UsuarioController.

This naming convention should follow through to your routes file. So your routes should look like this:

Route::get('/admin/login', '[email protected]');

martinbean left a reply on Which Relationship Would You Choose?

@yoeriboven Yeah, because I assumed your Post model had a profile_id column.

When you retrieve posts, you might be able to “map” the profiles onto them to avoid re-querying:

$profiles = $user->following()->get();

$posts = Post::whereIn('profile_id', $profiles->modelKeys())->latest()->take($limit)->get();

$posts->transform(function ($post) use ($profiles) {
    $post->setRelation('profile', $profiles->get($post->profile_id));
});

return $posts;

martinbean left a reply on Which Relationship Would You Choose?

@YOERIBOVEN - > The way I see this possible: add a Profile relationship to Post

@yoeriboven Does a Post not already have a Profile relationship? How else would you know who posted a Post…?

26 Feb
3 weeks ago

martinbean left a reply on Fetch Strtotime Data As Time Format With Am And Pm

@DEEKSHITH - Might have been an idea to mention that in your initial post…

Format your date value using JavaScript in that case. Moment.js is a popular package for formatting dates.

martinbean left a reply on Is There A Way I Could Provide Paramatere For All Controllers Used Inside Route Group?

@another_x I get what you’re wanting to do, but you can’t add a route parameter and not have it passed to your controller action.