verism

Experience

3,270

1 Best Reply Awards

  • Member Since 4 Months Ago
  • 18 Lessons Completed
  • 0 Favorites

18th October, 2017

verism left a reply on How Do I Set Up A One To Many Relationship With A Pivot (5.4) ? • 11 hours ago

@jontyjago I've done exactly the same thing with roles too - although in my case a significant number will have more than one role. I thought perhaps there was a more "correct" way of doing it in a One-ToMany scenario, but you've convinced me otherwise. Definitely overthinking it...

@xmarks Thanks for clarifying those. Of course, I'm now wondering if the first option is just tidier over all... Either way, those two look most viable.

verism left a reply on How Do I Set Up A One To Many Relationship With A Pivot (5.4) ? • 12 hours ago

@xmarks Yeah I'd considered that option, except I'm trying to avoid as many empty fields as possible. Not all users will have to fill in the gender option (I'm not sure what percentage), hence the reason for a pivot.

That said, maybe I'm overthinking it.

verism started a new conversation How Do I Set Up A One To Many Relationship With A Pivot (5.4) ? • 12 hours ago

I'm using the default Authentication functionality in Laravel, and have subsequently added a number of addition user-related tables and relationships. I now need to add a Gender table (with three options: Male, Female and Other) that some - but not all - users will select from.

I believe that I need a One-To-Many set-up for this with a genders_users pivot table (a gender will have many users, but a user my only have one gender), but the documentation only explains pivot tables in a Many-To-Many relationship.

Am I thinking about this in the right way, or is there a simpler solution?

11th October, 2017

verism left a reply on Customising The Default Authentication In Laravel 5.4 • 1 week ago

@Snapey Ah I can't believe I missed that. I had it in my test view, but just didn't update the registration form.

OK, so with that fixed, I'm now getting the following error:

Argument 1 passed to App\Http\Controllers\Auth\RegisterController::saveAndResize() must be an instance of App\Traits\File, instance of Illuminate\Http\UploadedFile given...

So I assume that means the validation isn't conflicting with anything. I tried just adding use App\Traits\File at the top of the RegisterContoller, but to no avail.

10th October, 2017

verism left a reply on Customising The Default Authentication In Laravel 5.4 • 1 week ago

Yeah, I've ditched validation for now.

Following your advice, I'm not 100% sure whether I'm looking at the right data, but this looks like the most obvious candidate:

+request: ParameterBag {#39 ▼
    #parameters: array:7 [▼
      "_token" => "I1fE5XLskvzoCOu3nqjvbteIp4bMW2f8GDHJGngi"
      "first_name" => "firstname"
      "last_name" => "lastname"
      "email" => "[email protected]"
      "password" => "secret"
      "password_confirmation" => "secret"
      "user_portrait" => "ats_ppap_august-2017.png"
    ]
  }

I can't find any instances of a file-related class anywhere.

9th October, 2017

verism left a reply on Customising The Default Authentication In Laravel 5.4 • 1 week ago

@Snapey - it's getting called if I comment out this part:

$this->validate($request, [
    'user_portrait' => 'required|mimes:jpeg,png|dimensions:min_width=800,max_width:1800|max:2048'
]);

But even then it doesn't do what it's meant to, I get the following error: "Argument 1 passed to App\Http\Controllers\Auth\RegisterController::saveAndResize() must be an instance of App\Traits\File, string given"...

verism left a reply on Customising The Default Authentication In Laravel 5.4 • 1 week ago

Ah I see - yeah we've talked a lot about the best UX approach. Whenever we ask for an image on the form it's for an actor's headshot - so it's largely expected that they'll have one already.

UX aside, I'm still not getting very far with the saveAndResize part...

verism left a reply on Customising The Default Authentication In Laravel 5.4 • 1 week ago

I found the reason for the redirect, at least - it was set in the Auth middleware.

@Snapey would you mind expanding a little on why you'd separate them out? (If it makes any difference: the users won't actually be able to do anything apart from log in/out until they've chosen a role and filled the necessary fields.)

