ycsm

ycsm

Member Since 2 Months Ago

Experience Points
1,180
Total
Experience

3,820 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
1
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 1
1,180 XP
Feb
17
6 days ago
Activity icon

Replied to Integrity Constraint Violation

I can confirm that I had an empty guarded array and no fillable in the User model. I still don't. Strange one.

Activity icon

Replied to Integrity Constraint Violation

Ok, turns out this worked:

        $user = new User();
        $user->firstname = $request->firstname;
        $user->lastname = $request->lastname;
        $user->gender = $request->gender;
        $user->year = @$request->year;
        $user->form_group = @$request->form_group;
        $user->fsm = @$request->fsm;
        $user->ppm = @$request->ppm;
        $user->sen = @$request->sen;
        $user->dob = $request->dob;
        $user->upn = $request->upn;
        $user->disability = $request->disability;
        $user->centre_id = $request->centre_id;
        $user->email = $request->email;
        $user->api_token = Str::random(60);
        $user->password = Hash::make($request->password);

I changed the way of adding the user to the database - I'm not sure why this fixed it, at least its working I guess! Still bugging me though...

Activity icon

Replied to Hijack Password Reset

Mike, thank you. Worked perfectly :)

Feb
16
1 week ago
Activity icon

Replied to Integrity Constraint Violation

Ramonegger - thanks for that. Guarded is set to empty already. Very odd! Still not sure how to fix this

Activity icon

Replied to Integrity Constraint Violation

Hi Sinnbeck, It dumps the firstname as expected

Feb
14
1 week ago
Activity icon

Started a new Conversation Integrity Constraint Violation

Hi all.

I'm having a real issue and can't seem to figure it out.

