kjdion84

kjdion84

Member Since 3 Years Ago

Experience Points 3,970
Experience Level 1

1,030 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 21
Lessons
Completed
Best Reply Awards 1
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.

07 Mar
1 year ago

kjdion84 started a new conversation Eager Loading For Gate

Lets say I am coding a forum and want to check if a user has permission to edit/delete their own posts.

The people with permission to do this are admins, mods of the posts' forum, and the poster themselves.

Each User has a boolean for admin, which is true if they are an admin.

Each User also has a mod_forums relationship which represents the forums they are a moderator of.

Each Post has a forum relationship which represents the forum the post belongs to.

For the admin part, this is easy:

Gate::before(function ($user) {
    if ($user->admin) {
        return true;
    }
});

So if a User is an admin, they can do anything.

For the post owner part, this is also easy using route model binding:

Gate::define('edit-post', function ($user, $post) {
    return $user->id == $post->user_id;
});

Now here is where I am stuck. I want to make sure that the auth User mod_forums is loaded eagerly so that I don't have a query for every single post checked in a thread.

Example:

@foreach($posts as $post)
    {{ $post->title }}
    <br>
    @can('edit-post', $post)
        <a href="#">Edit</a>
        <a href="#">Delete</a>
    @endcan
@endforeach

Let's say I was using this code:

Gate::define('edit-post', function ($user, $post) {
    $user->load('mod_forums');

    if ($user->mod_forums->contains('id', $post->forum->id)) {
        return true;
    }

    return $user->id == $post->user_id;
});

Would this execute a query on every single check in order to obtain the user mod_forums? I want to make it so that the relationship isn't reloaded every single time the permission is checked, especially when it is checked within a loop.

Edit: I'm thinking loadMissing() does what I want here? Does it persist to each separate Gate call?

11 Sep
1 year ago

kjdion84 started a new conversation Gate Define Doesnt Work

It only works if I'm logged in as a user with "Admin" role. It does not work even when I absolutely know that the $user->id == $concept->user_id.

Blade:

    @can('Own Concept', $concept)
        <div class="float-right">
            <button type="button" class="btn btn-primary btn-sm" data-toggle="tooltip" title="Update"><i class="fa fa-pencil"></i></button>
            <button type="button" class="btn btn-danger btn-sm" data-toggle="tooltip" title="Delete"><i class="fa fa-trash"></i></button>
        </div>
    @endcan

AuthServiceProvider:

        Gate::define('Own Concept', function ($user, $concept) {
            if ($user->roles->contains('name', 'Admin')) {
                return true;
            }

            return $user->id == $concept->user_id;
        });
07 Sep
1 year ago

kjdion84 started a new conversation Best Practices For Other Laravel Package Resources?

I'm working on a package that uses a bunch of stub file templates for a custom CRUD generator command. So these are not views, but a collection of templates for models, controllers, etc.

Now, I know that my package views should publish to the resources/views/vendor/package folder:

    $this->publishes([__DIR__ . '/../resources/views' => resource_path('views/kjdion84/turtle')], 'views');

But what about resources that are not views? For example, I want to make a crud folder in the resources folder.

Should I put them in resources/vendor/package/crud, resources/crud/vendor/package, or just resources/crud?

What is the best practice in this case?

14 Aug
2 years ago

kjdion84 left a reply on Prevent Model From Firing Update Event After Call Save()

$model->attribute = 'New Value';
$model->unsetEventDispatcher();
$model->save();
14 Jul
2 years ago

kjdion84 started a new conversation Laravel Datatables Searching BelongsToMany Name

I'm trying to search datatables by the name column of a table in a belongsToMany relationship. In this case, the table is tags.

Here are the tables in question:

    Schema::create('leads', function (Blueprint $table) {
        $table->increments('id');
        $table->text('data');
        $table->timestamps();
    });

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

    Schema::create('tag_lead', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('lead_id');
        $table->integer('tag_id');
    });

