michaelrtm

michaelrtm

Member Since 4 Years Ago

Melbourne

Teacher at Education Department Victoria

Experience Points 7,950
Experience Level 2

2,050 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 53
Lessons
Completed
Best Reply Awards 12
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.

26 Jun
2 years ago

michaelrtm left a reply on Is There A Better Way To Make This Query?

You should mark answers as correct once someone has provided a working solution ;)

michaelrtm left a reply on How To Fetch Relation Array Or Verifiy

I think you'll want something like this

@foreach($cat as $d)
    @if(empty($d->subMenu)
        <li class="mm_welcome">
            <a href="{{url($d->menuurl)}}">
                <i class="fa fa-dashboard"></i>
                <span>{{$d->name}}</span>
            </a>
        </li>
    @else
        <li class="mm_welcome">
            <a href="#">
                <i class="fa fa-barcode"></i>
                <span>{{$d->name}}</span>
                <i class="fa fa-angle-left pull-right"></i>
            </a>
            <ul class="treeview-menu">
                @foreach($d->subMenu as $s)
                    <li id="products_index">
                        <a href="{{url($s->suburl)}}"><i class="fa fa-circle-o"></i> {{$s->name}}</a>
                    </li> 
                @endforeach 
            </ul>
        </li>
    @endif
@endforeach
11 Jun
2 years ago

michaelrtm left a reply on Middleware Assigned To Wrong Routes

When you are wildcarding routes like you are with your prefix on the translate group, you want all other prefix groups to come first in your routes list. Move the translate group to the bottom of the file.

michaelrtm left a reply on Downloading The Content From A <div> As A Separate HTML File

You might be able to use this

var x=window.open();
x.document.open();
x.document.write('content');
x.document.close();

https://stackoverflow.com/a/9399405/1656006

michaelrtm left a reply on Downloading The Content From A <div> As A Separate HTML File

You can get the information using plain javascript document.getElementById('test').innerHTML;, then you can manage it how you would like to. Can't immediately think of how you would export it immediately to html, but my js skills are limited.

michaelrtm left a reply on Foreign Key Problem

Also, you can used $table->unsignedInteger () instead of chaining unsigned ()

michaelrtm left a reply on Foreign Key Problem

Try $users->permissions ()->name and $permissions->users ()->name

michaelrtm left a reply on I Am Having Difficulty Installing Laravel.

Don't forget to select answered to help others

10 Jun
2 years ago

michaelrtm left a reply on Unauthenticated On Api Returns 500 Not 401

Turns out I'm a goose, and should be using $this->json('post', //) not $this->post

michaelrtm left a reply on Relationships Not Working

That's correct, so it's kind of a waste of your time :)

michaelrtm left a reply on Relationships Not Working

Your column names should actually be category_id and subcategory_id, not just category and subcategory

The Eloquent relation looks for the model_id column in your database automatically.

Watch this series if you haven't, and pay attention to Episode 15

michaelrtm left a reply on Relationships Not Working

As @MaverickChan said, your methods are plural and you are trying to access singular. Rename your categories, subcategories and brands relation methods to category, subcategory and brand.

You also probably don't need to declare $table on subcategories, as Laravel (Symfony\Inflector) takes care of that for you.

michaelrtm left a reply on Is Vue Router The Best Way To Buil All Projects?

Probably the best place to ask about browser support is Gitter or the Official Forums

SPA or not depends on the scope of your project. There is no correct answer - you have to work that out for yourself.

09 Jun
2 years ago

michaelrtm started a new conversation Unauthenticated On Api Returns 500 Not 401

Trying to test my api so that only an authenticated user can post, but I'm getting a 500 response instead of a 401 or 403

Test

function only_an_authenticated_user_can_add_a_house()
    {
        $response = $this->post('/api/houses', [
            // bunch of data
        ]);

        // $response->assertStatus(401); //getting 500 ??
        $this->assertDatabaseMissing('houses', [
            //bunch of data
        ]);
    }

api.php

Route::group(['middleware' => 'auth:api'], function(){
    Route::post('/houses', '[email protected]');
});

Using Adam Wathan's disableExceptionHandling function to find the status code, otherwise I get a stack trace with

There was 1 error:

1) Tests\Feature\CreateHouseTest::only_a_registered_user_can_add_a_house
Illuminate\Auth\AuthenticationException: Unauthenticated.

//stack trace

Had a look through Illuminate\Auth\Middleware\Authenticate but couldn't find where the status code would be set?

michaelrtm left a reply on I Am Having Difficulty Installing Laravel.

Are you on Windows or macOS?

You'll need to create the ~/Code folder on your machine.

To get the default settings happening, ssh into your machine and

cd code
laravel new Laravel

that will give you an empty Laravel project at homestead.app

I highly recommend Valet if you are finding Homestead too difficult.

