xtremer360

xtremer360

Full Stack Developer at 321

Member Since 5 Years Ago

Kissimmee, FL

Experience Points
150,615
Total
Experience

4,385 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
1155
Lessons
Completed
Best Reply Awards
9
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 31
150,615 XP
Oct
18
4 days ago
Activity icon

Commented on Widget Workshop

Also to add if you have to assign private properties on a class and don't want the Widget to pass along the constructor for the viewData you can add this check inside of the foreach of the buildViewData method.

if ($method->isConstructor()) {
   continue;
}
Oct
10
1 week ago
Activity icon

Started a new Conversation Blog Post And Project Sharing Attachments And Categories

I'm attempting to map out my personal blog site with the right migrations and models. I have posts that each have either one or multiple categories and attachments which can be an image or a video. I also have projects that can either have one or multiple categories as well and one or multiple attachments attached to the project.

My question is my description above with how a project and a blog post can both have multiple attachments and categories assigned to them the correct way to set up my migrations.

Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    ...
    $table->timestamps();
});

Schema::create('attachments', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->morphs('attachable');
    $table->string('path');
    $table->timestamps();
});

Schema::create('projects', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('categories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->morphs('categorable');
    $table->string('name');
    $table->timestamps();
});
Oct
05
2 weeks ago
Activity icon

Replied to Laravel Mutator Not Working Correctly

@falloutboi Remember it will NEVER hit that if statement when you are returning the first_name property always.

Sep
25
3 weeks ago
Activity icon

Started a new Conversation Custom Relationship Returning Collection Instead Of Single Model

I created a custom relationship to handle situations for a polymorphic many to many relationship. My problem is if I have a model that has this trait attached and I want to grab the currentGroup they are attached to if they are it then returns a collection instead of a single model instance. I attempted to add ->first() to the end of the QB inside of the current method of the relationship class but it still returns the collection. What am I doing wrong here?

<?php

namespace App\Models\Concerns;

use App\Models\Member;
use App\Models\Group;

trait CanBeGroupMember
{
    /**
     * Get the group history the member has belonged to.
     *
     * @return App\Eloquent\Relationships\LeaveableMorphToMany
     */
    public function groupHistory()
    {
        return $this->leaveableMorphToMany(Group::class, 'member')->using(Member::class);
    }

    /**
     * Get the current group the member belongs to.
     *
     * @return App\Eloquent\Relationships\LeaveableMorphToMany
     */
    public function currentGroup()
    {
        return $this->groupHistory()->where('status', 'active')->current();
    }

    /**
     * Get the previous groups the member has belonged to.
     *
     * @return App\Eloquent\Relationships\LeaveableMorphToMany
     */
    public function previousGroups()
    {
        return $this->groupHistory()->detached();
    }
}
<?php

namespace App\Eloquent\Concerns;

use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Relations\Pivot;

trait IsLeaveableBelongsToMany
{
    /**
     * The cached copy of the currently attached pivot models.
     *
     * @var Collection
     */
    private $currentlyAttached;

    public function detach($ids = null, $touch = true)
    {
        $query = $this->newPivotQuery();
        // If associated IDs were passed to the method we will only delete those
        // associations, otherwise all of the association ties will be broken.
        // We'll return the numbers of affected rows when we do the deletes.
        if (! is_null($ids)) {
            $ids = $this->parseIds($ids);
            if (empty($ids)) {
                return 0;
            }
            $query->whereIn($this->relatedPivotKey, (array) $ids);
        }

        $results = $query->update(['left_at' => now()]);
        if ($touch) {
            $this->touchIfTouching();
        }
        return $results;
    }

    /**
     * Sync the intermediate tables with a list of IDs or collection of models.
     *
     * @param  \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array  $ids
     * @param  bool   $detaching
     * @return array
     */

    public function sync($ids, $detaching = true)
    {
        $changes = [
            'attached' => [], 'detached' => [], 'updated' => [],
        ];

        // First we need to attach any of the associated models that are not currently
        // in this joining table. We'll spin through the given IDs, checking to see
        // if they exist in the array of current ones, and if not we will insert.
        $current = $this->getCurrentlyAttachedPivots()
                        ->pluck($this->relatedPivotKey)->all();

        $detach = array_diff($current, array_keys(
            $records = $this->formatRecordsList($this->parseIds($ids))
        ));

        // Next, we will take the differences of the currents and given IDs and detach
        // all of the entities that exist in the "current" array but are not in the
        // array of the new IDs given to the method which will complete the sync.
        if ($detaching && count($detach) > 0) {
            $this->detach($detach);

            $changes['detached'] = $this->castKeys($detach);
        }

        // Now we are finally ready to attach the new records. Note that we'll disable
        // touching until after the entire operation is complete so we don't fire a
        // ton of touch operations until we are totally done syncing the records.
        $changes = array_merge(
            $changes,
            $this->attachNew($records, $current, false)
        );

        // Once we have finished attaching or detaching the records, we will see if we
        // have done any attaching or detaching, and if we have we will touch these
        // relationships if they are configured to touch on any database updates.
        if (count($changes['attached']) ||
            count($changes['updated'])) {
            $this->touchIfTouching();
        }

        return $changes;
    }