verism left a reply on Customising The Default Authentication In Laravel 5.4 • 1 week ago

I've tested the trait from another controller on different page and it worked as expected.

The traits saveAndResize method takes the following arguments:

public function saveAndResize(File $inputFile, $user_id)
{
    ...
}

Even just inserting a dd($inputFile) at the top results in the same behaviour - an attempt to redirect to /home.

verism started a new conversation Customising The Default Authentication In Laravel 5.4 • 1 week ago

I'm trying to add extra functionality to the registration portion of my Laravel application. I already ran make:auth to get the basics up and running, and have modified the user_name field ever-so-slightly. But I'm having trouble going much beyond that.

Users will opt to register with one role (via either a radio or select input), from a list of several. The form will then display the relevant fields to that role. The extra fields will also be stored in one or more table completely separately from the user table.

It seemed like overwriting the registered method from the RegistersUsers trait would be the right approach to this, but I'm having some difficulty. I tried customising the RegisterController like so:

class RegisterController extends Controller
{
    use RegistersUsers;
    use PortraitUploadTrait;

    protected $redirectTo = '/admin';

    public function __construct()
    {
        $this->middleware('guest');
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    protected function create(array $data)
    {
        $user = User::create([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

        return $user;
    }

    // try adding an image...
    protected function registered(Request $request, $user)
    {
        $this->validate($request, [
            'user_portrait' => 'required|mimes:jpeg,png|dimensions:min_width=800,max_width:1800|max:2048'
        ]);

        $this->saveAndResize( $request->user_portrait, $user->id );
        return redirect($this->redirectPath());
    }
}

However this always attempts a redirect to the home route (which doesn't exist) for some reason. The user is created, but it never gets as far as adding the image - and I'm not even sure if this is the right place for the logic to go. Am I on the right tracks?

6th October, 2017

verism left a reply on Should I Check For File Save Errors, And If So, How? • 1 week ago

Ah that's so helpful - huge thanks. And a bonus bugfix!

verism started a new conversation Should I Check For File Save Errors, And If So, How? • 1 week ago

I recently posted a question about users being able to save profile pictures, and the person who answered briefly mentioned about checking the results of the save. This got me wondering if I should be checking if the saves were successful or not, or whether this is something that Laravel takes care of already.

The main logic is currently contained in a trait, and will almost certainly undergo some refactoring:

trait PortraitUploadTrait
{
    public function saveAndResize($inputFile, $user_id) {
        $file_basename = time();
        $file_extension = $inputFile->extension();
        $file_path = 'user/' . $user_id . '/uploads/';

        $upload_width = getimagesize($inputFile)[0];

        $small = Image::make( $inputFile )->resize(200, null, function($constraint){
            $constraint->aspectRatio();
        })->stream();
        $medium = Image::make( $inputFile )->resize(800, null, function($constraint){
            $constraint->aspectRatio();
        })->stream();
        $large = Image::make( $inputFile )->resize(1000, null, function($constraint){
            $constraint->aspectRatio();
        })->stream();

        Storage::disk('public')->put( $file_path . $file_basename . '_small.' . $file_extension, $small, 'public');
        Storage::disk('public')->put( $file_path . $file_basename . '_medium.' . $file_extension, $medium, 'public');
        Storage::disk('public')->put( $file_path . $file_basename . '_large.' . $file_extension, $large, 'public');
    }
}```

And in my `PortraitController`, I have the following method:

```php
public function store(Request $request)
{
    $this->validate($request, [
        'user_portrait' => 'required|mimes:jpeg,png|dimensions:min_width=800,max_width:1800|max:2048'
    ]);

    $this->saveAndResize( $request->user_portrait, 2 );

    return redirect()->route('dashboard');
}

I'm worried that this isn't robust enough for production, so how could it be improved? Or is this actually sufficient?

5th October, 2017

verism left a reply on Npm Issue In Laravel • 1 week ago

As topvillas said, you'll need to upgrade your node installation, and probably nom while you're at it.

There are plenty of instructions on how to do this - this one might help: http://www.hostingadvice.com/how-to/update-node-js-latest-version/

verism left a reply on Npm Issue In Laravel • 1 week ago

@topvillas It's likely he has already read the error, but perhaps doesn't have the knowledge or experience to parse it.

verism left a reply on Npm Issue In Laravel • 1 week ago

It looks like you need a newer version of Node. What version are you using? Type node -v in the terminal.

4th October, 2017

verism left a reply on How Do I Make My Image Storing Method Reusable? • 2 weeks ago

That's a huge help, thanks. I had to alter the trait a little, so that all references to $request->$inputName were $inputName instead, but it works like a charm.

verism started a new conversation I've Got An Image Storing Class Method, Now What? • 2 weeks ago

I've been getting to grips with how to incorporate an image upload facility, and have basically written a stand-alone class to deal with this

class PortraitController extends Controller
{

    public function create()
    {
        return view('test');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'user_portrait' => 'required|mimes:jpeg,png|dimensions:min_width=800,max_width:1800|max:2048'
        ]);

        $file_basename = time();
        $file_extension = $request->user_portrait->extension();

        $user_id = '234567890'; // test purposes
        $filepath = 'user/' . $user_id . '/uploads/';

        $small = Image::make( $request->user_portrait )->resize(200, null, function($constraint){
            $constraint->aspectRatio();
        })->stream();
        $medium = Image::make( $request->user_portrait )->resize(800, null, function($constraint){
            $constraint->aspectRatio();
        })->stream();
        $large = Image::make( $request->user_portrait )->resize(1000, null, function($constraint){
            $constraint->aspectRatio();
        })->stream();

        Storage::disk('public')->put( $filepath.$file_basename.'_small.'.$file_extension, $small, 'public');
        Storage::disk('public')->put( $filepath.$file_basename.'_medium.'.$file_extension, $medium, 'public');

        // return redirect()->route('dashboard');
        return back();
    }
}

Happily, the images are processed and stored perfectly - however I'm not sure of the best way to incorporate this into my project. I will need to call the store method from at least two areas - once in the user registration process (I'll be customising the default RegisterController somehow) and again from one or more custom forms.

I started looking for information on how to call a method from another controller, only to discover that's a huge no-no, so how should I translate the above into something I can reuse at will?

22nd August, 2017

verism left a reply on Is My Destroy Method Properly Protected? • 1 month ago

@Lorceroth You read my mind... figuring that out was going to be my next task. I assumed middleware based on roles was possible, thanks for the advice.

verism left a reply on Is My Destroy Method Properly Protected? • 1 month ago

@thomaskim Thanks - that's pretty much what I hoped somebody would say.

verism started a new conversation Is My Destroy Method Properly Protected? • 1 month ago

I'm probably just being paranoid, but I want to check that the destroy method on my UsersController isn't open to abuse.

The relevant routes are...

Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
    ...
    // Users
    Route::get('users', '[email protected]')->name('users');
    Route::get('users/{id}', '[email protected]');
    Route::delete('users/{id}', '[email protected]');
    ...
});

