Indemnity83

Indemnity83

Member Since 3 Years Ago

Sacramento

Electrical Design Engineer at RagingWire Data Centers

Experience Points 78,840
Experience Level 16

1,160 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 675
Lessons
Completed
Best Reply Awards 15
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

06 Jan
5 months ago

Indemnity83 left a reply on Unknown Plugin "transform-object-rest-spread"

I removed the symlink and wrote a script to copy the folder over when I made changes.

Not elegant but it was easy.

16 Nov
7 months ago

Indemnity83 left a reply on Unknown Plugin "transform-object-rest-spread"

Turns out this was because caused by trying to symlink the library into the project.

07 Nov
7 months ago

Indemnity83 started a new conversation Unknown Plugin "transform-object-rest-spread"

First off, maybe my search-fu isn't up to par or I don't have a good enough understanding of the issue to apply solutions found elsewhere, but I did search for this answer before coming here.

Long story short I'm trying to break my Vue UI up in a way very similar (basically identical) to Laravel Spark, where mix is told to add a vendor library to the modules which contains the core business logic and is extended as Vue mixins on the consuming side.

However, even when I try to build up a skeleton of this architecture mix complians that I'm using an Unknown plugin "transform-object-rest-spread" and I haven't been able to get to the bottom of that.

In my library code I have a resources/js/modpacks folder with a current-modpacks.js file which contains the following:

module.exports = {
    /*
     * The component's data.
     */
    data() {
        return {
            modpacks: []
        }
    }
};

then in my host application, I have a similar current-modpacks.js file located in resources/js/components/solder/modpacks/current-modpacks.jswhich imports the core file and applies it as a mixin:

var base = require('modpacks/current-modpacks');

Vue.component('spark-current-modpacks', {
    mixins: [base]
});

The final piece to the puzzle is telling webpack (through mix) to include the library JS as a module:

const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | 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
    .js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .webpackConfig({
        resolve: {
            modules: [
                path.resolve(__dirname, 'vendor/technicpack/solder-framework/resources/js'),
                'node_modules'
            ],
            alias: {
                'vue$': mix.inProduction() ? 'vue/dist/vue.min' : 'vue/dist/vue.js'
            }
        }
    });

Even this simple of an implementation results in an error though, the full dump:

ERROR in .-framework/resources/js/modpacks/current-modpacks.js
Module build failed: ReferenceError: Unknown plugin "transform-object-rest-spread" specified in "base" at 0, attempted to resolve relative to "/Users/kyleklaus/technicpack/solder-framework/resources/js/modpacks"
    at /Users/kyleklaus/technicpack/solder/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17
    at Array.map (<anonymous>)
    at Function.normalisePlugins (/Users/kyleklaus/technicpack/solder/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/Users/kyleklaus/technicpack/solder/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at OptionManager.init (/Users/kyleklaus/technicpack/solder/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/Users/kyleklaus/technicpack/solder/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/Users/kyleklaus/technicpack/solder/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/Users/kyleklaus/technicpack/solder/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/Users/kyleklaus/technicpack/solder/node_modules/babel-loader/lib/index.js:50:20)
    at /Users/kyleklaus/technicpack/solder/node_modules/babel-loader/lib/fs-cache.js:118:18
    at ReadFileContext.callback (/Users/kyleklaus/technicpack/solder/node_modules/babel-loader/lib/fs-cache.js:31:21)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:235:13)
 @ ./resources/js/components/solder/modpacks/current-modpacks.js 1:11-47
 @ ./resources/js/app.js
 @ multi ./resources/js/app.js ./resources/sass/app.scss

I'm not sure what I'm doing wrong; anybody have any thoughts?

Indemnity83 left a reply on User Current Team During API Calls

For anybody who comes across this thread, here is what I ended up doing. In the end, requiring the team to be identified in the URI was the only real choice and I've built a convention now that at least works for me.

My TeamScope looks like this now:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class TeamScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $team = request()->route('team');

        $builder->where(
            'team_id', '=', $team->id
        );
    }
}