    /**
     * Get the pivot models that are currently attached.
     *
     * @return \Illuminate\Support\Collection
     */
    protected function getCurrentlyAttachedPivots()
    {
        return $this->currentlyAttached ?: $this->newPivotQuery()->whereNull('left_at')->get()->map(function ($record) {
            $class = $this->using ? $this->using : Pivot::class;

            return (new $class)->setRawAttributes((array) $record, true);
        });
    }

    protected function baseAttachRecord($id, $timed)
    {
        return Arr::add(
            parent::baseAttachRecord($id, $timed),
            'joined_at',
            now()
        );
    }

    public function current()
    {
        $this->wherePivot('left_at', null);

        return $this;
    }

    public function detached()
    {
        $this->wherePivot('left_at', '!=', null); //Laravel translates this to `IS NOT NULL`

        return $this;
    }

}

Sep
23
4 weeks ago
Activity icon

Replied to Unit Testing A Model

@martinbean

So do you mean I should remove the following from the model?

if (!$this->is_employed) || $this->is_retired) {
    throw new CannotBeRetiredException;
}
Activity icon

Started a new Conversation Unit Testing A Model

I'm trying to unit test my models and currently have a method that will retire a player from the system. I'm trying to find out if I should have my checks on the status of the player in the policy or in the model because it changes how I approach my unit testing for the player.

What suggestions or ideas do people have?

Policy

/**
     * Determine whether the user can retire a player.
     *
     * @param  App\Models\User  $user
     * @param  App\Models\Player  $player
     * @return bool
     */
    public function retire(User $user, Player $player)
    {
        if (!$player->is_employed || $player->is_retired) {
            return false;
        }

        return $user->isSuperAdministrator() || $user->isAdministrator();
    }

Model

/**
     * Retire a model.
     *
     * @return \App\Models\Retirement
     */
    public function retire()
    {
        if (!$this->is_employed) || $this->is_retired) {
            throw new CannotBeRetiredException;
        }

        $this->retirements()->create(['started_at' => now()]);
        $this->touch();
    }
Aug
22
2 months ago
Activity icon

Replied to Refactoring To Datatable Classes

@jlrdw No worries on the misunderstanding. Some of the references for the package have sites that I think are temporarily down because I can't access any of them.

Is there anyone that has used this package and created their own classes that extend the package datatables class and modified the class so that they can handle all of the logic in one place.

Aug
21
2 months ago
Activity icon

Replied to Refactoring To Datatable Classes

@jlrdw I've updated with my full controller method.

Activity icon

Replied to Refactoring To Datatable Classes

How would I apply a scope for this?

Activity icon

Started a new Conversation Refactoring To Datatable Classes

I'm trying to figure out how I can refactor this little bit of controller code to individual classes that can be used instead. The package I am using is Yajra Laravel Datatables package.

/**
     * View a list of users.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\DataTables\UsersDataTable  $table
     * @param  \App\Filters\UserFilters  $requestFilter
     * @return \Illuminate\View\View
     */
    public function index(Request $request, UsersDataTable $table, UserFilters $requestFilter)
    {
        $this->authorize('viewList', User::class);

        if ($request->ajax()) {
            $query = User::with('employment');
            $requestFilter->apply($query);

            return $table->eloquent($query)
                ->addColumn('action', 'users.partials.action-cell')
                ->filterColumn('name', function ($query, $keyword) {
                    $sql = "CONCAT(users.first_name, ' ', users.last_name)  like ?";
                    $query->whereRaw($sql, ["%{$keyword}%"]);
                })
                ->filterColumn('id', function ($query, $keyword) {
                    $query->where($query->qualifyColumn('id'), $keyword);
                })
                ->toJson();
        }

        return view('users.index');
    }
Aug
16
2 months ago
Activity icon

Started a new Conversation Yajra Datatables