Here is my model code:

    class Lead extends \Eloquent
    {
        public function tags()
        {
            return $this->belongsToMany('App\Tag');
        }
    }

Here is my controller code:

    $leads = Lead::with('tags')->get();

    return Datatables::of($leads)
        ->filterColumn('tags', function($query, $keyword) {
            $query->whereRaw('tags.name like ?', ['%'.$keyword.'%']);
        })
        ->make(true);

Here is my JS code:

    $('#leads-datatable').DataTable({
        ajax: '{{ route('backend.leads.datatable') }}',
        columns: [
            { data: 'id' },
            { data: 'data' },
            { data: 'tags', sortable: false },
            { data: 'created_at' },
            { data: 'updated_at' }

        ]
    });

This does not work and produces error mb_strtolower() expects parameter 1 to be string, array given.

I just want datatables to search all the tag names for each lead. How do I do this?

18 Jun
2 years ago

kjdion84 left a reply on Blade Auth()->user() Trying To Get Property Of Non-object

dd(auth()->user()):

User {#230 ▼
  #fillable: array:3 [▶]
  #hidden: array:2 [▶]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:7 [▶]
  #original: array:7 [▶]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: array:1 [▶]
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
  #rememberTokenName: "remember_token"
}

kjdion84 left a reply on Blade Auth()->user() Trying To Get Property Of Non-object

Check the code, particularly @if (auth()->guest()) at the top.

Are you saying that blade will try and execute the @if (auth()->user()->hasAnyPermission(['View Users', 'View Roles'])) conditional despite the fact that it is in the @else statement?

kjdion84 started a new conversation Blade Auth()->user() Trying To Get Property Of Non-object

I'm using spatie permissions package: https://github.com/spatie/laravel-permission

The package does not have a directive to check if a user has any permission, though method hasAnyPermission does exist.

I'm trying to use the following conditional in blade:

@if (auth()->user()->hasAnyPermission(['View Users', 'View Roles']))

This is causing a Trying to get property of non-object of error.

Why is this happening?

EDIT

I am going to post more of the code in the layout:

    @if (auth()->guest())
        <!-- Guest Menu -->
        <li {{ (request()->is('login') ? 'class=active' : '') }}><a href="{{ route('login') }}">Login</a></li>
        @if (config('lion.allow_registration'))
            <li {{ (request()->is('register') ? 'class=active' : '') }}><a href="{{ route('register') }}">Register</a></li>
        @endif
    @else
        <!-- Auth Menu -->
        @if (auth()->user()->hasAnyPermission(['View Users', 'View Roles']))
            <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                    Settings <span class="caret"></span>
                </a>
                <ul class="dropdown-menu" role="menu">
                    @can('View Users')
                        <li {{ (request()->is('users') ? 'class=active' : '') }}><a href="{{ route('users') }}">Users</a></li>
                    @endcan
                    @can('View Roles')
                        <li {{ (request()->is('roles') ? 'class=active' : '') }}><a href="{{ route('roles') }}">Roles</a></li>
                    @endcan
                </ul>
            </li>
        @endif
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                {{ auth()->user()->name }} <span class="caret"></span>
            </a>
            <ul class="dropdown-menu" role="menu">
                <li {{ (request()->is('profile') ? 'class=active' : '') }}><a href="{{ route('profile') }}">Profile</a></li>
                <li><a href="{{ route('logout') }}">Logout</a></li>
            </ul>
        </li>
    @endif 

This codes works perfectly without the conditional statement @if (auth()->user()->hasAnyPermission(['View Users', 'View Roles'])).

14 May
2 years ago

kjdion84 left a reply on How To Use Events With Standalone Eloquent?

sceithamer you are amazing! That worked perfectly for my trait.

You don't even have to create an Oberserver class, you can just call setEventDispatcher and then handle the events statically.

Example:

            // dispatch events
            static::setEventDispatcher(new Dispatcher());
            static::saving(function ($model) {
                $model->tenant_id = App::$tenant->id;
            });