michaelrtm left a reply on Cant Create User

Not that it is vital to how it works, you can also clean up your code a bit. (Requires Use App\User; under the namespace)

public function create_user(Request $request){ 

    $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'phone' => $request->phone,
            'city' => (isset($request->city)) ? $request->city : NULL,
            'image' => (isset($request->image)) ? $request->image : NULL
        ]);

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

@Snapey I think the voucher is 10 chars long so it would be 'hey, you are a winner, use the code 'd6GBf34ez6' to claim your reward.

So table would be partA hashedConcatinatedAandB and salt

User would enter 'd6GBf34ez6' App would take d6GB and perform the lookup, then compared salted/rehashed to d6GBf34ez6... I think

Seems ok to me, but I'm not a security expert :D

michaelrtm left a reply on Relationships Not Working

Do you have a Subcategories model with relationships on categories and products, and do you have a Brand model setup too?

Do the Products only belong to one Category and one Subcategory?

Can you show the store method on Products?

michaelrtm left a reply on Error Displaying Uploaded Image: NotFoundHttpException In RouteCollection.php Line 179:

Have you created a symlink from /var/www/html/Project_name/storage/app/public/ to /var/www/html/Project_name/public??

php artisan storage:link
08 Jun
2 years ago

michaelrtm left a reply on Error Displaying Uploaded Image: NotFoundHttpException In RouteCollection.php Line 179:

First questions:

Is the image definitely there?

Does your server have read permissions to the folder?

When you say app/public/, do you mean like /var/www/Project_name/public or /var/www/Project_name/app/public? (Just double checking)

Have you considered using Storage::? https://laravel.com/docs/5.4/filesystem

https://stackoverflow.com/questions/27300431/notfoundhttpexception-when-trying-to-access-image

https://laracasts.com/discuss/channels/laravel/image-urls-giving-notfoundhttpexception-in-routecollectionphp-line-161

michaelrtm left a reply on How To Handle Checkboxes?

I've chosen to make everything Models, as it allows for options - eg you might need to add 'International' to location one day or Volunteer to employment.

Managing those can be a simple CRUD option in your admin panel, or you can hard code it into your database and seed those options when you go to production.

michaelrtm left a reply on How To Handle Checkboxes?

An employee is either full time, part time or contract - that can't be mixed An employee can only work remotely, in the office or Hybrid - that can't be mixed

Employee belongsToMany Vehicles
Employee hasOne Location // is really only one of those choices?
Employee hasOne Employment_type // 

Vehicle BelongsToMany Vehicles
Location belongsTo Employee
Employment_type belongsTo Employee

Employee Table

$table->integer('id');
//other data
$table->integer('employee_location_id');
$table->integer('employment_type_id');

Vehicle / Location and Employment type Table

$table->integer('id');
//other data
$table->string('type');

employee_vehicle Pivot Table

$table->integer('vehicle_id');
$table->integer('employee_id');

I would personally name the models vehicle and location but that's you choice

michaelrtm left a reply on Sanitizing Inputs With 5.4

As far as I can tell there is no replace() function on the Collection

https://laravel.com/docs/5.4/eloquent-collections#available-methods

michaelrtm left a reply on How To Handle Checkboxes?

You haven't really given a lot of information. Are these vehicle choices the only choices, or might you one day need a boat choice? Are vehicles a Model in your system, or is this just for a profile?

I'd probably have a pivot table user_vehicles with user_id and vehicle_type - gives it room to grow.

Your other option is to store it as a string on whatever table you are storing it on. You would put $table->string('vehicles') in your migration and then store the selected vehicles with something like $user->vehicles = implode(",", Input::vehicle); and retrieving with something like $vehicles = explode(",", $user->vehicles);. This is gross though, and I would be avoiding it.

michaelrtm left a reply on Sanitizing Inputs With 5.4

Can you show your code for your FormRequest?

michaelrtm left a reply on Problem With Relationships

All groups for a user should be a belongsToMany relationship. You'll need a group_user pivot table for that.

$projectsForGroup = Group::find($group_id)->projects()->get();
$filesForProject = Project::find($project_id)->files()->get();

Would really suggest going back and watching this series https://laracasts.com/series/laravel-from-scratch-2017

You'll find stuff about relationships in #15

01 Jun
2 years ago

michaelrtm left a reply on Struggling To Understand How To Check If Not In Pivot Table

perhaps try ->employees()->has

Not 100% sure about chaining sorry.

michaelrtm left a reply on Save(Input::all()) - Not Saving

Save has never worked by accepting an array. Create does, and then you save afterwards.

You cannot save a model without first creating it.

Also, I believe the update method persists changes to the database, so the save method there is redundant.

michaelrtm left a reply on Struggling To Understand How To Check If Not In Pivot Table