I'm using the following package to better display a rendered table of users for my project. The problem is what I would like to do is extract the logic inside of the ajax check to a new Datatable class that extends the package's default Datatable class. The methods that I'm looking at for the class doesn't exactly line up with what I'm doing.

https://github.com/yajra/laravel-datatables

https://yajrabox.com/docs/laravel-datatables/master/editor-tutorial

public function index(IndexUserRequest $request, DataTables $table, UserFilters $requestFilter)
    {
        $this->authorize('viewList', User::class);

        if ($request->ajax()) {
            $query = User::with('employment');
            $requestFilter->apply($query);

            return $table->eloquent($query)
                ->addColumn('action', 'users.partials.action-cell')
                ->filterColumn('id', function ($query, $keyword) {
                    $query->where($query->qualifyColumn('id'), $keyword);
                })
                ->toJson();
        }

        return view('users.index');
    }
Aug
13
2 months ago
Activity icon

Replied to Filter Statuses Array

I ended up going with this in the view.

@foreach (\App\Enums\PlayerStatus::toArray() as $key => $value)
    <option value="{{ $value }}">
        {{ trans('enums.' . \App\Enums\PlayerStatus::class . '.' . constant("\App\Enums\PlayerStatus::$key")) }}
    </option>
@endforeach
Activity icon

Replied to Filter Statuses Array

I am actually using the following package.

https://github.com/mad-web/laravel-enum

What I want to do is have it loop over all of the enums defined in the PlayerStatusEnum file and display the label inside of the value of the option but then display the lang. However, I'm struggling to try and get the lang value shown for the option.

@foreach (\App\Enums\PlayerStatus::toArray() as $key => $value)
    <option value="{{ $value }}">{{ __('enums.'.\App\Enums\PlayerStatus::class.'.'.\App\Enums\PlayerStatus.'::'.$key) }}</option>
@endforeach

lang/en/enums.php

PlayerStatus::class => [
    PlayerStatus::BOOKABLE => 'Bookable',
],
Activity icon

Started a new Conversation Filter Statuses Array

Hey all I'm trying to figure out what's the best way to go for this situation. The code below is coming from a filter form that allows the user to select any possible status to filter the list of players query. So I'm wondering if it would be worth creating a method for the Player model that returns an array of statuses. These statuses are NOT stored in the database, however, each status has an associated scope inside of the Player model. Another reason why I thought it would be a good idea to create a method that returns the array of possible statuses is that when the user submits the form that can filter by the status I have a validation Rule::in() that has the array of statuses.

What are thoughts on this?

@foreach ($statuses as $status)
    <option value="only_{{ strtolower($status) }}">{{ $status }}</option>
@endforeach 

old version looks like this.

<option value="only_bookable">Bookable</option>
<option value="only_pending_introduction">Pending Introduction</option>
<option value="only_retired">Retired</option>
<option value="only_injured">Injured</option>
<option value="only_suspended">Suspended</option>
Jul
28
2 months ago
Activity icon

Replied to Trying To Sync And Update Child Models

Any ideas on this problem?

Jul
26
2 months ago
Activity icon

Replied to Trying To Sync And Update Child Models

I have made a few changes and still running into an issue.

    /**
     * Scope a query to only include current coaches.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     */
    public function scopeCurrentCoaches($query)
    {
        return $query->whereHasMorph('coaches', Coach::class, function ($query) {
            $query->whereNull('left_at');
        });
    }

    /**
     * Scope a query to only include current players.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     */
    public function scopeCurrentPlayers($query)
    {
        return $query->whereHasMorph('players', Player::class, function ($query) {
            $query->whereNull('left_at');
        });
    }
/**
     * Get all coaches that have been members of the team.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphByMany
     */
    public function coaches()
    {
        return $this->morphedByMany(Coach::class, 'member')->using(Member::class)->withPivot(['joined_at', 'left_at']);
    }

    /**
     * Get all players that have been members of the stable.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphByMany
     */
    public function players()
    {
        return $this->morphedByMany(Player::class, 'member')->using(Member::class)->withPivot(['joined_at', 'left_at']);
    }

So now I have the following.

$currentTeamCoaches = $team->currentCoaches()->get()->pluck('id');
$currentTeamPlayers = $team->currentPlayers()->get()->pluck('id');

So now I am having a problem trying to run the scope.