... so I assume that it's secure, due to the middleware?

The destroy method on the UsersController is as follows:

public function destroy(Request $request)
{
    $id = $request->id;
    $user = User::find($id);
    $user->roles()->detach();
    $user->delete();

    return redirect()->route('users');
}

It ostensibly works as it should, I just really want to know if there's something I should be doing to increase security.

verism left a reply on Different Dashboards For Different People • 1 month ago

I think maybe that ought to be:

if($request->user()->hasRole('landlord'))

with parentheses. But I could be wrong.

verism left a reply on Role-dependent User Profiles • 1 month ago

Apologies if bumps are frowned upon, but I'm hoping someone else might have some further insight into this.

20th August, 2017

verism left a reply on Role-dependent User Profiles • 1 month ago

@jlrdw Thanks for the advice... that's not quite what I'm trying to ask about though. I already have the roles working fine (so far). What I need the most help with is how I should organise database tables that relate to the profiles (age, ethnicity, etc) given that some fields are shared between roles and others are not.

--

@Rogercbe That's what I initially thought, but I'm not sure how that fixed the issue of some data being used by multiple roles.

If someone has both an actor and a director role, in which table does the URI for their user picture sit? If, for some reason, one of their roles is removed, their user picture will still need to be associated with their profile - actor or director.

