Braunson

Founder at Geekybeaver

Member Since 5 Years Ago

Ontario, Canada

Experience Points
30,155
Total
Experience

4,845 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
121
Lessons
Completed
Best Reply Awards
34
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 7
30,155 XP
Oct
09
6 days ago
Activity icon

Commented on Integrate A Site Template

Why drag the CSS into the pub directory, instead use the resources/css + Laravel Mix? Feels misleading to new comers..

Oct
07
1 week ago
Activity icon

Replied to Teams Via Subdomain

Something along the lines of this https://medium.com/@weihien90/laravel-5-simple-subdomain-for-multi-tenant-application-551ee489b599

If you do pursue it with Spark, it'll work almost the same way.

Sep
30
2 weeks ago
Activity icon

Replied to Where Are You All From?

Canada eh :)

Sep
24
3 weeks ago
Activity icon

Replied to Check Quantity If It Available On Stock

We don't know what your database looks like for the products or how it's structured. But you can do a check in your controller/service to check stock beforehand (before any save logic) and respond accordingly..

Sep
01
1 month ago
Activity icon

Replied to How Would You Set Up "Credit" In Movie Database

I think the pivot table is the best optioin. If you want to have parent and sub credits, then apply that on your pivot table..

person_id | movie_id | role_parent_id | role_child_id
Aug
14
2 months ago
Activity icon

Replied to Are Event Listeners Cached In Some Way?

From the docs..

... during your deployment process, you should run the event:cache Artisan command to cache a manifest of all of your application's events and listeners

So yes event & listeners are cached. Clear your cache on deployment and if you are using queue's, restart them on deploy.

Aug
01
2 months ago
Activity icon

Replied to Saving API Usage For Metered Billing

I don't know of any handy package but I want to suggest using Middleware to do the counting for you, it abstracts that logic away from your API endpoint controller methods.

If you do build one, you should publish it as a package, I'm sure others would appreciate it :)

Activity icon

Replied to How To Setup A Callback API Endpoint That Recieves Payment Status From A Payment Gateway

I'm not sure what Payment Processor you are using but you would look at their dev docs to see what is being sent to your server when you provide them with a webhook. Are they providing a POST or GET request?

They should also provide you with some information as to what they are POSTing. Typically a webhook will be a POST especially when they are sending you a bunch of data.

So check your PP's dev docs to see what they send you and how. Outside of that it's up to you to do with the $request as you choose.

As an example, MailGun will POST to a webhook URL I provide. I used their docs to find out what they POST to me and I actually validate the incoming request (using custom Middleware) well I validate the signature included in the request.

So check the docs, and what you are provided with do what you need to with the $request :)

Jul
30
2 months ago
Activity icon

Replied to Change Request Body Middleware

Your looking at (from the title) a method for Slim maybe?

You can do this with Middleware doing so like this:

Example File: app/Http/Middleware/TestMiddleware.php

<?php namespace App\Http\Middleware;

use Closure;

class TestMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $input = $request->all();

        if (isset($input['foo'])) {
        $input['foo'] = 'bar';

            // Input modification
            $request->replace($input);

            \Log::info($request->all()); // Shows modified request
        }

        return $next($request);
    }

}
Jul
24
2 months ago
Activity icon

Replied to Convert String Array To Array Of Int(s)

array_map to intval ;-)

$array = ["123", "34", "223"];
$integerIDs = array_map('intval', $array);
Jul
17
2 months ago
Activity icon

Replied to Saving For Each Loop

Try clearning your cache and cookies:

php artisan cache:clear then delete browser cookies. This issue has been posted previously on this form, try searching next time :)

Jul
14
3 months ago
Activity icon

Replied to Laravel Make Service Pattern Command

Just a suggestion, good job but perhaps stub out some example methods in the service stub as a starting point for others? :)

Jun
27
3 months ago
Activity icon

Replied to How Can I Show Edit And Delete Button To The Post Owner In Vuejs Comeponent Larave?

You will need some way to know the current logged in user as well as the post user. Since you are passing in the post parameter to the deletePost method in Vue you should have access to post.user_id now you just need to find a way to get the currently logged in user.