$employeesWithNoEnrollment = Employer::find($employer_id)->employees->has('courses', '==', $course)->get();

I expected != to be the operator needed to make this work, but in my quick tests that gave me the wrong employees.

My quick test didn't have an employer, so worked with

Employee::has('courses', '==', $course)->get();

michaelrtm left a reply on Struggling To Understand How To Check If Not In Pivot Table

This isn't as clean as it could be. I'm sure there is a more elegant way, but this will work.

$course = Course::find($course_id);
$employees = Employer::find($employer_id)->employees->get();
$enrolled = Course->attendees()->get();

$employeesWithNoEnrollment = $employees->diff($enrolled)

return response()->json($employeesWithNoEnrollment, 200);

https://laravel.com/docs/5.2/collections#method-diff

michaelrtm left a reply on Struggling To Understand How To Check If Not In Pivot Table

You have no where clause on there at all, you are simply returning every employee for the Employer.

Ithink you probably want something like

Employer::find($companyid)->employees->wherePivot(field, condition);

michaelrtm left a reply on Two Separate Projects

The way you are trying to implement, {standard} is dynamic, looking for a Standard model

Try:

Route::group(['domain' => 'standard.contacts.dev'], function() { 
   Route::get('/', function () { return 'Hello World'; });
});

See here for a more detailed explanation

https://stackoverflow.com/questions/42053284/static-and-wildcard-laravel-sub-domain

michaelrtm left a reply on Save(Input::all()) - Not Saving

Update takes two arrays, first Attributes and then Options

update(array $attributes = array(), array $options = array())

Save only takes a single array - Options

save(array $options = array())
12 Aug
2 years ago

michaelrtm left a reply on Best Way To Delete On Cascade (repository? Event?)