I am trying to add a user, this used to work... However,now I get an error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_email_unique' (SQL: insert into users (updated_at, created_at)

        public function store(Request $request)
    {

        if(auth()->user()->hasRole('Centre Admin')){
            $centre_id = auth()->user()->centre_id;
        }else{
            $centre_id = $request->centre_id;
        }

        $this->validate($request, [
                'firstname' => ['required', 'string', 'max:255'],
                'lastname' => ['required', 'string', 'max:255'],
                'gender' => ['sometimes', 'numeric'],
                'year' => ['sometimes','nullable', 'numeric'],
                'form_group' => ['sometimes', 'string', 'nullable'],
                'upn' => ['sometimes', 'string', 'nullable'],
                'sen' => ['sometimes', 'string', 'nullable'],
                'ppm' => ['sometimes', 'nullable','numeric'],
                'fsm' => ['sometimes', 'nullable','numeric'],
                'dob' => ['date'],
                'disability' => ['sometimes', 'nullable', 'string'],
                'centre_id' => ['numeric'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
                'password' => ['required', 'string', 'min:8', 'confirmed'],
            ],[
                'dob.required' => 'Please enter a date',
                'dob.date' => 'Please enter a valid date',
            ]
        );

        User::create([
            'firstname' => $request->firstname,
            'lastname' => $request->lastname,
            'gender' => $request->gender,
            'year' => @$request->year,
            'form_group' => @$request->form_group,
            'fsm' => @$request->fsm,
            'ppm' => @$request->ppm,
            'sen' => @$request->sen,
            'dob' => $request->dob,
            'upn' => $request->upn,
            'disability' => $request->disability,
            'centre_id' => $request->centre_id,
            'email' => $request->email,
            'api_token' => Str::random(60),
            'password' => Hash::make($request->password)
        ]);

        // assign roles
        if(!empty($request->roles)){
            $roles = $request->roles;
            foreach($roles as $role){
                $user->assignRole($role);
            }
        }

        return redirect()->route('users.index')->with('success', 'User created successfully');
    }

I have checked the database for empty email columns, non exist, no matter what email address I use I get that error.

A note - I can update fine, this works perfectly for emails and all fields

EDIT: If I dump $request-email - the email dumps fine, and I am 100% sure the email is not in the database. I have tied numerous random emails.

Activity icon

Started a new Conversation Hijack Password Reset

Hi everyone.

At the moment I set some session variables by hijacking the laravel authenticated function like so:

    protected function authenticated(Request $request, $user)
    {
        session(['api_token' => $user->api_token]);
        session(['season' => Season::where('active', 1)->first()]);
        session(['centres' => Centre::where('active', 1)->get()]);
        session(['centre' => Centre::findOrFail(auth()->user()->centre_id)]);
        session(['user' => $user]);

        return redirect()->route('home') ;

    }

However, when a user resets their password, Laravel logs the user in but ignores the above function, none of the session data is set. Is there any way to fix this?

Activity icon

Replied to NewQuery In User Model

Thanks guys. This is the way to go!

Feb
13
1 week ago
Activity icon

Started a new Conversation NewQuery In User Model

Hi. I am using newQuery in several models without an issue. However, I run into trouble with the user model.

I don't want the newQuery to apply when the user wants to login, as this breaks and the user cant login (however, it appears to work when the user is logged in). Here is what I'm using:

<?php

namespace App;

use Carbon\Carbon;
...
use Staudenmeir\EloquentHasManyDeep\HasRelationships;

class User extends Authenticatable
{
    use SoftDeletes, Notifiable, HasRoles, HasRelationships;

    public function newQuery()
    {
        $centre_id = session('centre')->id ?? '';
        return parent::newQuery($centre_id)
            ->when($centre_id, function ($query, $centre_id) {
                return $query->where('centre_id', $centre_id);
            });

    }

Is there a way to bypass this newQuery during login?

Feb
07
2 weeks ago
Activity icon

Replied to WithTrashed() On Child Model

I edited the code slightly. It works nicely :)

Activity icon

Replied to WithTrashed() On Child Model

Hello again Sinnbeck. I was just about to post! I got it working like so:

$participation->user()->withTrashed()->first()->full_name

Would there be any reason you wouldn't recommend this approach?

EDIT: incorrect code

Activity icon

Started a new Conversation WithTrashed() On Child Model

Hi there. I have SoftDeletes enabled on my user table. I can query withTrashed() directly, which is great. However..

After much searching I can't seem to figure out a way to access them from a parent model.

I have:

$session->participations

Participations is a pivot table which contains session_id and user_id.

Obvious (to me) ways of retrieving withTrashed records is

$session->participations->user->withTrashed()

.. doesn't work.

What am I missing here?

Activity icon

Replied to Array Index In Config/sitevars.php Not Performing As It Should?

I get the 3 rows in the database that have NULL in the year column, the rest of the 200+ users are not shown

Activity icon

Replied to Array Index In Config/sitevars.php Not Performing As It Should?

It depends, its just based on the User model, so it could be the authenticated user, or any User you call... but..

That worked! Thank you!

Why did that work??

Activity icon

Replied to Array Index In Config/sitevars.php Not Performing As It Should?

Here's a more comprehensive look...

User Model

<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Traits\HasRoles;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;

class User extends Authenticatable
{
    use Notifiable, HasRoles, HasRelationships;
    

    protected $dates = ['dob'];
    

    public function getFullNameAttribute() //set full name as full_name
    {
        return ucfirst($this->firstname) . ' ' . ucfirst($this->lastname);
    }

    public function getFullNameInitialAttribute() //set full name with just initial
    {
        return ucfirst($this->firstname[0]) . ' ' . ucfirst($this->lastname);
    }

    public function getYearGroupAttribute() //get year from intake
    {
        $set_year = Config::get('sitevars.years');
        return $set_year[$this->year];*/
        
    }


}

sitevars.php in config

<?php


return [
    'years' => [

        2019 => 7,
        2018 => 8,
        2017 => 9,
        2016 => 10,
        2015 => 11,
        2014 => 12,
        2013 => 13,

    ],

];

It's called a few times, here's one example:

<td>{{ $user->year_group }}{{ $user->form_group }}</td>
Feb
06
2 weeks ago
Activity icon

Replied to Array Index In Config/sitevars.php Not Performing As It Should?

It's all manually defined like so... nothing dynamic..

return [
    'years' => [

        2019 => 7,
        2018 => 8,
        2017 => 9,
        2016 => 10,
        2015 => 11,
        2014 => 12,
        2013 => 13,

    ],

];
Activity icon

Replied to Array Index In Config/sitevars.php Not Performing As It Should?

Also - using

return $set_year[intval($this->year)];

Gives me: Undefined offset: 0

Activity icon

Replied to Array Index In Config/sitevars.php Not Performing As It Should?

Hi Snapey, vardump says interger

    int(2019)
Activity icon

Replied to Array Index In Config/sitevars.php Not Performing As It Should?

It's a function within the user model

public function getYearGroupAttribute() //get year from intake
    {
        $set_year = Config::get('sitevars.years');
        return $set_year[$this->year];
    }
Activity icon

Replied to Array Index In Config/sitevars.php Not Performing As It Should?

Thanks Sergiu, unfortantely, no luck

syntax error, unexpected '{', expecting ']'
Activity icon

Started a new Conversation Array Index In Config/sitevars.php Not Performing As It Should?

Hello. I've got the following code and it's driving me insane..

echo $this->year; //This echoes 2019
return $set_year[2019]; //This works, it returns the expected value
return $set_year[$this->year]; //This returns nothing and gives me an 'Undefined Index'

What's going on here? Here is how I set the array:

return [
    'years' => [

        2019 => 7,
        2018 => 8,
        2017 => 9,
        2016 => 10,
        2015 => 11,
        2014 => 12,
        2013 => 13,

    ],

];
Activity icon

Replied to Session Data I've Set Disappears After A Period Of Inactivity

I think I may know the cause - I didn't change the env file on my public server... woops.

Activity icon

Started a new Conversation Session Data I've Set Disappears After A Period Of Inactivity

Hi there. I may be doing this the wrong way, or there may be a better way to do it..

Upon login I'm setting some session data:

session(['api_token' => $user->api_token]);
session(['season' => Season::find($request->season)]);
session(['centres' => Centre::where('active', 1)->get()]);

I call it like so...

session('season')->name

.env file:

SESSION_LIFETIME=9999999999

This works great for a while, but if there's a period of a few hours of activity (I haven't timed it exactly), then the session data I've set gets lost, I have to log out then back in to set the session data again.