+exception: Symfony\Component\Debug\Exception\FatalThrowableError^ {#5387
      -originalClassName: "TypeError"
      #message: "Argument 1 passed to Illuminate\Database\Eloquent\Builder::getBelongsToRelation() must be an instance of Illuminate\Database\Eloquent\Relations\MorphTo, instance of Illuminate\Database\Eloquent\Relations\MorphToMany given, called in /Users/jeffreydavidson/Projects/Ringside/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php on line 215"`
Activity icon

Started a new Conversation Trying To Sync And Update Child Models

I'm trying to figure out how I can minimize this code block. What I'm trying to do is keep a record of all old and current coaches and players for a specific team. I am currently trying to figure out how I can utilize the updateExistingPivot correctly and the syncWithoutDetatching correctly as well.

I"m only wanting to update the players and coaches that are now referred to as former coaches and players. Would I need a whereIn()? I don't know if that can be done with a pivot?

$newTeamCoaches = $request->input('coaches');
$newTeamPlayers = $request->input('players');

$currentTeamCoaches = $team->players()->current()->get()->pluck('id');
$currentTeamPlayers = $team->coaches()->current()->get()->pluck('id');

$formerTeamCoaches = $currentTeamCoaches->diff(collect($newTeamCoaches));
$formerTeamPlayers = $currentTeamPlayers->diff(collect($newTeamPlayers));

$team->coaches()
    ->updateExistingPivot($formerTeamCoaches, ['left_at' => now()]);

$team->players()
    ->updateExistingPivot($formerTeamPlayers, ['left_at' => now()]);

$team->coaches()->syncWithoutDetaching($newTeamCoaches);
$team->players()->syncWithoutDetaching($newTeamPlayers);
public function scopeCurrent($query)
{
    return $query->whereNull('left_at');
}
Jul
08
3 months ago
Activity icon

Started a new Conversation Data Providers Are They Worth It

I am trying to decide if using data providers for my tests is the best way to go.

Below I have an example of a test where an administrator can update an inactive user to be active. I have a data provider that I can apply to this test that returns an array of two different types of administrator roles. This array of roles are roles that have the ability to perform this action.

I understand for this simple test it would be just as easy to create a new test that assures the same functionality passes for the two different admin types however this starts to get bigger as different conditions are met on whether or not the user can be activated at all.

On the other end of the spectrum, I have 20+ tests that feature endpoint testing that tests form validation fails with passing the post parameters. Those tests all say that a specific role is logged in during those tests but both types of admin roles have the same type of results.

I'm seeking advice as to if many people reach for data providers a lot with situations like this or not or if there are some better alternatives. I've heard that some people will separate out the same tests into separate directories with a directory for each role but seems like a copy and paste for the same test with one minor change. Plus when criteria changes or another role is added you'd have to go in and create an additional directory with more copied tests.

What do you all think?

/** @test */
    public function an_administrator_can_activate_an_inactive_user()
    {
        $this->actAs('administrator');
        $user = factory(User::class)->states('inactive')->create();

        $response = $this->put(route('users.activate', $user));

        $response->assertRedirect(route('users.index'));
        tap($user->fresh(), function ($user) {
            $this->assertTrue($user->is_active);
        });
    }
Jun
09
4 months ago
Activity icon

Replied to How To Order A Product Only Once In Laravel?

I think I've missed the question here. Did you include one?

May
10
5 months ago
Activity icon

Started a new Conversation Packages Not Being Defined

I'm trying to figure out why my Sticky and PerfectScrollbar are not defined when I try and load my page. This error says it's coming from the scripts.bundle.js.

resources/js/scripts.bundle.js

"use strict";
import jQuery from "jquery";
...
...

resources/js/entries/app.js

import "../bootstrap.js";
import "../scripts.bundle.js";

resources/js/bootstrap.js

import jQuery from "jquery";
import Sticky from "sticky-js";
import PerfectScrollbar from "perfect-scrollbar";
import Cookies from "js-cookie";
import Datatables from "datatables";
import "./bootstrappers/datatables.js";
window.$ = jQuery;

webpack.js

const mix = require("laravel-mix");
const endsWith = require("lodash.endswith");
const glob = require("glob");
const output = require("friendly-errors-webpack-plugin/src/output");

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.styles(
    [
        "resources/css/theme/style.bundle.css",
        "resources/css/theme/skins/header/base/light.css",
        "resources/css/theme/skins/header/menu/light.css",
        "resources/css/theme/skins/brand/dark.css",
        "resources/css/theme/skins/aside/dark.css"
    ],
    "public/css/theme.css"
);

mix.styles(
    [
        "resources/vendors/flaticon/flaticon.css",
        "resources/vendors/flaticon2/flaticon.css"
    ],
    "public/css/fonts.css"
);
mix.sass("resources/sass/app.scss", "public/css");

/************************************************************************
 * Copy Static Assets
 ************************************************************************/
mix.copyDirectory("resources/vendors/flaticon/font", "public/css/font");
mix.copyDirectory("resources/vendors/flaticon2/font", "public/css/font");

/************************************************************************
 * Mix Configuration
 * * We aren't keen on the "Build successful" notifications, so disable
 *   them
 * * We load in our webpack.config.js, which just contains aliases so
 *   PHPstorm reads them
 ************************************************************************/
// mix.webpackConfig(require("./webpack.config"));
mix.disableSuccessNotifications();
mix.sourceMaps(false, "inline-source-map");

/************************************************************************
 * Spit out all our entries as individual files
 * * specifically it's anything in resources/js/entries/*
 *   or any child directories, that get made into their own files
 * * It could be simpler, but we also make it output a line in the console
 *   for each entry.
 ************************************************************************/
/** @var {String[]} */
const entries = glob.sync("resources/js/entries/**/*.js");
const buildOutputPath = file =>
    file.replace("resources/js/entries/", "public/js/");
entries
    .filter(entry => !endsWith(entry, "app.js"))
    .forEach(file => {
        output.title("info", "ENTRY", file);
        mix.js(file, buildOutputPath(file));
    });
// We need to manually run this last as otherwise our output path breaks.
mix.js("resources/js/entries/app.js", "public/js/app.js");

// mix.js(["resources/js/scripts.bundle.js"], "public/js/app.js");

/************************************************************************
 * Extract all the vendor files, these are anything that appear in more
 * than ~3 of our entries. These all end up in vendor.js
 ************************************************************************/
mix.extract([
    "jquery",
    "popper.js",
    "bootstrap",
    "js-cookie",
    "moment",
    "tooltip.js",
    "perfect-scrollbar",
    "sticky-js",
    "wnumb",
    "datatables"
]);

May
06
5 months ago
Activity icon

Replied to Clear Viewed Episodes In Series

Go to the series you are wanting to rewatch and you can unclick the button on the lesson that says Lesson Completed. It should update with making it unwatched.

Activity icon

Replied to Clear Viewed Episodes In Series

You can still access series and rewatch them now even if you've watched them before.

Apr
28
5 months ago
Activity icon

Replied to Sending String Parameter From Route To View

@neeonline Doesn't your first suggestion add logic to the view. I was starting to think about a view composer but not sure if that is the right direction.

Apr
27
5 months ago
Activity icon

Replied to Internal Api Requests

Ah okay. Take a look at the other responses on that post. More people are saying to use app()->handle() rather than Route::dispatch().

Activity icon

Replied to Internal Api Requests

Well, I don't believe there is a dispatch method on the Route class or a create method on the Request class.. Where did you see these methods?

Apr
26
5 months ago
Activity icon

Replied to Sending String Parameter From Route To View

There may be some misunderstanding. Is there a way I can with a view composer or something to where on any index page it will show the state as capitalized when the variable is being requested.

Activity icon

Replied to Sending String Parameter From Route To View

@patickadvance You are taking away the state getting put through the String title helper though. So that doesn't answer the question.

Activity icon

Started a new Conversation Sending String Parameter From Route To View

I am trying to think of any better way to send through a string that has retrieved from a route parameter and has been run through a title string helper and echoed out into the view. The reason being is a have many other modules that share this same functionality and would like to make it easier to manage across all instances.

So I'm trying to figure out what would be the best strategy so that I don't have to continue adding the Str::title($state) and pass it to the view on every module that uses it. Is there a more strategic way of moving that logic somewhere.

Route::get('/users/state/{state?}', '[email protected]')->name('users.index');
Route::get('/students/state/{state?}', '[email protected]')->name('teachers.index');
Route::get('/teachers/state/{state?}', '[email protected]')->name('teachers.index');

UsersController

public function index($state = 'active')
{
    $users = User::hasState($state)->get();
    $state = Str::title($state);

    return response()->view('users.index', compact('users', 'state'));
}

StudentsController

public function index($state = 'active')
{
    $students = Student::hasState($state)->get();
    $state = Str::title($state);

    return response()->view('students.index', compact('students', 'state'));
}

TeachersController

public function index($state = 'active')
{
    $teachers = Teacher::hasState($state)->get();
    $state = Str::title($state);

    return response()->view('teachers.index', compact('teachers', 'state'));
}

Users/index.blade.phjp

{{ $state }} Users

Teachers/index.blade.phjp

{{ $state }} Teachers

Students/index.blade.phjp

{{ $state }} Students