You can set it like so https://stackoverflow.com/a/52703853/610880

Then you would use v-if something like this:

<li><a @click="deletePost(post,key)" v-if="post.user_id === user.id" title="Edit Post" class="pencil-edit">Edit Post</a></li>
Jun
24
3 months ago
Activity icon

Replied to Laravel Cashier - Adding Days To Subscription

@Tyler The repo is your friend in this case, you can see what happens then you 'cancel' a subscription via the cancel method.

For Stripe: https://github.com/laravel/cashier/blob/707ef5ec28974f74c57461ef25c125c46050d885/src/Subscription.php#L404

The code will cancel the subscription at the end of the billing period. The code will set the cancel_at_period_end field in stripe to true. Stripe will end the subscription at the end of the billing period.

For BrainTree: https://github.com/laravel/cashier-braintree/blob/1b9c2500a030fa7589386d829160d63669ead7fa/src/Subscription.php#L369

You can see the code uses the BraintreeSubscription class to call cancel() which if we dig into the braintree/braintree_php package you'll see here it calls the Braintree API Gateway and calls here to cancel the subscription in Braintree.

So to answer your question simply:

  1. Yes there is a difference in using the cancel subscription method vs deleting the entry from the DB. The subscription is technically stored on the Processor side (Stripe/Braintree), your app's database just keeps reference of it, deleting it in your db will just delete your app's reference, the customer will still be billed by the processor (Stripe/Braintree) since that's where the actual processing/charging magic happenbs.

  2. Cashier-Braintree is just a wrapper to help facilitate the use of BrainTree in Laravel, if you want to use t he direct BrainTree PHP library, go for it, but I'd personally use Cashier and if it doesn't do what I need, to just extend it to suit my needs.

I hope this helps give you more insight and a better idea on how things work under the hood with Laravel's Cashier/Cashier-Braintree :)

Activity icon

Replied to Integrate PHP Code With Contact Form 7 Fields

@hassanshahzadaheer You can see how to do it in the CF7 docs https://contactform7.com/selectable-recipient-with-pipes I've updated my answer to include an example of a dropdown in the CF7 edito.

An example of how to create dropdowns in CF7 editor:

[select cows "1" "2" "3"]
Jun
21
3 months ago
Activity icon

Replied to Laravel Cashier - Adding Days To Subscription

Yes that sounds like your best bet. I'm not familiar at all with BrainTree myself but from the flow you've described.

  1. Cancel users existing subscription $user->subscription('fooSub')->cancel();
  2. Create a subscription that ends on X date
  3. Subscribe the user to the new subscription.

On step 2, since Cashier (BrainTree) doesn't seem to have methods to create custom subscriptions, you'll have to do this likely with the BrainTree PHP library @ https://developers.braintreepayments.com/reference/request/subscription/create/php manually. You will want to set the billing day of month to the new date you need.

$result = $gateway->subscription()->create([
  'paymentMethodToken' => $token,
  'planId' => 'custom_plan_foo1234',
  'billingDayOfMonth' => 30,
  // ...
]);

After that you can just re-subscribe your user using Cashier like so: $user->newSubscription('newSub')->create($token); You will need the CC token also to re-subscribe the user.

Activity icon

Replied to 'no Input Specified' Challenge On The Browser When Trying To Load 'homestead.test'

Looks like you have another issue here where the base box won't download. Please check this solution https://github.com/mitchellh/vagrant/issues/6725#issuecomment-223733553

Activity icon

Replied to Laravel Cashier - Adding Days To Subscription

Yes anchorBillingCycleOn is for Stripe only. As for BrainTree it doesn't look like there is an option for what you need in Cashier.

I can suggest another option, is using the 'trial days' instead and requiring CC on setup so they have X many days before they are "subscribed". This however only works on initial sign up but not necessarily when they are/have been subscribed already.

You cannot change the billing date on an existing subscription, you must cancel the subscription and create a new one.

With Braintree, the next billing date is calculated, and so can't be changed unfortunately.

Activity icon