Probably necromancing an old post (can't see a date on my phone and stumbed across this through google)

Another option is to access the boot method on your model, then your cooked in events are already available

protected static function boot()
    {
        parent::boot();
        static::deleting(function ($user){
            //delete logic
    }
10 Aug
2 years ago

michaelrtm left a reply on Initial Install Of Spark Kills Session After Logging In Via Chrome

If the API hits a 401 it automatically logs you out

/resources/assets/js/inteceptiors.js (line 22)

case 401:
    Vue.http.get('/logout');
    $('#modal-session-expired').modal('show');
    break;
02 Mar
3 years ago

michaelrtm left a reply on Help With Pivot/many To Many Type Relationships

On a recent Full Stack Radio (ep 35) they discuss that instead of having a pivot table, try to give your 'pivot' a real name - then you can give it a model and it becomes a real object, instead of this inbetween object that can be a pain.

assigned modules (participant-modules) could be "assignments" participant-activities could be

a participant has many assignments a participant has many activities through assignments (hasManyThrough)

a module has many assignments a module has many activities

assignment has one participant assignment has one module

an activity belongs to a module

Just an idea

michaelrtm left a reply on Form Binding, Form::select

Do you really need to use the form helpers? There's a reason they were deprecated :P I'd look at doing it this way:

<select id="foo" name="users[]" multiple >
    @foreach($users as $user)
        <option value='{{ $user->id }}' {{ in_array($user->id, $task->users) ? selected ; ''>{{ $user->name }}</option>
    @endforeach
</select>

Looking at the form helper docs and source code, the select method only accepts one value (string $selected)

28 Nov
3 years ago

michaelrtm left a reply on Spark + Custom Vue Components

Ok.. so spark by default uses browserify (Which I have never used)

Simple as adding lines to app.js and running gulp

require('laravel-spark/core/bootstrap');
// load extra stuff here
new Vue(require('laravel-spark'));

michaelrtm left a reply on Laravel Relationship - Foreign Key Delete

So why doesn't

$user = User::find($id);
$user->delete();

also remove tasks? Is it not doing the same as what using the DB facade would achieve?

I thought the point of defining the cascade was to prevent having to manually delete everything related?

michaelrtm started a new conversation Spark + Custom Vue Components

If I'm storing my js files in /resources/assets/js/someFolder/someFile.js what is the best way to recursively concatenate those files into the existing app.js that comes with spark? Everything I've tried so far is not working :(

Everything being:

scripts = [
    'app.js',
    '/someFolder/someFile.js'
]

mix.scripts(scripts);
02 Jul
4 years ago

michaelrtm left a reply on Accessing Main Function Argument Inside Advanced Where

thank you for your prompt reply!

michaelrtm started a new conversation Accessing Main Function Argument Inside Advanced Where

I am passing an argument from a controller to a model function. Inside the model function I have an advanced where that calls function ($query).

Once that function is called I lose the scope of my argument variable ($grade). I have tried calling is as global from many different places, but can't figure out how to get that data into my where.

Help please?!

/** * Create an array of domains for a specific grade, built with grade, level and school domains * * @param $grade Grade object * @return domains collection */ public function getDomains($grade) { $domains = $this->domains()->where(function ($query){ $query->where('grade_id','=',$grade->id) ->where('school_id','=',$this->id); })->orWhere(function ($query){ global $grade; $query->where('level_id','=',$grade->level_id) ->where('school_id','=',$this->id); })->orWhere(function ($query){ $query->whereNull('level_id') ->whereNull('grade_id') ->where('school_id','=',$this->id); })->get();

    dd($domains);
    return $domains;
}
25 Jun
4 years ago

michaelrtm left a reply on Using HasManyThrough Through A Pivot Table

I still couldn't load related models through the query build way, and so I kept trying to work it out.

I ended up creating a new pivot table that had student_id and group_id as the primary keys, with no incremental id.

My Group model now has

public function comments()
{
    return $this->hasManyThrough("App\Comment", "App\Student", 'id', 'student_id');
}

and

App\Group::with('comments')->get()

returns a beautiful, related collection

michaelrtm left a reply on Using HasManyThrough Through A Pivot Table

I ended up going with this from one of the responses from the first link (lionelpc's response)

public function getCommentsAttribute(){
    return DB::table('comments')
        ->join('grade_student', 'comments.student_id', '=', 'grade_student.student_id')
        ->select('comments.*', 'grade_student.grade_id')
        ->where('grade_student.grade_id', '=', $this->id)->get();
}
24 Jun
4 years ago

michaelrtm started a new conversation Using HasManyThrough Through A Pivot Table

I am trying to create a relationship to access a table called comments through a model called grade, loaded through the students in the grade

Both the Grade and Student models belongToMany of the other

From my understanding, it is not possible to access a hasManyThrough relationship that requires a pivot table (comments do not have a Grade identifier, only a student identifier)

class Grade extends Model{
    public function comments(){
        return $this->hasManyThrough("App\Comment","App\Student");
    }
}

I have these functions I found for Laravel 4 @ http://stackoverflow.com/questions/23788844/hasmanythrough-with-one-to-many-relationship/23789210#23789210 but it gives me the error Class 'App\Illuminate\Database\Eloquent\Relations\HasMany' not found

I don't have a good understanding on Namespaces, and can't work out what I should be doing in it's place for Laravel 5.

public function getCommentsAttribute()
{
    if ( ! array_key_exists('comments', $this->relations)) $this->loadComments();

    return $this->getRelation('comments');
}

protected function loadComments()
{
    $comments = Comment::join('grade_student', 'comments.student_id', '=', 'grade_student.student_id')
        ->where('grade_student.grade_id', $this->getKey())
        ->distinct()
        ->get(['comments.*','grade_id']);

    $hasMany = new Illuminate\Database\Eloquent\Relations\HasMany(Translation::query(), $this, 'grade_id', 'id');

    $hasMany->matchMany(array($this), $comments, 'comments');

    return $this;
}

More Info

Comment Table

    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->integer('student_id')->unsigned();
        $table->integer('domain_id')->unsigned();
        $table->integer('teacher_id')->unsigned();
        $table->text('comment');

        $table->foreign('student_id')->references('id')->on('students') ->onDelete('cascade');
        $table->foreign('domain_id') ->references('id')->on('domains')->onDelete('cascade');
        $table->foreign('teacher_id')->references('id')->on('teachers')->onDelete('cascade');
    });

My Students Table

Schema::create('students', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
    $table->string('unique_identifier');
    $table->string('first_name');
    $table->string('last_name');
    $table->enum('gender',array('m','f'));
});

My Grades Table

Schema::create('grades', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
    $table->string('name',20);
    $table->integer('school_id')->unsigned();
    $table->integer('level_id')->unsigned();
    $table->foreign('school_id')->references('id')->on('schools')->onDelete('cascade');
    $table->foreign('level_id')->references('id')->on('classes_levels')->onDelete('cascade');
});

My Pivot Table

Schema::create('grade_student', function (Blueprint $table) {
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->timestamps();
    $table->integer('grade_id')->unsigned();
    $table->integer('student_id')->unsigned();
    $table->integer('school_id')->unsigned();
    $table->integer('year');

    $table->foreign('grade_id')->references('id')->on('grades')->onDelete('cascade');
    $table->foreign('student_id') ->references('id')->on('students')->onDelete('cascade');
    $table->foreign('school_id')->references('id')->on('schools') ->onDelete('cascade');
});

michaelrtm left a reply on Relationships Oddity

K, so I'm gonna be that guy that answers his own question... specifying which column to use fixes the issue...

    public function teacher(){
        return $this->belongsTo("App\User",'user_id');
    }

I don't know why though

michaelrtm left a reply on Relationships Oddity

as another aside I also tried naming the function goat and that also returned null :)