11 May
2 years ago

kjdion84 started a new conversation Eloquent Datatables Not Applying Where(), OrderBy(), Etc

I've written a class which takes an Eloquent Model and manipulates it in order to output JSON for a datatable. The datatable uses server side processing via a POST request.

Datatable library URL: https://datatables.net

Here is the class:

namespace App\Helpers;

class Datatable {
    public static $request;
    public static $model;
    public static $records_total;
    public static $records_filtered;

    static function make ($request, $model) {
        self::$request = $request;
        self::$model = $model;
        self::setRecordsTotal();
        self::filter();
        self::setRecordsFiltered();
        self::orderLimit();
        self::renderJson();
    }

    // set total record count
    static function setRecordsTotal () {
        self::$records_total = self::$model->count();
    }

    // filter by search query
    static function filter () {
        if (!empty(self::$request['search']['value'])) {
            foreach (self::$request['columns'] as $column) {
                if ($column['searchable'] == 'true') {
                    self::$model->where($column['data'], 'LIKE', '%'.self::$request['search']['value'].'%');
                }
            }
        }
    }

    // set filtered record count
    static function setRecordsFiltered () {
        self::$records_filtered = self::$model->count();
    }

    // apply order by & limit
    static function orderLimit () {
        self::$model->orderBy(self::$request['columns'][self::$request['order'][0]['column']], self::$request['order'][0]['dir']);
        self::$model->skip(self::$request['start'])->take(self::$request['length']);
    }

    // render json output
    static function renderJson () {
        $array = [];
        $array['draw'] = self::$request['draw'];
        $array['recordsTotal'] = self::$records_total;
        $array['recordsFiltered'] = self::$records_filtered;
        $array['data'] = [];
        $results = self::$model->get();

        foreach ($results as $result) {
            $array['data'][] = $result->toArray();
        }

        echo json_encode($array);
    }
}

Here is how I call the class:

Datatable::make($_POST, new User());

So User() is an Eloquent model in this instance.

Now, the initial rendering of the datatable works great. However, when I try and search or order it, it seems like my code within the filter() and orderLimit() methods is not being applied, because it just keeps spitting out the exact same results in the exact same order.

Why are my where(), orderBy(), etc. not being applied to the Model properly?

01 May
2 years ago

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

Session. Otherwise all controllers inside the route group will need $subdomain as a parameter in their methods, which is ugly as shit.

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

The only solution I came up with was to use a middleware which grabs the subdomain via getHost(). Not an elegant solution at all.

30 Apr
2 years ago

kjdion84 started a new conversation Middleware To Skip Route Group

Let's say I have the following routes file:

Route::group(['middleware' => 'foo.only'], function () {
    Route::get('/', '[email protected]');
    Route::get('/about', '[email protected]');
});

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

In my FooOnlyMiddleware handler I have something like:

public function handle($request, $next)
{
    if ($foo == true) {
        return $next($request);
    }
    else {
        // skip the entire route group and move onto the next route
    }
}

How do I do this so that if $foo = false it will skip the entire route group and move onto the bar routes?

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

Do you think storing the tenant domain in the session is the best approach?

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

I think I'm getting closer but this is just frustrating.

In my login view I have the following line:

<form class="form-horizontal" role="form" method="POST" action="{{ route('login') }}">

I'm assuming it wants me to pass the tenant_domain parameter within {{ route('login') }}, right?

But this is already acquired by the route group. So how is this supposed to work?

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

It doesn't work either way. If I comment out the forgetParameter in my middleware, the result is the same.

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

No, my issue is that it seems the Auth routes are still requiring the tenant_domain parameter even though I've specifically called forgetParameter on it in my tenant middleware.

Because it all works when I remove the domain/tenant group wrapper.

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

The tenant domain is a wildcard. I want to forget the parameter because after the middleware uses it, it has no other purpose.