So I'm now grabbing the team directly from the request (if you're not using Spark, you'll also need to set up explicit route model binding to resolve team from the URL)

My original concern with this method was now how do I tweak all the routes so the URI has the {team_id} in it without completely duplicating my frameworks route list. For this, I ended being more explicit about my route registration in the framework service provider:

<?php


namespace TechnicPack\SolderFramework;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

class SolderFrameworkServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        // Register framework resources
        $this->registerRoutes();
    }

    /**
     * Register Solder's routes.
     */
    private function registerRoutes()
    {
        // If the routes have not been cached, we will include them in a route group
        // so that all of the routes will be conveniently registered to the given
        // controller namespace. After that we will load the Solder routes file.
        if (! $this->app->routesAreCached()) {
            Route::name('api.')
                ->namespace('TechnicPack\SolderFramework\Http\Controllers')
                ->prefix(Solder::$apiRoutePrefix)
                ->group(function ($router) {
                    require __DIR__.'/Http/routes.php';
                });
        }
    }
}

The key thing here is that the prefix call points to a static class which contains a default prefix of '/api' but can easily be overridden (you could do this with a config parameter too if you wanted).

<?php

namespace TechnicPack\SolderFramework;

class Solder
{
    /**
     * The string prefix for all solder api routes.
     *
     * @var string
     */
    public static $apiRoutePrefix = 'api';

    /**
     * Set the uri to prefix api routes with.
     *
     * @param $prefix
     *
     * @return Solder
     */
    public static function prefixApiRoutesWith($prefix)
    {
        self::$apiRoutePrefix = $prefix;

        return new static();
    }
}

Now, in my Spark application service provider I can override the prefix for all of my framework routes and inject the {team} into the URI:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use TechnicPack\SolderFramework\Solder;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register()
    {
        Solder::prefixApiRoutesWith('{team}/api');
    }
}
04 Nov
7 months ago

Indemnity83 started a new conversation User Current Team During API Calls

I'm wondering if anybody has come up with an elegant solution to team switching in API calls.

I've currently got a global scope that I apply which will limit results to the user's current team

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class TeamScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        /** @var User $user */
        $user = auth()->user();

        $builder->where(
            'team_id', '=', $user->currentTeam()->id
        );
    }
}

This works great, particularly when consuming my API on the front-end. Team switching etc is all great.

But its really confusing for external consumers because the results are scoped to a specific team, but there is nothing in the request which defines the team (its whatever team the user was last using on the web). It's even worse if the users are active on the front-end as its possible for two calls to the same API endpoint to return different results if the user changes teams between the calls.