Replied to 'no Input Specified' Challenge On The Browser When Trying To Load 'homestead.test'

Make sure your Homestead.yaml project / folders paths are correct. Then run vagrant up --provision and try the URL again.

Activity icon

Replied to Lavacharts Gauge Colors

I'm not super familiar with Lavacharts but looking at the docs on both Lavacharts and Google it looks like only

  • greenColor
  • redColor
  • yellowColor

https://developers.google.com/chart/interactive/docs/gallery/gauge#Configuration_Options

Activity icon

Replied to Database Sessions Pruning

Yes they are cleaned out. There is another thread on Laracasts here asking the same question. Check out https://github.com/laravel/laravel/blob/master/config/session.php specifically look at the comment for Lottery.


    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

Laravel cleans up expired session entries based on a lottery setting.

However note that not all session drivers require manual cleanup, something like Redis doesn't need it because it automatically deletes expired keys.

You can see in the StartSession middleware where it cleans up the sessions using the method collectGarbage which cleanrs the session based on the lottery config (above).

https://github.com/illuminate/session/blob/master/Middleware/StartSession.php

The default configurations are [2, 100]. It means that a random integer is chosen between 1 and 100, if it's lower or equals to 2 the cache will be cleared. (Aka you have a 2% possibility to clear the cache every call).

Jun
20
3 months ago
Activity icon

Replied to Integrate PHP Code With Contact Form 7 Fields

You'll want to look into the Hooks the Contact Form 7 provides. You'll hook into the response to output what you want.

As for the dropdowns, you create them in the Contact Form 7 form editor with the provided options.

You can see a list of hooks at http://hookr.io/plugins/contact-form-7/5.1.3/hooks/#index=a (for the latest version of CF7), you'll probably want something like the wpcf7_ajax_json_echo hook to modify the outbound response returned to the user. Here's an example:

Something like this (untested), but it would go in your wp-content/themes/footheme/functions.php (your theme, functions file).

add_filter('wpcf7_ajax_json_echo', function( $response, $result )
{
    $cow  = 100;
    $goat = 200;

    if (isset($response['cow']) || isset($response['goat'])) {
        if (isset($response['cow'])) {
            $cowSelect = $response['cow'];
            $cow = ($cow - $response['cow']);

            switch ($cowSelect) {
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                    $message .= 'Total '.$cow.' cows remaning'.'<br/>';
                    break;
            }
        }

        if (isset($response['goat'])) {
            $goatSelect = $response['goat'];
            $goat = ($goat - $response['goat']);

            switch ($goatSelect) {
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                    $message .= 'Total '.$goat.' goats remaning'.'<br/>';
                    break;
            }
        }
    }

    return $response;
}, 10, 2);

Then you just need to create a dropdown with the options you want, make the dropdown required (if it needs to be required) in the Contact Form 7 form editor.

May
29
4 months ago
Activity icon

Replied to Injecting Bugsnag In Queuefailed

Just a thought, why not use the event illuminate.queue.failed and create a listener to log this. The parameters provided are $connection, $job, $data.

As for your error, you have too many params according to the error in your closure it's providing one, you expect two (JobFailed, Bugsnag).

Queue::failing(function (JobFailed $event) {
            // $event->connectionName
            // $event->job
            // $event->exception
        });
May
08
5 months ago
Activity icon

Replied to Event Listener With Popup Notification?

@splendidkeen @princeoo7

Using the package I linked above: Laravel Websockets https://docs.beyondco.de/laravel-websockets/1.0/basic-usage/pusher.html as your pusher replacement

Also you can use this tutorial to give you an idea of what to do https://www.youtube.com/watch?v=i6Rdkv-DLwk in order to build real time user notifications with Laravel Echo (which you'll use with the above package)

May
03
5 months ago
Activity icon

Replied to Any Recommendation For Text Editor With Image Uploads?

This is what your looking for https://alex-d.github.io/Trumbowyg/ with this plugin https://alex-d.github.io/Trumbowyg/demos/#plugins-upload

Then you would set the upload endpoint in Laravel so it could be S3/DO whatever you want from there at the server endpoint.