Basically, when the user visits myapp.com I want it to point to my homepage. If they visit tenantdomain.myapp.com, it should access their own app backend. Each tenant has complete control of the users of their app.

Heres my entire routes file so you can see what I'm trying to do:

<?php

// tenant routes
Route::group(['domain' => '{tenant_domain}.'.config('laravel-backend.domain'), 'middleware' => 'tenant'], function () {
    Route::get('/', function () {
        // send to dashboard/login based on auth
        if (Auth::check()) {
            return redirect()->route('dashboard');
        } else {
            return redirect()->route('login');
        }
    });

    Route::group(['middleware' => 'guest'], function () {
        // login routes
        Route::get('login', 'Auth\[email protected]')->name('login');
        Route::post('login', 'Auth\[email protected]');

        // password reset routes
        Route::get('password/reset', 'Auth\[email protected]')->name('password.request');
        Route::post('password/email', 'Auth\[email protected]')->name('password.email');
        Route::get('password/reset/{token}', 'Auth\[email protected]')->name('password.reset');
        Route::post('password/reset', 'Auth\[email protected]');
    });

    Route::group(['middleware' => 'auth'], function () {
        // dashboard route
        Route::get('dashboard', '[email protected]')->name('dashboard');

        // auth user routes
        Route::get('profile/update', '[email protected]')->name('profile.update');
        Route::post('profile/update', '[email protected]');
        Route::get('logout', 'Auth\[email protected]')->name('logout');

        // user routes
        Route::group(['middleware' => 'permission:View Users'], function () {
            Route::get('users', '[email protected]')->name('users');
            Route::get('users/datatable', '[email protected]')->name('users.datatable');
        });
        Route::group(['middleware' => 'permission:Create Users'], function () {
            Route::get('users/create', '[email protected]')->name('users.create');
            Route::post('users/create', '[email protected]');
        });
        Route::group(['middleware' => 'permission:Edit Users'], function () {
            Route::get('users/{id}/edit', '[email protected]')->name('users.edit');
            Route::patch('users/{id}/edit', '[email protected]');
        });
        Route::group(['middleware' => 'permission:View Users Activity'], function () {
            Route::get('users/{id}/activity', '[email protected]')->name('users.activity');
            Route::get('users/{id}/activity/datatable', '[email protected]')->name('users.activity.datatable');
            Route::get('users/{id}/activity/details', '[email protected]')->name('users.activity.d');
        });
        Route::get('users/{id}/delete', '[email protected]')->name('users.delete')->middleware('permission:Delete Users');

        // user role routes
        Route::group(['middleware' => 'permission:View Roles'], function () {
            Route::get('roles', '[email protected]')->name('roles');
            Route::get('roles/datatable', '[email protected]')->name('roles.datatable');
        });
        Route::group(['middleware' => 'permission:Create Roles'], function () {
            Route::get('roles/create', '[email protected]')->name('roles.create');
            Route::post('roles/create', '[email protected]');
        });
        Route::group(['middleware' => ['permission:Edit Roles', 'not.admin']], function () {
            Route::get('roles/{id}/edit', '[email protected]')->name('roles.edit');
            Route::patch('roles/{id}/edit', '[email protected]');
        });
        Route::get('roles/{id}/delete', '[email protected]')->name('roles.delete')->middleware('permission:Delete Roles', 'not.admin');
    });
});

// homepage routes
Route::get('/', '[email protected]');

I just don't understand why it isn't working.

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

<?php

namespace App\Http\Middleware;

use App\Tenant;
use HipsterJazzbo\Landlord\Facades\Landlord;

class TenantMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, $next)
    {
        $tenant = Tenant::where('domain', $request->route('tenant_domain'))->firstOrFail();

        Landlord::addTenant('tenant_id', $tenant->id);

        $request->route()->forgetParameter('tenant_domain');

        return $next($request);
    }
}

Is causing:

UrlGenerationException in UrlGenerationException.php line 17:
Missing required parameters for [Route: login] [URI: login].
in UrlGenerationException.php line 17
at UrlGenerationException::forMissingParameters(object(Route)) in RouteUrlGenerator.php line 90
at RouteUrlGenerator->to(object(Route), array(), true) in UrlGenerator.php line 320
at UrlGenerator->toRoute(object(Route), array(), true) in UrlGenerator.php line 301
at UrlGenerator->route('login', array()) in Redirector.php line 154
at Redirector->route('login') in web.php line 21
at Router->{closure}() in Route.php line 189
at Route->runCallable() in Route.php line 163
at Route->run() in Router.php line 559
at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 30
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in TenantMiddleware.php line 25
at TenantMiddleware->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in SubstituteBindings.php line 41
at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 65
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Router.php line 561
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 520
at Router->dispatchToRoute(object(Request)) in Router.php line 498
at Router->dispatch(object(Request)) in Kernel.php line 174
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 30
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ValidatePostSize.php line 27
at ValidatePostSize->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Kernel.php line 149
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 53

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

Yes, the code you posted is exactly what I am using now, yet the Auth routes still do not work and are still requiring the tenant_domain parameter.

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

You are correct.

I have a tenants table, and a tenant can have any number of users (which uses the Laravel Auth scaffolding). I've added a tenant_id to my users table which is handled by the model trait BelongsToTenants.

My tenant middleware sets the tenant_id using the tenant_domain. After that, the tenant_domain should be forgotten for all subroutes within the group. This is working fine for all of my routes except ones which use the Auth scaffolding.

kjdion84 left a reply on How Can I Set Auth::routes() With A Dynamic Subdomain

Did you figure this out? Having the exact same issue.

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

Apparently this error only occurs with the auth scaffolding routes....any idea why?

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

I put $request->route()->forgetParameter('tenant_domain'); in the middleware handler and that did not fix it.

29 Apr
2 years ago

kjdion84 left a reply on Do Not Require Subroutes To Use Route Group Parameter

<?php

namespace App\Http\Middleware;

use HipsterJazzbo\Landlord\Facades\Landlord;

class TenantMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, $next)
    {
        Landlord::addTenant('tenant_id', $request->route('tenant_domain'));

        return $next($request);
    }
}

Its using a package that automatically assigns the particular tenant_id to all eloquent queries using a trait in my model classes.

Example:

<?php

namespace App;

use HipsterJazzbo\Landlord\BelongsToTenants;
use Spatie\Permission\Models\Role as SpatieRole;

class Role extends SpatieRole
{
    use BelongsToTenants;
}

Therefore, I don't have to actually utilize the $tenant_domain in the models themselves, so including it in every single controller method for the aforementioned routes is pointless.

Package I'm using is here: https://github.com/HipsterJazzbo/Landlord

kjdion84 started a new conversation Do Not Require Subroutes To Use Route Group Parameter

Posted on SO but don't seem to be getting an answer so I was wondering if you guys could help me.

Lets say I have the following code:

Route::group(['domain' => '{tenant_domain}.myapp.com', 'middleware' => 'tenant'], function () {
    Route::get('/', function () {
        // send to dashboard/login based on auth
        if (Auth::check()) {
            return redirect()->route('dashboard');
        } else {
            return redirect()->route('login');
        }
    });

    Route::group(['middleware' => 'guest'], function () {
        // login routes
        Route::get('login', 'Auth\[email protected]')->name('login');
        Route::post('login', 'Auth\[email protected]n');

        // password reset routes
        Route::get('password/reset', 'Auth\[email protected]')->name('password.request');
        Route::post('password/email', 'Auth\[email protected]')->name('password.email');
        Route::get('password/reset/{token}', 'Auth\[email protected]')->name('password.reset');
        Route::post('password/reset', 'Auth\[email protected]');
    });
});

The tenant middleware utilizes the tenant_domain but none of the controllers inside the group do. I want to make it so that none of the subroutes require tenant_domain as a parameter in their controllers.

How do I do this?