verism started a new conversation Role-dependent User Profiles • 1 month ago

I'm working on a site where a single user is currently able to have one or more roles: actor, director, writer, and admin. For this, I'm using Laravel's default user functionality for authorisation, and a roles table, and roles_user pivot table for the rest. Users may have one or more roles.

However, I also need users to have a profile, that changes depending on the roles they have been assigned. Some fields should be specific to a particular profile type (only actors need to specify a native accent, while only writers will need to enter a location). Other fields will need to be shared by multiple profile types (both actors and directors will need a user picture).

My problem is trying to figure out how best to organise the profile data. If there were no shared fields, I'd simply have a database for each - but with a large proportion of shared info, this isn't viable. I considered one single table, but that feels very wrong, as there'd likely be a lot of empty fields. Does anyone have any thoughts on how I should go about this?

10th August, 2017

verism left a reply on Multiple User Types With Their Own Distinct Attributes • 2 months ago

@ejdelmonico I thought my question was clear enough - although maybe it was a little buried. I think martinbean has interpreted it correctly though.

verism left a reply on Multiple User Types With Their Own Distinct Attributes • 2 months ago

@martinbean Yes, sorry, "profiles" is definitely a more fitting term. And you're absolutely right about an actor being able to direct something - I thought I explained that, but perhaps it wasn't clear enough.

Your description of the profiles (ActorProfile etc) is almost exactly what I was thinking of - just better described. Although - just so I'm clear - although they can have multiple profile types, they can only ever have one of each type. Am I right in thinking that a user_id column is all I'd need to associate the profiles with users?

And the network suggestion also makes sense - thanks for the advice.

verism started a new conversation Multiple User Types With Their Own Distinct Attributes • 2 months ago

I'm planning for a site where there will be users of different types (Actor, Director, Writer etc). The different user types will have largely distinct attributes, and users will be able to register as one or more of these types. I'm already using a modified version of the baked-in Auth, for basic logging in.

The plan is to have a Migration/Model for each user type, with all of their associated attributes, as well as a user_id field that references their index in the users table. For example:

Schema::create('actors', function(Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('gender');
    $table->string('height');
    ...
});

I'll need to be able to set up all the obvious user admin: list all users along with their type(s), filter users by type, and so on. However I've not managed this kind of database before - is this a sensible way to approach it?

I also need to include social network links for all users, however the exact networks will differ depending on user type - some shared across types, others not. Is there an optimal way to achieve this as well?

21st July, 2017

verism left a reply on Send An "inactive" User Back To The Login Page With A Status. • 2 months ago

Turns out my desired code was actually spot-on... I'd just neglected to include the relevant blade directive in the view:

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

verism left a reply on Send An "inactive" User Back To The Login Page With A Status. • 2 months ago

@Talky I understand the point you're making, but that part of the code is working exactly as it should. The values in the table have a tinyint value of either 0 or 1.

verism started a new conversation Send An "inactive" User Back To The Login Page With A Status. • 2 months ago

I'm getting stuck into my first Laravel project and am currently customising a few areas of authorisation. I've added a boolean "active" column to the users table, which is false by default, so that all users must be approved by an administrator.

I've changed the LoginContoller.php to include the following:

public function login(Request $request)
{

    ...

    $email = $request->get($this->username());
    $user = User::where($this->username(), $email)->first();

    ...

    if ($user) {
        if ($user->active === 0) {
            return $this->sendFailedLoginResponse($request, 'auth.inactive');
        }
    }

    ...

}

However, what I'd like, would be to send a status message with the form, rather than have the error appear on one of the forms input fields. Something a little more like the following:

if ($user) {
    if ($user->active === 0) {
        return back()->with('status', 'Your account is not activated. Please activate it first.');
    }
}

This redirects back to /login, but with no message, no errors, just the form. Is this doable?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.