If you want just an uploader.. Uppy is great and supports multiple providers which looks awesome https://uppy.io/ - I plan on seeing if I can integrate Uppy with Trumbowyg in the future.

Activity icon

Replied to Multiple Variants Of Same App...how To Manage

I suggest checking out Git Submodules or even think about modularizing your app from a code level.

You have some options:

  1. Have two separate apps running with two different code bases
  2. Have two separate apps running with the same code base but with different "enabled modules"
  3. Run both apps together with different "modules enabled"

I've been thinking about this same thing and I think making things into modules in Laravel and making use of Git Submodules to manage the shared submodules is the best way to manage the code. I guess it depends how much is similiar between the two projects.

Activity icon

Replied to Event Listener With Popup Notification?

I think you would be better off either using native web push notifications OR using something like Pusher or the alternatives Laravel Websockets for this and then you can push real-time to specific channels.

Again if your just doing all this for one popup and only ever one, the top two may be overkill.

If you want to do it using your example, the easiest method is setting a a notification table, where you set the message to the user, and on page load, you have a partial that checks for any new notifications (provided in a global view composer) and if there are show them the user and mark them as read, so the next page load they don't appear again.

In the backend you'd trigger an event (i.e. PostApproved) and a listener would be like .. NotifySubmitterOfApproval and in that listener you would create a new notifications table entry for that user.

Personally if I'm going to be using more than just one notification, I'd make use of webpush/sockets ;-)

Activity icon

Replied to Perfectly Smooth Looped Eased Css Animation

I think this is what you want.. check this out http://codepen.io/empreintes/pen/jyWQym

Other solutions for what you want at https://stackoverflow.com/q/41587802/610880

Activity icon

Replied to Route::getRoutes() Returns Only Package Routes

I don't think there's an easy way to specify a package and get the routes but you can sort by controller using a slightly modified code snippet from here..

$userRoutesArray = [];
$lookFor = 'UserController';
foreach (\Route::getRoutes() as $value) {
    $controller = $value->getAction();

    if (! isset($controller['controller'])) {
        continue;
    }

    if (strpos($controller['controller'], $lookFor)) {
        array_push($userRoutesArray, $value->uri());
    }
}

dd($userRoutesArray);

If you wanted to get all routes from t he app, you could run this snippet:

$routes = collect(\Route::getRoutes())->map(function ($route) { 
    return $route->uri(); 
});

dd($routes);
Activity icon

Replied to Create Account When User Registers

If you check in the Spark code, it shows the above but also where it appends the user who registered as the owner to the team.

If you have access to the repo https://github.com/laravel/spark-aurelius/blob/23107d494edb3165fd80b27c04f83528e4537c53/src/Interactions/Settings/Teams/CreateTeam.php#L72-L84

If you do not.. this is the code. You can see on the Spark::interact(AddTeamMemberContract part it adds the user to the team ;-)

    public function handle($user, array $data)
    {
        event(new TeamCreated($team = Spark::interact(
            TeamRepository::class.'@create', [$user, $data]
        )));

        Spark::interact(AddTeamMemberContract::class, [
            $team, $user, 'owner'
        ]);
        
        event(new TeamOwnerAdded($team, $user);

        return $team;
    }

So I'm not sure why your looking to change the Spark registration process as it already creates the team and adds the user registered as the owner already on register?

May
01
5 months ago
Activity icon

Replied to Trying To Get Property Of Non-object

Try dumping out $print via dd inside your foreach loop to see what's available or what is being returned. See if duedate is in the array. Make sure duedate is hot hidden in the Model also.

Apr
30
5 months ago
Activity icon

Replied to How To Process Mail Send Issues?

Typically this depends on what provider your using. If your using something like MailGun, you would setup a webhook, and have it record any webhook calls for "failed" or the like for those reasons.

If your using plain PHP's mail method, it just literally sends an email regardless and return true/false without any explanation. You'd have to dig into your server's mail logs (if any) and it may give you reasons why, but not always.

So your best bet at this point is using a third party like MailGun or SendMail and setting up Webhooks for these success/failed/dropped/bounced events and use the message id to track them.

Activity icon

Replied to Laravel Telescope System Requirements

Try increasing your PHP's memory_limit.

There's an Issue thread for composer here https://github.com/composer/composer/issues/945 with some other debug steps/solutions to try which may help.

Apr
26
5 months ago
Activity icon

Replied to Doing Something Before Delete In Eloquent Models Even In Mass Deleting

You can override deleting event in the Model's boot method OR you can use an observer to observe the deleting event and do the image deletion there before the Product finishes deleting.

An example of the first thing I suggested is:

    public static function boot()
    {
        parent::boot();

        static::deleting(function($team) {

            // Delete your photo here

        });
    }

I'd suggest creating an event listener / observer instead tho it's a bit cleaner especially when you have more and more logic.

Apr
25
5 months ago
Activity icon

Replied to How To Sort Posts By Latest Commented

@memele Whoops, here you are

$latestComments = Post::with('comments')->get()->sortByDesc('comments.created_at');

We sort using Collection helpers after getting the results :)