To reiterate: I want the tenant_domain to be required for the route group, but I do not want to have every route in the group require this parameter as it is being utilized in the middleware only. I've tried using forgetParamater in the tenant middleware and that didn't work.

26 Apr
2 years ago

kjdion84 left a reply on L5 - Best Way To Get User Timezone

Sorry for ressing this thread, but using momentjs does not mutate the time strings to their appropriate timezone when selecting data via relationships.

25 Apr
2 years ago

kjdion84 started a new conversation Telling Eloquent What To Use As Class Name

I've got the following class which works:

<?php

namespace App;

use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Permission\Models\Role as SpatieRole;

class Role extends SpatieRole
{
    use LogsActivity;

    /**
     * The attributes that should be logged.
     *
     * @var array
     */
    protected static $logAttributes = ['name'];
}

However, I'd like to rename this class to UserRole, but its causing database column not found errors in belongsToMany relationship tables when I try.

How do I make this work? I've already tried adding:

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'roles';

kjdion84 left a reply on Where Are You All From?

Oshawa Ontario.

kjdion84 left a reply on Recommended Admin Packages?

Voyager was already mentioned, backpack also looks decent: https://github.com/Laravel-Backpack

kjdion84 left a reply on Array Validation Rules Not Working

Iterate through each array item and use a validator for each item.

kjdion84 started a new conversation Validation Rule UI

Does a package exist that allows me to create forms for my dynamic fields in order to specify Laravel validation rules per field?

22 Apr
2 years ago

kjdion84 left a reply on How To Populate Timezone Selectbox In Laravel 5

<select name="timezone" id="timezone" class="form-control">
    @foreach (timezone_identifiers_list() as $timezone)
        <option value="{{ $timezone }}"{{ $timezone == old('timezone') ? ' selected' : '' }}>{{ $timezone }}</option>
    @endforeach
</select>

Laravel utilizes this PHP function.

kjdion84 left a reply on L5 - Best Way To Get User Timezone

I did this by following these steps:

  • Create a migration adding a timezone string column in the users table with a default of config('app.timezone').

  • Add a <select> in your user updating forms:

<select name="timezone" id="timezone" class="form-control">
    @foreach (timezone_identifiers_list() as $timezone)
        <option value="{{ $timezone }}"{{ $timezone == old('timezone', request()->user()->timezone) ? ' selected' : '' }}>{{ $timezone }}</option>
    @endforeach
</select>
  • Add timezone to $fillable in the User model. My user profile controller uses fill() in order to update the users info via all().

  • Make the validation rule required|timezone for this field.

kjdion84 left a reply on Onclick Disable Submit Button

Disable every form from double-submitting and add a fontawesome loading spinner to its submit button :)

    $('form').submit(function (event) {
        if ($(this).hasClass('submitted')) {
            event.preventDefault();
        }
        else {
            $(this).find(':submit').html('<i class="fa fa-spinner fa-spin"></i>');
            $(this).addClass('submitted');
        }
    });
20 Apr
2 years ago

kjdion84 started a new conversation Question About Customer Databases

Does each customer have their own database instance in Spark?

18 Jul
3 years ago

kjdion84 left a reply on Using An Admin Theme

Just update your layouts.app view (resources/views/layouts/app.blade.php) to use the header & footer from the HTML code that is provided by the template you purchased. You'll also need to include any CSS/JS in your public folder that came with the template.

The template will have a documentation/demo where you can just view the source and copy the coding for each element you want to implement.

kjdion84 left a reply on Authentication Always Fail

I recommend you look at the built-in auth scaffolding and modify it to suit your needs. It already has working login, registration, and password resetting. You can use the Hash facade in order to seed the user table with a password.

php artisan make:auth

17 Jul
3 years ago

kjdion84 left a reply on How To Deploy Laravel Project On VPS And How To Manage Changes?

There is also deploybot, which allows you to manually or automatically deploy your repository commits via FTP/SFTP/SSH/etc.

https://deploybot.com/