Basically, the call to $user->currentTeam() prevents the API call from being (stateless)[https://restfulapi.net/rest-architectural-constraints/#stateless]

So obviously I need to get the team id or slug into the request; I can imagine a couple of ways to do this, but each has trade-offs (note, I've used team_id below, but team_slug could be substituted too).

  • Accept a ?team_id= query parameter which, if provided is used instead of the state. This is pretty straight forward, if a bit a-typical, and although its technically optional its practically required on all API requests for any third-party consumer: 'team_id', '=', request('team_id', $user->currentTeam()->id)
  • Require the team_id in the URI so that URI's end up looking like /{team_id}/api/posts. Then use the URI param to scope results. This is probably the best solution from the perspective of a third-party consumer, but makes my use of a global scope less practical, since every API controller method is going to accept the team and filter inside the controller method. (maybe there is a way to pop a parameter off of the request I'm not aware of?)
  • Add team_id as a header to requests. This is ugly, it is really no different than the query parameter except that now client endpoint caching is hosed and building a request is awkward, I'm really only listing it here for completeness.
13 Oct
1 year ago

Indemnity83 left a reply on Using Flysystem-aws-s3-v3 With Another S3 System Other Than Amazon

@robjbrain I just never encountered it. I only needed to connect to one service.

09 Jun
2 years ago

Indemnity83 left a reply on [Suggestion Needed] Generate Large And Secure Unique Codes, Yet Easy To Query

I'm no security expert either; but I guess I don't see how the makeup of the un-hashed code makes any difference to the security.

If you don't need cryptographically secure hashing, use hashid's but don't store the hased value in the DB anywhere. You populate a table with 50,000 records, each with an auto incrementing ID. You use HashIDs to generate 50,000 hashed codes from those IDs and send out the hashes. When somebody comes to the site, you accept the HashID string, and determine the record ID.

If you want cryptographically secure hasing, generate 50,000 random strings statically somewhere, and run them through a one-way encryption (like bcrypt) and store that value in the DB. You can index that column for speed, but 50,000 records isn't crazy to search against. Then when a user enters the code just use that as the record locator.

08 Jun
2 years ago

Indemnity83 left a reply on Laravel Phpunit Testing Mail Sending

Are you tied to Laravel 5.1? Laravel 5.3 added simple mail fakes you can use for your tests.

If you're tied to 5.1 then you need to swap the mail class for your own fake or mock as part of your test.

Indemnity83 left a reply on [Suggestion Needed] Generate Large And Secure Unique Codes, Yet Easy To Query

Why do you need to go to all that trouble of hashing for coupon codes? If your DB is dumped it is usually trivial to invalidate all the codes you had an re-generate new ones.

I would personally look at using the hashids library to basically translate your coupon code id's into unique codes. This makes lookups of the alphanumeric coupon codes trivial and fast.

Indemnity83 left a reply on Is It Possible To Use Laravel Dusk Browser Outside Of Testing?

Is this something that a library like guzzle couldn't already handle? Using dusk to check a value on a page seems a bit overkill.

12 Apr
2 years ago

Indemnity83 left a reply on Handling Failed Eloquent Methods

I'm not sure what this line of code is trying to do, which is a pretty good hint that it should be extracted to a public method on the $product class that better describes it.

// total stab in the dark at a method name, you'll probably want to update it
public function firstLocaleData($locale, $default = null)
{
    $first = $this->attributes->first();

    if( empty($first) ) {
        return $default;
    }

    return $first->attributeValues->where('locale', $locale);
}

Indemnity83 left a reply on One Route For Handlling Multiple Models

Another option is to create a do most of the heavy lifting in a trait that takes the request, and the commentable model to be used.

trait Commentable
{
    public function addCommentTo(Request $request, $model) 
    {
        // should create an interface for the $model to ensure that
        // it will have the 'comments()' method, or do a check here 
        // and throw an error early. for this example I'm trying to keep
        // it simple and assuming the $model provided will have a defined
        // comments() method that returns a morphMany relationship.

        // validation
        $this->validate($request, [
            'body' => ['required'],
        ]);

        // persist
        return $model->comments()->create([
            'body' => $request->body
        ]);
    }
}

Then create dedicated Controllers/endpoints for each commentable object that use the trait

// in routes/web.php

Route::post('posts/{post}/comments', '[email protected]');
Route::post('users/{user}/comments', '[email protected]');
class PostCommentsController extends Controller
{
    use Commentable;

    public function store(Request $request, Post $post)
    {
        // authorization if necessary

        $comment = $this->addCommentTo($request, $post)
    }       
}

class UserCommentsController extends Controller
{
    use Commentable;

    public function store(Request $request, User $user)
    {
        // authorization if necessary

        $comment = $this->addCommentTo($request, $user)
    }       
}

Indemnity83 left a reply on Return Rows In Laravel That Are Not Empty

No ... that's not any better, arguably it's much worse.

You should have two independent tables.

table lunches | id | name | |----|---------| | 1 | Chicken | | 2 | Cheese | | 3 | Ham | | 4 | Tuna |

table countries | id | name | |----|-------------------| | 1 | Western Australia | | 2 | Rest of Australia | | 3 | Germany & Austria | | 4 | UK & Eire | | 5 | Holland | | 6 | Italy |

Helpful guide for database normalization: http://www.studytonight.com/dbms/database-normalization.php

11 Apr
2 years ago

Indemnity83 left a reply on Support Emails Not Working But Password Reset Emails Working

You need to set that to YOUR email address ... it can't be [email protected]

Indemnity83 left a reply on Not Loading Relationship

$winner = Winners::all(); is the only line that's actually doing anything. the all() method at the end executes the SQL query, so your subsequent call to load() isn't doing anything except building a query string in memory (it never gets executed).

The right syntax would be something more like this

$winner = Winners::load(['points' => function ($query) {
    $query->selectRaw('sum(points) as points_count')
        ->groupBy('points')->get();
    }])
    ->get();

Indemnity83 left a reply on Return Rows In Laravel That Are Not Empty

The columns don't have to do anything with each other. I just said on my previous post that if I write

This should be a major red flag ... if the two data sets are independent, they should be in independent tables.

10 Apr
2 years ago

Indemnity83 left a reply on Good Practices To Compile Many Sub Apps

What do you mean by having two app, myapp and yourapp? Why wouldn't these be in totally different Laravel projects each with their own package.js and dependencies?

Indemnity83 left a reply on 500 Internal Server Error

What's your laravel.log show (it's in storage/logs)?