However, the user still remains logged in, I can pull Auth data perfectly fine.

What is going on here?

Jan
31
3 weeks ago
Activity icon

Started a new Conversation Laravel & QR Code Reader - No Camera Capture When On Live Server?

I am running Laravel on a local machine and the following plugin (https://github.com/gruhn/vue-qrcode-reader) is working great! It detects the camera immediately. However, when I deploy to my Forge server there is no camera detection at all. No errors logged - is there something I'm missing here? Any steps I should have taken?

Here is the component:

<template>
    <div>
        <p v-if="messageShow" class="message">{{ messageShow }}</p>
        <div class="qr-fullscreen">
            <p class="decode-result" style="color:#ccc">Scanned: <strong style="color:#fff">{{ name }}</strong>
                <br>
                <input v-model="currentUser" name="adduser" id="adduser" @input="addParticipation(currentUser)" class="form-control user_input" type="text" list="manual" placeholder="Manually add an attendee">
                <datalist id="manual">
                    <option v-for="user in users" v-bind:key="user.upn" v-bind:value="user.upn">{{user.firstname}} {{user.lastname}} (Year {{user.year}})</option>
                </datalist>
            </p>
            <qrcode-stream @decode="onDecode" @init="onInit" />
            <a v-bind:href="'/admin/sessions/'+this.session.id" class="qr-fullscreen-close">
                <i class="fa fa-times"></i>
            </a>
        </div>
    </div>
</template>

<script>
    import { QrcodeStream } from 'vue-qrcode-reader';

    export default {

        mounted() {
            $('.loading').hide();
        },

        components: { QrcodeStream },

        data () {
            return {
                result: '',
                error: '',
                name: 'No one scanned',
                user: [],
                currentUser: '',
                messageShow: ''
            }
        },

        methods: {
            onDecode (result) {
                this.result = result;
                this.addParticipation(this.result);
            },

            addParticipation(upn){
                var last_character = upn[upn.length-1];
                if(isNaN(last_character)){}else{

                    let currentObj = this; // important?
                    axios.post('/api/session_capture', {
                        session_id: this.session.id,
                        upn: upn,
                        api_token: localStorage.getItem('api_token')
                    })
                        .then((response) => {
                            if (response.data.message) {
                                this.toggleMessage(response.data.message);
                            } else {
                                this.playSound();
                                this.toggleMessage(response.data.name + ' added successfully');
                                this.name = response.data.name;
                                this.currentUser='';
                                $('#manual option[value='+upn+']').remove();
                            }
                        })
                        .catch((error) => {
                            currentObj.output = error;
                            console.log(currentObj.output);
                        });
                }
            },
            toggleMessage($msg) {
                this.messageShow = $msg;
                setTimeout(() => {
                    this.messageShow = false;
                }, 4000);
            },
            playSound() {
                const path = this.root+'/audio/snap.mp3';
                const audio = new Audio(path);
                var playPromise = audio.play();

                if (playPromise !== undefined) {
                    playPromise.then(_ => {
                        console.log('Success');
                    })
                        .catch(error => {
                            console.log(`playSound error: ${error}`);
                        });
                }
            },

            async onInit (promise) {
                try {
                    await promise
                } catch (error) {
                    if (error.name === 'NotAllowedError') {
                        this.error = "ERROR: you need to grant camera access permisson"
                    } else if (error.name === 'NotFoundError') {
                        this.error = "ERROR: no camera on this device"
                    } else if (error.name === 'NotSupportedError') {
                        this.error = "ERROR: secure context required (HTTPS, localhost)"
                    } else if (error.name === 'NotReadableError') {
                        this.error = "ERROR: is the camera already in use?"
                    } else if (error.name === 'OverconstrainedError') {
                        this.error = "ERROR: installed cameras are not suitable"
                    } else if (error.name === 'StreamApiNotSupportedError') {
                        this.error = "ERROR: Stream API is not supported in this browser"
                    }
                    this.toggleMessage(this.error);
                    console.log(this.error);
                }
            }
        },

        props:[
            'session',
            'root',
            'users'
            ],
    }



</script>

<style>
    .message {
        position: fixed;
        z-index: 2001;
        padding: 10%;
        left: 0;
        text-align: center;
        width: 100%;
        background-color: rgba(0, 0, 0, 0.4);
        top: 50%;
        transform: translateY(-50%);
        color: #fff;
    }
    .user_input{
        margin-top: 5px !important;
        width: 90vw !important;
    }

</style>
Jan
27
3 weeks ago
Activity icon

Started a new Conversation Best Way To Set Up This Relationship?

Hello all.

I'm after a bit of logic advice. I am creating a system where users login and register their participation at an activity. They can participate at an activity many times. What is the best way to do this? I want to ensure I can use eloquent with this rather than creating my own functions.

I am imagining...

Users:

id

Activitys:

id
name

Participations:

id
user_id
activity_id
time_at_activity

I want to later be able to do such things as: $user->participations->where('activity_id', 3) for example.

What is the best way to set this up? I had in mind..

User: hasMany->Participations

Activity: belongsTo->Participation

Participation: hasMany->Activitys & belongsTo->User

Does this look correct?

Jan
22
1 month ago
Activity icon

Replied to Api_token Working - But How To Authorize Access To API's By Roles/permissions?

Hi Jeffrey, Thanks for the post!

I saw a little bit of information in your first link that I hadn't spotted before.

THIS DIDN'T WORK (it would work in web.php):

    Route::post('privacy_change', '[email protected]_change')->middleware('can:change_privacy');

THIS WORKED!

Route::group(['middleware' => ['auth:api']], function () {

    Route::post('privacy_change', '[email protected]_change')->middleware('can:change_privacy');

});

Apparently because of this bit of information I found, which I had no knowledge of before... "Out of the box, the web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider."

It is now working!! I just needed to wrap the API routes

Activity icon

Started a new Conversation Api_token Working - But How To Authorize Access To API's By Roles/permissions?

Hello. I'm struggling to get this basic concept off the ground, and have actually found little to no literature on the internet on how to do this. I want to restrict access to API routes (either on the controller level or the route level) to different roles.

Currently I have 3 levels of control setup on a laravel project and it all works perfectly on the web side. I'm using laravel's built in guards and no extra packages like spatie or bouncer.

However, when attempting to figure out how to set access levels on API's I am really struggling (the API's are all local). I have setup an api_token in the users table and I can successfully restrict access - but, I can only differentiate between a guest and a user who is logged in. I have no way to differentiate what type of user it is.