That's what I use ( although I'm about to write my own app that does this with Laravel :) ).

kjdion84 left a reply on Best Place To Declare Possible Permissions?

I think I like the idea of just having them in a custom config array, so I don't have to create new migrations each time I want to add new permissions.

So create a permissions.php file in my config folder with something like:

return  [
    'permissions' => [
        'create-posts', 
        'read-posts', 
        'update-posts'
    ]
];

Kind of like how Laravel Doctrine does it. Thank you @kfirba.

kjdion84 started a new conversation Best Place To Declare Possible Permissions?

I'm working with the Laravel ACL and I have a quick question - where should I put my "possible permissions", as in, a list of all the permissions a user can be given?

I was thinking of creating a Permission model and putting them all in a database table, but creating an extra database query just for that seems kind of overkill.

Any suggestions would be much appreciated.

kjdion84 started a new conversation PHPStorm Migration Method Warnings

I have the IDE helper dependency installed and for the most part everything is OK. However, I just noticed in my migrations there are still method warnings.

See this screenshot: https://snag.gy/KJpBob.jpg

I already tried installing the Laravel plugin on top of using the IDE helper, the warnings were still there. Is there a way to fix this?

16 Jul
3 years ago

kjdion84 left a reply on Setup Laravel 5 Through PHPStorm Via Composer For WampServer 3

@d3xt3r Uh...because some people might prefer using WampServer over a Vagrant box?

Also, the first 2 steps come naturally after you've done it once or twice (you only need to configure Composer paths in PHPStorm once). The other 2 steps are simply adding the IDE helper dependency and a virtual host. Not really a huge pain in the ass as doing this takes all of 30 seconds.

You forgot to add all the steps involved in installing Homestead, not to mention installing additional tools such as PHPMyAdmin which come with WampServer out of the box.

kjdion84 started a new conversation Setup Laravel 5 Through PHPStorm Via Composer For WampServer 3

This is a small guide for people to help get them started with Laravel 5 on Windows using PHPStorm 2016 and WampServer 3. I am creating this because it was a little frustrating for me as a Laravel newbie to get started in my local environment, and I had to go through several sources to get things running smoothly. So after almost breaking my keyboard with my forehead and figuring everything out, here is how I did it.

In this guide you will have already installed:

Step 1: Configure Composer in PHPStorm

  • Go to Settings -> Languages & Frameworks -> PHP -> Composer
  • Set the PHP executable path to C:\wamp\bin\php\php5.6.19\php.exe
  • Set the composer.phar path to C:\ProgramData\ComposerSetup\bin\composer.phar

Step 2: Create new Laravel project in PHPStorm (via Composer)

  • Go to File -> New Project
  • Select Composer Project on the left-hand side
  • Enter the Location you want Laravel to be installed in i.e. C:\wamp\www\my-awesome-project
  • Select Use existing composer.phar and ensure the path is there
  • Search for laravel/laravel in Filter packages and select it, you can leave the version as <default>
  • Ensure the path to the PHP executable is also set below (scroll down if you don't see it)
  • Click Create
  • Add /.idea to your .gitignore file

Step 3: Add the IDE helper dependency

  • Go to Tools -> Composer -> Add dependency...
  • Search for barryvdh/laravel-ide-helper
  • Click on the newest NON--dev version and Install
  • Add line to providers array in config/app.php - Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
  • Go to Tools -> Run Command... then enter php artisan ide-helper:generate in the command prompt

Step 4: Add vhost to WampServer

  • Make sure WampServer is running and navigate to http://localhost in your browser
  • Click Add a Virtual Host under Tools
  • Enter a name for the vhost like myawesomeproject
  • Enter path to public folder for vhost like c:/wamp/www/my-awesome-project/public
  • Right click the WampServer icon in the taskbar, go to Tools -> Restart DNS

You should now be able to visit http://myawesomeproject in your browser and it will display your Laravel project. Now all that's left to do is configure your environments and write your app.