Activity icon

Replied to Validation On Required_if

I'm not entirely sure what your trying to do. If you want to (on the Update Form Request) only require the banner field when it's filled out then you would likely use the sometimes validation method.

https://laravel.com/docs/5.8/validation#conditionally-adding-rules

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

i.e

'banner' => 'sometimes|required|mimes:jpeg,png|dimensions:width=1920,height=1080',

Activity icon

Replied to (1/1) FatalErrorException Maximum Execution Time Of 60 Seconds Exceeded

Looks like if the file is large it's taking too long to load it.

In this case I'd suggest offloading this type of large operation to the queue system and queue it.

Alternatively you could batch loop and batch insert the data (instead of one by one) which may speed up the script but again all depends on the file size and contents it has to go through, your best bet is to queue this up.

Activity icon

Replied to Logging Raw Data

This is the function of the logger. I don't think there's an easy way to disable timestamps other than to create your own Logger/driver.

https://laravel.com/docs/5.8/logging

Activity icon

Replied to How To Sort Posts By Latest Commented

Try something like this..

$latestComments = Post::with('comments')->orderBy('comments.created_at', 'desc')->get();
Apr
24
5 months ago
Activity icon

Replied to Achieve Available Venue On That Date.

Hmm you are checking for Venues with bookings between your start and end date.

What about using whereNotBetween

$availableVenue = Venue::with(['bookings' => function ($query) use ($startDate, $endDate) {
    $query->whereNotBetween('startDate', [$startDate, $endDate])
            ->whereNotBetween('endDate', [$startDate, $endDate]);
}])->get();

dd($availableVenue);

There's likely a more ideal way to do this but it should work...

Activity icon

Replied to How To Validate URL Query Parameters?

Look into using Form Requests to validate your inbound form requests before you need to do any logic.

https://laravel.com/docs/5.8/validation

Activity icon

Replied to Swift_IoException Unable To Open File For Reading [1]

Sounds like your path to the file is wrong. Does it say which line? Perhaps it's the first one, are you referencing an existing file somewhere in SalesregisterExport?

Have you confirmed permissions are correct (so it can create a file)?

Activity icon

Replied to Scheduling Sending Multiple Queued Mails

Can you confirm your server has mail enabled/installed? Try adding this in a php file and running it to test mail.

<?php
$sender = '[email protected]'; // Update this
$recipient = '[email protected]'; // Update this

$subject = "php mail test";
$message = "php test message";
$headers = 'From:' . $sender;

if (mail($recipient, $subject, $message, $headers))
{
    echo "Message accepted";
}
else
{
    echo "Error: Message not accepted";
}
?>

If that works and you get an email let us know, otherwise it may be you have to enable/fix mail on your local server first before you'll receive anything.

Additionally if mail is enabled and working properly elsewhere, do you have any errors in your log? Have you tried changing your .env file MAIL_DRIVER to log? If it's logging them it's likely a mail related issue.

Activity icon

Replied to How Do I Implement An Interface Onto A Laravel Project Properly?