Is there some basic concept I've missed here? If you'd like to see any specific code please let me know!

Thank you

Nick

Jan
16
1 month ago
Activity icon

Replied to Laravel Forge Failure To Install Repo

Please ignore above comment, I found a reference to it in app.php :)

Activity icon

Replied to Laravel Forge Failure To Install Repo

Right, so I've pulled from the repo (without composer install), sorted out ENV file, then run composer.. I get a different message

> @php artisan package:discover --ansi

In ProviderRepository.php line 208:
                                                            
  Class 'App\Providers\TelescopeServiceProvider' not found  

I used telescope a while back but removed it. I've used PHPStorm to search all files in my app folder and see no reference to telescope at all...

Activity icon

Replied to Laravel Forge Failure To Install Repo

Aha... I have added the following code to these:

AuthSP:

    public function boot()
    {
        $this->registerPolicies();

        // Implicitly grant "Super Admin" role all permissions
        // This works in the app by using gate-related functions like auth()->user->can() and @can()
        Gate::before(function ($user, $ability){
            return $user->hasRole('Super Admin') ? true : null;
        });

        //Superadmin check
        Gate::define('isSuperAdmin', function($user){
            return $user->hasRole('Super Admin');
        });

        //PLT Student check
        Gate::define('isPLTStudent', function($user){
            return $user->hasRole('PLT Student');
        });

        //Student check
        Gate::define('isStudent', function($user){
            return $user->hasRole('Student');
        });

        //Logged in?
        Gate::define('logged-in', function($user){
            return Auth::user();
        });

        //SEE Admin Panel
        Gate::define('SEE-admin-panel', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //SEE Admin Dashboard
        Gate::define('SEE-admin-dashboard', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //USERS PERMISSIONS

            //Overall
            Gate::define('USERS-manage-users', function($user){
                return $user->hasAnyRoles(['PLT Student']);
            });

            //Specific
            Gate::define('USERS-create-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-view-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-edit-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-delete-users', function($user){
                return $user->hasRole('PLT Student');
            });

        //RUNS PERMISSIONS

        //Overall
        Gate::define('RUNS-manage-runs', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //Specific
        Gate::define('RUNS-create-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-view-runs', function($user){
            return $user->hasAnyRoles(['PLT Student', 'Student']);
        });
        Gate::define('RUNS-edit-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-delete-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-delete-runs', function($user){
            return $user->hasRole('PLT Student');
        });

    //RUNTYPES PERMISSIONS

        //Overall
        Gate::define('RUNTYPES-manage', function($user){
            //return $user->hasAnyRoles(['PLT Student']);
        });

        //Overall
        Gate::define('RUNTYPES-view', function($user){
            return $user->hasAnyRoles(['PLT Student', 'Student']);
        });

    //RUNTYPES PERMISSIONS

        //Overall
        Gate::define('GROUP-manage', function($user){
            //return $user->hasAnyRoles(['PLT Student']);
        });
    }

AppSP:

    public function boot()
    {
        View::share('run_types', RunType::orderBy('name')->get()); //share with all
    }
Jan
15
1 month ago
Activity icon

Started a new Conversation Laravel Forge Failure To Install Repo

I've tried to install a repository but keep getting the following message

"Illuminate\Database\QueryException : SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO)"

This has happened for 3 different repositories, one of which has worked previously.

Support got back to me and said "It sounds like you have a Artisan command or Service Provider that is calling your database on every command. That should be fixed before installing the repository." - but I really am not sure what they mean/it could be?

Activity icon

Replied to Gate::allows() Function Not Working In API Routes

May I ask - this is a long time ago I know, but do you have the full code you used to get this working?

Activity icon

Started a new Conversation Laravel - Using Gates On API Requests For Authorization

I have a laravel app setup perfectly with roles and permissions using gates. For example, in the web routes file I have this which works great:

WEB.PHP

Route::resource('groups', 'SuperAdmin\GroupsController')->middleware('can:SEE-admin-dashboard');

However, when I try to apply the same middleware to API requests (inside Vue Components), it will not work. I keep getting unauthorised messages. Here are two things I've tried..

API.PHP

Attempt 1-

Route::post('group_times', '[email protected]_groups_times')->middleware('can:SEE-admin-dashboard');

Attempt 2-

Route::middleware('auth:api')->post('group_times', '[email protected]_groups_times', function(Request $request) {
    return $request->user();
});

I'm getting a 401 unauthorised message:

401 Unauthorised

I have setup each user with an API token as mentioned in the Laravel docs. Like so, but no such luck.

401 unauthorized: https://imgur.com/het8wEf

Am I missing something here? Do I have to pass any tokens? What is the best way to achieve authentication over an API request that still uses the gates? Is this possible? I've been learning Laravel over the last few weeks and this really is my first major stumbling block

Here is the code from AuthServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

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


        // Implicitly grant "Super Admin" role all permissions
        // This works in the app by using gate-related functions like auth()->user->can() and @can()
        Gate::before(function ($user, $ability){
            return $user->hasRole('Super Admin') ? true : null;
        });

        //Superadmin check
        Gate::define('isSuperAdmin', function($user){
            return $user->hasRole('Super Admin');
        });

        //PLT Student check
        Gate::define('isPLTStudent', function($user){
            return $user->hasRole('PLT Student');
        });

        //Student check
        Gate::define('isStudent', function($user){
            return $user->hasRole('Student');
        });

        //SEE Admin Panel
        Gate::define('SEE-admin-panel', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //SEE Admin Dashboard
        Gate::define('SEE-admin-dashboard', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //USERS PERMISSIONS

            //Overall
            Gate::define('USERS-manage-users', function($user){
                return $user->hasAnyRoles(['PLT Student']);
            });

            //Specific
            Gate::define('USERS-create-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-view-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-edit-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-delete-users', function($user){
                return $user->hasRole('PLT Student');
            });

        //RUNS PERMISSIONS

        //Overall
        Gate::define('RUNS-manage-runs', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //Specific
        Gate::define('RUNS-create-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-view-runs', function($user){
            return $user->hasAnyRoles(['PLT Student', 'Student']);
        });
        Gate::define('RUNS-edit-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-delete-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-delete-runs', function($user){
            return $user->hasRole('PLT Student');
        });

    //RUNTYPES PERMISSIONS

        //Overall
        Gate::define('RUNTYPES-manage', function($user){
            //return $user->hasAnyRoles(['PLT Student']);
        });

        //Overall
        Gate::define('RUNTYPES-view', function($user){
            return $user->hasAnyRoles(['PLT Student', 'Student']);
        });

    //RUNTYPES PERMISSIONS

        //Overall
        Gate::define('GROUP-manage', function($user){
            //return $user->hasAnyRoles(['PLT Student']);
        });
    }

}

Vue axios:

//Get time data to populate table
            getTimes(){
        axios.post('/api/group_times', {
                group_id: this.group_id,
                amount: 5,
                season_id: this.season_id
            })
                .then(response => {
                        this.times = response.data;
                    }
                );
        },
Jan
06
1 month ago
Activity icon

Replied to Adding Data To The Login Form?

Thank you all, working a treat. I'm rather new to Laravel and this has really helped

Activity icon

Started a new Conversation Adding Data To The Login Form?

Hello all. I'm wanting to pass some data to the login view (an array of "seasons"), and also want to retrieve it upon login and add it to session data. Where do I hijack the formcontroller and submission? I've checked my LoginController and there doesn't appear to be a way to pass data to the view, and also I am unable to find out where to get the submitted for data upon login.

Image of picture

Dec
20
2 months ago
Activity icon

Replied to Relationship Isn't Clear

Thanks a lot for your help. Seriously - how do I buy you a coffee?

Dec
19
2 months ago
Activity icon

Replied to Relationship Isn't Clear

That simple! Thanks so much STEREOH - how do I buy you a coffee?

For future reference - is there a better way for me to organise this relationship?

Activity icon

Replied to Relationship Isn't Clear

Just ran it, no use - I'm forever running it, just in case!

Activity icon

Replied to Relationship Isn't Clear

Database structure if any use:

https://i.imgur.com/XC3IUf9.png

Activity icon

Replied to Relationship Isn't Clear

Here she is in full:



namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    protected $guard_name = ['web'];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getFullNameAttribute() //set full name as full_name
    {
        return ucfirst($this->firstname) . ' ' . ucfirst($this->lastname);
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function group()
    {
        return $this->belongsTo(Group::class);
    }

    public function times()
    {
        return $this->hasMany('\App\Time');
    }

    public function runs()
    {
        return $this->belongsToMany(Run::class)
            ->using(Time::class)
            ->withPivot('time');
    }

}
Activity icon

Replied to Relationship Isn't Clear

Aha, that makes sense.

I'm half way there! I'm just trying to query on the reverse side of this - from the aspect of a user

$user->runs() or \App\User::find($time->user_id)->runs()

And I'm getting the following respectively...

** SQLSTATE[42S02]: Base table or view not found: 1146 Table 'traversy.run_user' doesn't exist (SQL: select runs.*, run_user.user_id as pivot_user_id, run_user.run_id as pivot_run_id, run_user.time as pivot_time from runs inner join run_user on runs.id = run_user.run_id where run_user.user_id = 32) (View: C:\Users\Nick\PhpstormProjects\traversy\resources\views\dashboard.blade.php) **

** htmlspecialchars() expects parameter 1 to be string, object given (View: C:\Users\Nick\PhpstormProjects\traversy\resources\views\runs\show.blade.php) **

Activity icon

Replied to Relationship Isn't Clear

Wow, that worked. So I know - what is the reason for adding protected $table = 'times';? Is it a reserved name or something like that?

Activity icon

Replied to Relationship Isn't Clear

No, it's called times.

Here's a quick screencast of the table structures: https://www.screencast.com/t/glUpxHIiqgYi

Activity icon

Replied to Relationship Isn't Clear

I did spot that typo but still an error (a different one, sorry - I've seen so many errors today they're getting all jumbled in my mind!), this is what I get. It looks like laraval is using singular time instead of times?

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'traversy.time' doesn't exist (SQL: select * from time where time.run_id = 7 and time.run_id is not null)


namespace App;

use Illuminate\Database\Eloquent\Model;

class Run extends Model
{
    protected $guarded = [];

    protected $dates = ['date'];

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

    public function times()
    {
        return $this->hasMany('\App\Time');
    }

    public function users()
    {
        return $this->belongsToMany(User::class)
            ->using(Time::class)
            ->withPivot('time');
    }

}

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    protected $guard_name = ['web'];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getFullNameAttribute() //set full name as full_name
    {
        return ucfirst($this->firstname) . ' ' . ucfirst($this->lastname);
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function group()
    {
        return $this->belongsTo(Group::class);
    }

    public function times()
    {
        return $this->hasMany('\App\Time');
    }

    public function runs()
    {
        return $this->belongsToMany(Run::class)
            ->using(Time::class)
            ->withPivot('time');
    }

}

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class Time extends Pivot
{
    protected $guarded = [];

    public $incrementing = true;

    public function run()
    {
        return $this->belongsTo('\App\Run');
    }

    public function user()
    {
        return $this->belongsTo('\App\User');
    }


}

This happens with $run->times and $run->users

    public function show(Run $run)
    {
        dd($run->times);
        $runners = getActiveRunners();
        return view('runs.show', compact('run', 'runners'));
    }