Best to delete all its contents, try your program again and then paste the error here (or in a pastebin)

Indemnity83 left a reply on 500 Internal Server Error

Cart::update($id, $request->quantity); this is likely your problem, update isn't a static method.

You also must be following and older guide or using an older version of laravel, you don't need to do all that work on the validation.

public function update(Request $request, $id)
{
    $this->validate($request, [
        'quantity' => 'required|numeric|between:1,5',
    ]);

    $cart = Cart::findOrFail($id);

    $cart->update($request->only('quantity'));

    return response()
        ->with('success_message', 'Quantity was updated successfully!')
        ->json([
            'success' => true,
        ]);
}

Indemnity83 left a reply on Building An Baas Application. Best Practice, Laravel And Lumen

What is Baas (B? as a service?).

I'm not an expert, but my two cents...

First off all I am in need of advice. Would I be correct in the following statement. I would have a server for my database and a server for my application

Separation of your application server and DB server is a load/budget dependant decision. For a small application a single server will likely handle both components without any issues.

Secondly In the application server I would like to build my back-end which has all my models and controllers security authentication services. In short the Application business logic.

Yes? I'm not sure where the question is in here...

Thirdly I have my different applications that all interact with the application server and the application server to the database. IS this correct?

I'm not following why you need to have multiple code bases? Maybe related to not knowing what the 'B' in Baas stands for. Unless you have a very slim, single purpose application (like an API, with no HTML views or the like) then I would just go with the full Laravel.

Indemnity83 left a reply on Laravel 5.4 Request::session() Should Not Be Called Statically

Because session() isn't a static method. You can use the global request helper though:

`$validationCode = request()->session()->get('validation_code', '');

Indemnity83 left a reply on Laravel Dusk And Composer Install

The very first line of the official docs is to install dusk through composer, did you run this exactly as it looks (you can't install it globally):

composer require laravel/dusk

Indemnity83 left a reply on Store Image Names One By One Or As Array In Mysql Db?

What's wrong with filling a database; that's what it's for!

Unless there is something unique about each of the 5 images (ie, the first is always the user's profile picture, the second is their car, etc...) then I think the way you have it implemented now where a User hasMany Image and images are on their own table.

You just have to implement a little logic to maintain the 5-image limit is all (count $user->images as a validation before storing)

Indemnity83 left a reply on Use A Token API Auth Along With OAuth

I would make it work in one controller method; then you can extract that into the handle method of a custom middleware knowing you have something working at a simpler level.

If all you're after is the $user to be loaded, or an error thrown it might be as easy as:

<?php

namespace App\Http\Middleware;

use Closure;

class MultiGuardAuthentication
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (\Auth::guard('api')->check()) {
            $user = \Auth::guard('api')->user();
        }

        if (\Auth::guard('token')->check()) {
            $user = \Auth::guard('token')->user();
        }

        if(! isset($user)) {
            throw new AuthenticationException;
        }

        Auth::login($user);

        return $next($request);
    }

}

Indemnity83 left a reply on Mocking Models

Well duh... it's because my controller isn't resolving the model from the IOC container, it's calling it directly. $modpack = Modpack::whereSlug($modpackSlug)->firstOrFail();.

So I suppose this isn't going to work, not without complicating my controller code. I guess I'm just going to duplicate the toArray() unit tests in my feature test to some extent.

Indemnity83 left a reply on Eager Loading Users!

Not your problem, but just a suggestion if you renamed some of your variables and relationships to may make things a little easier to read. Totally up to you, just my two cents.

In your Message class

protected $with = ['to', 'from'];

public function from() {
    return $this->belongsTo(User::class, 'user_from'); 
}

public function to() {
    return $this->belongsTo(User::class, 'user_to');
}

in your controller:

// You don't need to do with with() here, you 
// have it defined in your model already.
$inboxMessages = Message::where('user_to', Auth::id())->latest()->get();
$outboxMessages = Message::where('user_from', Auth::id())->latest()->get();

return view('mail.index', compact('inboxMessages', 'outboxMessages');

Then in your view you should be able to do this:

@foreach ($outboxMessages as $message)
    <p>To: {{ $message->to->firstname }}</p>
    <p>From: {{ $message->from->firstname }}</p>
@endforeach

Indemnity83 left a reply on Eager Loading Users!

What does your query look like that produces the collection?

Indemnity83 left a reply on Return Rows In Laravel That Are Not Empty

Dang man ... you're just a glutton for punishment or something; I think what everybody is trying to tell you is that you're making this problem so much harder than it has to be

What is it you're trying to do here? Can you describe it at a high level? Why are the lunch options coming from a table with seemingly un-related data?

What does IE, what does 'tuna' have to do with 'UK & Eire'?

Indemnity83 left a reply on Use A Token API Auth Along With OAuth

Hmm, ok so you have two different guards ...

I still think you're going to have to do the check in the controller, or make a third custom guard that does both checks for you. assuming your guards (in config/auth.php) look like this right now:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],

    'token => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

I think you can just check both like this

if (\Auth::guard('api')->check()) {
    $user = \Auth::guard('api')->user();
}

if (\Auth::guard('token')->check()) {
    $user = \Auth::guard('token')->user();
}

if(! isset($user)) {
    abort(401, 'Not Authenticated');
}

Indemnity83 left a reply on Help Please Simple SQL Laravel

You could then refactor things a bit and get your query to be very readable:

$result = \App\Model3::with('category')
    ->whereStatus(1)
    ->whereSectionId($section_id)
    ->whereCategoryStatus(1)
    ->whereSectionStatus(1)
    ->get();

// Included to show how structure of result returns your results
dd([
    'title' => $result->title,
    'subtitle' => $result->subtitle,
    'description' => $result->description,
    'photo' => $result->photo,
    'name_category' = $result->category->name
]);
// app/Model3.php
class Model3 extends Model {

    public function category() {
        return $this->belongsTo(Category::class);
    }

    public function section() {
        return $this->belongsTo(Section::class);
    }

    public function scopeWhereCategoryStatus($query, $status) {
        return $query->whereHas('category',  function ($query) use ($status) {
            $query->whereStatus($status);
        });
    }

    public function scopeWhereSectionStatus($query, $status) {
        return $query->whereHas('section',  function ($query) use ($status) {
            $query->whereStatus($status);
        });
    }
}

Indemnity83 left a reply on Help Please Simple SQL Laravel

Snapey probably has your answer, but just to close the loop; taking advantage of Eloquent can probably simplify this code a bit.

// app/Model3.php
class Model3 extends Model {

    public function category() {
        return $this->belongsTo(Category::class);
    }

    public function section() {
        return $this->belongsTo(Section::class);
    }
}
// app/Category.php
class Category extends Model {

}
// app/Section.php
class Section extends Model {

}

Then your query can be built using the defined relationships, there are a couple ways to do this depending on exactly what you find most comfortable

$results = \App\Model3::with('category')
    ->where('status', 1)
    ->whereHas('category',  function ($query) {
        $query->where('status', 1);
    })
    ->whereHas('section',  function ($query) use ($section_id) {
        $query->where('status', $section_id);
    })
    ->get();

dd($results)

note that I haven't tested this code, It may have some typo's and minor logical problems but I think it will get the point across

Indemnity83 left a reply on Use A Token API Auth Along With OAuth

by Token do you mean the personal access token that can be generated as part of Passport?

If so, this is already supported by Passport out of the box, just apply the auth:api middleware and developers can either pass a token received through the OAuth process, or a static Personal Access Token.

If instead you're trying to allow non authenticated access to an endpoint (and presumably adjust the response according to authentication state) then leave the middleware empty for the particular route, tell the controller you want to use the api authentication mechanism (instead of the default session based one). This will authenticate users if the Token is present, but doesn't imeediatly throw an error if the token is missing.

You can then check if the user is authenticated in your controller method:

class FooController extends Controller {

    /**
     * Create a new controller instance.
    */
    public function __construct()
    {
        Auth::shouldUse('api');
    }

    // Route::get('foo/{bar}', '[email protected]');
    public function show($bar) {

    if (Auth::check()) {
        // user is authenticated
    } else {
        // user is not authenticated
    }

    

}

Indemnity83 left a reply on Mocking Models

If I comment out the assertJson() assertion so it doesn't fail on an explicit assertion, then I clearly get an error that the toArray() method on the mock was never called:

Method toArray() from Mockery_0_App_Modpack should be called
 exactly 1 times but called 0 times.

 /Users/kklaus/code/solder/vendor/mockery/mockery/library/Mockery/CountValidator/Exact.php:37
 /Users/kklaus/code/solder/vendor/mockery/mockery/library/Mockery/Expectation.php:298
 /Users/kklaus/code/solder/vendor/mockery/mockery/library/Mockery/ExpectationDirector.php:120
 /Users/kklaus/code/solder/vendor/mockery/mockery/library/Mockery/Container.php:297
 /Users/kklaus/code/solder/vendor/mockery/mockery/library/Mockery/Container.php:282
 /Users/kklaus/code/solder/vendor/mockery/mockery/library/Mockery.php:152
 /Users/kklaus/code/solder/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:142

Indemnity83 started a new conversation Mocking Models

I know there are lots of threads about this; and I feel that I've followed everything I can find but my mocks don't seem to be used so I'm hoping for some help pointing out where I've made a mistake.

I have a feature test that is supposed to make sure that when a particular endpoint is requested, I get back the expected data, the controller method looks like this:


public function show($modpackSlug) {
    $modpack = Modpack::whereSlug($modpackSlug)->firstOrFail();

    // do some authorization stuff

    return response()->json($modpack->toArray());
}

I already have a pretty robust unit testing already for the Modpack::toArray() method, so I don't really want to duplicate that again in the feature test, so I thought I would mock the toArray() method and just have it return a known representation during test. This lets me keep the feature test down to its key, does the route work and return a json representation of the resource.


/** @test */
public function can_get_details_of_modpack() {
    // Arrange - Create a modpack with known slug
        $modpack = factory(Modpack::class)->create(['slug' => 'test']);

    // Expect - modpack->toArray() called once and returns 'modpack-details'
    $mockModpack = \Mockery::mock(Modpack::class)->shouldReceive('toArray')->once()->andReturn('modpack-details')->getMock();
        $this->app->instance(Modpack::class, $mockModpack);

    // Act - get api/modpack/{modpackSlug}
        $response = $this->get('api/modpack/test');

       // Assert
        $response->assertStatus(200);           // No errors
        $response->assertJson(['modpack-details']);   // Response is in expected JSON format

}

however, if I run this test the assertJson() fails because the actual toArray() on my Modpack is being called instead of the Mock of the Modpack. I'm can't quite figure out why or what I've missed in swapping the actual model with my mock.

Any advice is appreciated.

23 Feb
2 years ago

Indemnity83 started a new conversation Date Based Pagination

I would really like to be able to "paginate" an eloquent query by date (specifically so all rows from a particularly date are grouped on each "page", going to the previous page would go to the previous date).

Is this something that the paginate (probably simplePaginator) can handle in Laravel; or is this best handled with some custom query scoping?

15 Feb
2 years ago

Indemnity83 left a reply on Unit Test For API POST Not Finding Type Hinted Model Laravel 5.3

Ok; which line in the CustomerApiController is 264? Sounds like it must be the validation line; just confirming.

Can you just add a couple die and dump checks? are you actually getting a null $account (I still suspect not).

What kind of relationship is the customer() method return in your Account model?

Indemnity83 left a reply on Inserting Csv File Content To A Table

Is this just a one time thing or something that might happen regularly?

If its one-time; then just use a DB tool like SequelPro to get the data in there.

If its a regular thing then there are lots of libraries for parsing CSV data, and even some built in php handling for crude imports.

The simplest example I can think of (untested), given you have a CSV in the following format

| name | email | password | |-------------------|-------------------------------|----------| | Jigsaw | [email protected] | password | | Samara | [email protected] | password | | Frederick Krueger | [email protected] | password |

Then you could write a simple import script as follows

// in routes/web.php

Route::post('import', function(Request $request) {
    
    // Validate the data
    $this->validate($request, [
        'users' => 'required|file',
    ]);

    // Open up the CSV, and create an array of the data
    $file = $request->file('users');
    $csv = array_map('str_getcsv', file($file));
    
    // Pull out the first row as array keys
    array_walk($csv, function(&$a) use ($csv) {
        $a = array_combine($csv[0], $a);
    });
    array_shift($csv); # remove column header

    // Run through each record now and create a new user
    foreach( $csv as $user ) {
        Users::create($user);
    }
});

You should be able to merge the array_walk and foreach to save some of the code; but I wanted to make it clear what each step of the process was.

Again, this is untested code; there are likely some silly mistakes but the main point is to express a method of solving your problem.

Indemnity83 left a reply on Unit Test For API POST Not Finding Type Hinted Model Laravel 5.3

The problem appears to be in your Customer class on line 68 though; not in the controller; it doesn't appear to be getting to the line that deals with the account.

What does your Customer class look like, particularly whatever method includes line 68?

09 Feb
2 years ago

Indemnity83 left a reply on Model Relationships In Laravel 5.3

Can you state what you're after in simple language? I'm not following what you want and I get the impression you're trying harder than you need to in order to achieve your goal.

Its sounds like you have Appliances and Details, either of which can belong to a Cart? I'm not sure what Cart_goods are, can't wrap my head around your applications taxonomy.

Indemnity83 left a reply on PHP Parse Error: Syntax Error, Unexpected '.' In /var/www/vendor/illuminate/support/Facades/Facade.php On Line 52

Have you tried removing the vendor folder and re-installing composer dependencies?

rm -rf vendor/*
composer install

Indemnity83 left a reply on Where Are You All From?

Sacramento, California, USA

Indemnity83 left a reply on Remember User

Next time just copy/pasted the actual text in instead of a million screenshots :P.

Skimming through everything you posted looks fine (looks default). But maybe the problem is in your controllers? The blade template doesn't know or care about sessions.

Indemnity83 left a reply on Error With Uploading Image: Unable To Read Image From File ().

couple general comments:

You can move the auth check into a gate so its re-usable in other places around the site.

You should drop the check for hasFile() and the duplicate validation check for images validation. This will prevent all the user submitted fields from being lost if the user doesn't include a file and will check that its not only been included, but is a valid image. You can also drop the required and mimes checks, since image does this checks already.

Not sure if/how you're using a repository but it seems like you can replace three command sequence $subscription = new subscriptions([...]);, $subscription->save(); and $subscription = DB::table()... with a single $subscription = Subscription::create([...]); or similar from your repository.

If you're using Laravel 5.3 or newer you can replace all your file manipulation stuff with a simpler command set as well. You don't need to check that the request has a file again, you're already doing that and exiting if it doesn't. I would even suggest moving the file resize into a job that happens outside the controller.

My $1.25:

Create a gate to authorize actions. This goes in your App\Providers\AuthServiceProvider

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Gate::define('create-subscription-post', function ($user) {
        return $user->role_id < 5;
    });
}

Then refactor your method for creating subscriptions

public function createSubscriptionPost(Request $request) 
{
    // Authorize the action. 
    if (Gate::denies('create-subscription-post', $post)) {
        return back()->with('errorstatus', 'You don't have permission for this action.');
    }

    // Validate the submitted data
    $this->validate($request, [
        'name' => 'required|max:50',
        'credits' => 'numeric|required',
        'price' => 'numeric|required',
        'xpmultiplier' => 'numeric|required',
        'escalating' => 'required',
        'image' => 'image',
    ]);

    // Looks like in your screenshot you might be implementing a
    // repository, since I dont' know anything about your repository
    // I've swapped the code here for the standard Laravel Eloquent 
    // methods, this may or maynot be useful to you. 
    //
    // Also, for simplification I'm assuming you have $fillable properly
    // set in order to allow the use of $request->all() here. 
    $subscription = Subscription::create($request->all());

    // Deal with the uploaded file (assumed your using Intervention Image)
    $imagePath = $request->file('image')->store(public_path());
    Image::make($imagePath)->resize(200, 200)->save($imagePath);
    $subscription->update(['image' => $imagePath]);
    
    // Done
    return back()->with('status', 'Succesfully created subscription logo!');
}

Indemnity83 left a reply on Series Listings Page Showing Course Completed When Not

Just checked mine... exactly the same thing; marked complete on curated page; but two unwatched on series page

Wondering how many other series have new episodes that I haven't watched; felt like there was a lull in content, turns out it was just a lull in notification. :)

Indemnity83 left a reply on [Laravel 5] Modify Input Before Validation

Laravel 5.4 added middleware out of the box to trim strings and convert empty strings to null which covers the most common use cases here. But it also adds a TransformsRequest middleware that can be extended to cover the less common transformations you might have.

For example, to ucfirst the name fields:

<?php
namespace App\Http\Middleware;

class TransformNames extends TransformsRequest
{
    /**
     * The attributes that should be transformed.
     *
     * @var array
     */
    protected $attributes= [
        'first_name',
    'last_name',
    ];

    /**
     * Transform the given value.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return mixed
     */
    protected function transform($key, $value)
    {
        if (in_array($key, $this->except)) {
            return is_string($value) ? ucwords($value) : $value;
        }

    return $value;
        
    }
}

Then register the middleware and add it to the appropriate routes (or controller constructor)

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
   // existing middleware
    'ucnames' => \App\Middleware\TransformNames::class,
];
Route::post('admin/profile', function () {
    //
})->middleware('ucnames');
05 Jan
2 years ago

Indemnity83 left a reply on Validation Errors Showing :filterAttribute

Turned out to be an over-reaching find-replace problem :P

24 Dec
2 years ago

Indemnity83 left a reply on How To Handle Route With Optional Authentication

That's exactly what I'm trying to do but it doesn't seem to work with Laravel Passport

Indemnity83 started a new conversation How To Handle Route With Optional Authentication

I have a couple routes that that can show/hide data based on the authenticated user. I'm trying to use Passport to manage my API authentication and that works great but I can't seem to figure out how to have a route that will authenticated a user if the Authorization token is present, but still calls the controller method even if there isn't an Authorization token present (I'll handle the data in the controller)

Think of something like an index of Posts, where guests can only see the published posts, and authenticated users can see published and draft posts.

Any advice?