From what I understand, it's not possible to pass the route variable to the Controller's constructor. However there are other methods.. such as getting the Route::current()->parameter('accountType') and then setting it in the constructor but you wouldn't inject the dependency tho necessarily.

For example:

public function __construct(AccountTypeInterface $accountType)
{
    $accountType = \Route::current()->parameter('accountType');
    $this->accountType = $accountType->where('slug', $accountType)->first();
}

You may be able to use the request() help also instead of route()/Route:: This is untested but may be a possible solution.. no it's not ideal but it may work.

FWIW: There was a proposal in the Laravel framework repo for this same feature at https://github.com/laravel/framework/issues/1025 it was rejected :(

Apr
23
5 months ago
Activity icon

Replied to Validation On Required_if

Have you tried using the required_unless rule?

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

'fee' => 'required',
'amount' => 'bail|required_unless:fee,=,2|integer|gte:1',

bail = Stop running validation rules after the first validation failure.

So it'll try and validate required_unless, but if that fails then it'll bail.

Activity icon

Replied to Best Way To Tackle This App? Ideas Welcome

Welcome! Ok so there are couple ways you can do this but since it's super simple, you can literally use a flag like you mentioned on the users table.

A user registers and by default is a Client.

You don't necessarily have to have a flag to specify client/admin just admin. This way by default all users are clients. You'd have to manually (at least for the first user) update their to have the is_admin flag set to true/1.

So you'll have 1 users table, with an additional flag called is_admin set to 0 by default. This way you can use the auth/register system that comes with Laravel.

Now for checking if they are an admin or not.. you can create a custom Blade Directive for use in Blade Views (see the Laravel docs about creating directives) and you would add the helper on the User.php model (which you'd also use to check in the blade directive). Let me give you the code..

User.php (the model, place in the class)

/**
 * A helper to determine if the current user is an admin
 */
public function isAdmin()
{
    return $this->is_admin;
}

AppServiceProvider.php (put this code inside boot() method

/**
 * If statement check if user is an admin
 *
 * Usage: @admin yep they are an admin @admin
 */
Blade::if('admin', function() {
    return auth()->check() && auth()->user()->isAdmin();
});

Now you can use the directive in your views like this..

@admin
This is text for the admin
@endadmin

And you can use the helper method in the code/middleware on a user like so:

if ($user->isAdmin()) {
    // Do admin stuff
}

If you wanted, you could create a helper and directive to return bool if they are a client.. like so..

User.php (the model, place in the class)

/**
 * A helper to determine if the current user is a client
 */
public function isClient()
{
    return ! $this->is_admin;
}

AppServiceProvider.php (put this code inside boot() method

/**
 * If statement check if user is an admin
 *
 * Usage: @admin yep they are an admin @admin
 */
Blade::if('client', function() {
    return auth()->check() && auth()->user()->isClient();
});

Hope this helps!

An example middleware for checking if admin is this..

app/Http/Middleware/CheckAdmin.php

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {        
        // Is there current user an admin
        if ($request->user()->isAdmin()) {
            return $next($request);
        }

        return response('Unauthorized.', 401);
    }
}

Don't forget to register the middleware in your app\Http\Middleware\Kernel.php file and use it wherever needed

Activity icon

Replied to How Can I Get Data From Database?

Hmm not entirely sure what your having issues with as you don't specifically explain. You should be able to access the variable $totalMarks in your blade view and use it?

Activity icon

Replied to How Can I Get Chunked Value From Nested Eloquent Collection

I'm not sure how products relate to brands (assuming it's by brand_id on products) so something along the lines of ..

$brands->groupBy('products.brand_id')`
Activity icon

Replied to What Is Your Laravel Design Pattern?

In existing projects you'll have to plan a way to move things part by part or module by module. It'll be tedious in an existing project, especially when it's a larger project.

A good Laracasts series is https://laracasts.com/series/solid-principles-in-php if your looking to learn more SOLID principles in PHP.

I'd suggest if you are trying to use SOLID to stick to it as much as possible but no code is perfect and you'll likely not be able to stick to it 100% for every piece of code so don't sweat the small things ;-)