PHPackages                             networkrailbusinesssystems/laravel-moodle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. networkrailbusinesssystems/laravel-moodle

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

networkrailbusinesssystems/laravel-moodle
=========================================

A Laravel package to authenticate against Moodle and retrieve course data

0.3.1(6mo ago)81721PHPPHP ^8.3

Since Jul 8Pushed 3mo ago3 watchersCompare

[ Source](https://github.com/Network-Rail-Business-Systems/laravel-moodle)[ Packagist](https://packagist.org/packages/networkrailbusinesssystems/laravel-moodle)[ RSS](/packages/networkrailbusinesssystems-laravel-moodle/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (15)Used By (0)

LaravelMoodle
=============

[](#laravelmoodle)

A Laravel package to authenticate with Moodle and retrieve course information.

Installation
------------

[](#installation)

```
composer require networkrailbusinesssystems/laravel-moodle
```

The package should auto register the service providers.

### Migrations

[](#migrations)

Your User table should include the following columns:

```
$table
    ->string('password')
    ->nullable();

$table
    ->string('username')
    ->unique()
    ->nullable();

$table
    ->unsignedBigInteger('moodle_id')
    ->nullable();
```

### Configuration

[](#configuration)

Optionally, publish the config file. This is required if you want to customise which fields are synchronised from Moodle to your user model.

```
php artisan vendor:publish
```

Update your auth.php config file, providers &gt; users &gt; drivers to `moodle`

Update the .env file with the `MOODLE_BASE_URL` with the url of your Moodle installation and `MOODLE_ADMIN_TOKEN` with a token for an existing user that has permission to search existing users.

### User Model

[](#user-model)

When a user logs in for the first time their email, username and id are set from Moodle in the user model. If you want to customise the fields that are synchronised then publish the `laravel-moodle` config file and update the sync\_attributes array.

Any fields that you synchronise will need to added to the `protected $fillable` array in your User model.

If you want to use a different model to `App\User` then update the `user_model` in the `laravel-moodle` config file.

### Credentials

[](#credentials)

The package expects the credentials from the LoginController to be an array containing `username` and `password`, but if you want to use `username` instead then add `MOODLE_LOGIN_ATTRIBUTE=username` to your .env file.

**Users set as a Site Administrator in Moodle will not be able to login using LaravelMoodle until they manually generate a token for their account as per step #5 below.**

### Middleware

[](#middleware)

The package contains a middleware that you can use to check if the user has a moodle token in their session. If they don't it will log the user out from their Laravel session and redirect the user ot the login page.

To use globally list the `NetworkRailBusinessSystems\LaravelMoodle\Middleware\MoodleToken::class` in the `$middleware` property of `app/Http/Kernel.php`.

To use on specific routes add `'laravel-moodle' => \NetworkRailBusinessSystems\LaravelMoodle\Middleware\MoodleToken::class` to the `$routeMiddleware` in `app/Http/Kernel.php` and then add to your route.

```
Route::get('/', function () {})->middleware('laravel-moodle');
```

Emulator
--------

[](#emulator)

An emulator is provided for development purposes, which simulates some of Moodle's endpoint responses.

You can enable it in your application while serving, set the `MOODLE_EMULATOR_ENABLED` env setting to `true`.

For unit tests, add `NetworkRailBusinessSystems\LaravelMoodle\ServiceProvider::startEmulator()` to your `setup` function.

Moodle Configuration
--------------------

[](#moodle-configuration)

In order to access data from Moodle, it needs to be configured first as the web service features are disabled by default.

1. Enable Web Services for mobile devices
    - Site Administration &gt; Mobile app &gt; Mobile settings
    - Enable web services for mobile devices - yes
    - Save changes
2. Enable Web Services (yes, again)
    - Site Administration &gt; Advanced features
    - Enable Web Services - yes
    - Save changes
3. Create new webservice
    - Site Administration &gt; Plugins &gt; Web services &gt; External Services
    - Add Custom Service or use an existing custom service
        - Name: Web Service
        - Short name: web\_service
        - Enabled: true
        - Authorised users only: false
        - Can download files: true
        - Save changes
4. Enable the following functions in the new Moodle web service
    - Site Administration &gt; Plugins &gt; Web services &gt; External Services
    - On the newly created Web Service, click functions and add the following
        - core\_badges\_get\_user\_badges
        - core\_calendar\_get\_calendar\_monthly\_view
        - core\_completion\_get\_activities\_completion\_status
        - core\_completion\_get\_course\_completion\_status
        - core\_course\_get\_categories
        - core\_course\_get\_contents
        - core\_course\_get\_course\_module
        - core\_course\_get\_courses
        - core\_course\_get\_courses\_by\_field
        - core\_course\_search\_courses
        - core\_enrol\_get\_enrolled\_users
        - core\_user\_get\_users
        - enrol\_manual\_enrol\_users
        - enrol\_manual\_unenrol\_users
        - enrol\_self\_enrol\_user
        - gradereport\_overview\_get\_course\_grades
        - mod\_assign\_get\_assignments
        - mod\_assign\_get\_submissions
        - mod\_assign\_get\_submission\_status
        - mod\_assign\_save\_submission
        - mod\_page\_get\_pages\_by\_courses
        - mod\_page\_view\_page
        - mod\_resource\_get\_resources\_by\_courses
        - mod\_resource\_view\_resource
        - mod\_book\_get\_books\_by\_courses
        - mod\_scorm\_get\_scorm\_scoes
        - mod\_scorm\_get\_scorms\_by\_courses
5. Create a token for the admin user (used in the Laravel .env file)
    - Site Administration &gt; Plugins &gt; Web services &gt; Manage tokens
    - Click Add
        - Search for the admin user you want to use
        - Select your Web Service
        - Save changes
6. Allow users to create tokens for the new Web Service so they can create a token when they log in
    - Site Administration &gt; Users &gt; Define Roles
    - Edit Authenticated user
    - Capabilities &gt; Create a web service token &gt; Allow
    - Save

Endpoints
---------

[](#endpoints)

Use the LaravelMoodle facade to access the web service data.

```
use NetworkRailBusinessSystems\LaravelMoodle\LaravelMoodle as LaravelMoodle;
```

The package uses [Spatie Data Transfer Objects](https://github.com/spatie/data-transfer-object) to format the response into objects.

### Get Courses

[](#get-courses)

Returns a collection of courses.

```
$data = LaravelMoodle::getCourses();

foreach ($data->courses as $course) {
    echo $course->fullname; // My First Course
}

echo $data->courses[0]->fullname; // My First Course
```

To filter the list of courses pass in the term and the field. you can use id, ids, shortname and category id.

```
// Get course with id 3
$data = LaravelMoodle::getCourses('2', 'id');

// Get courses with ids 2 & 3
$data = LaravelMoodle::getCourses('2,3', 'ids');
```

### Get Course By Id

[](#get-course-by-id)

Once you know the course ID (int) you can get a specific course.

```
$course = LaravelMoodle::getCourse(2);

echo $course->fullname; // My First Course
```

### Search Courses

[](#search-courses)

Pass in your search term as the first parameter (string).

```
$searchResults = LaravelMoodle::searchCourses('search term');

echo $searchResults->total; // 1
echo $searchResults->courses[0]->fullname; // My First Course
```

Optionally pass in page number (integer) and per page (integer).

```
$searchResults = LaravelMoodle::searchCourses('search term', 2, 15);
```

You can also limit the search to only enrolled courses by specifying 1 as the 4th parameter.

```
$searchResults = LaravelMoodle::searchCourses('search term', 2, 15, 1);
```

### Get Course Contents By Id

[](#get-course-contents-by-id)

Once you know the course Id you can get the contents of a specific course.

```
$courseContents = LaravelMoodle::getCourseContents(1);

echo $courseContents[0]->name; // Topic name
echo $courseContents[0]->modules[0]->name; // Activity name
```

### Get Course Module By Id

[](#get-course-module-by-id)

Once you know the module id from the course contents you can get more details about the module.

```
$module = LaravelMoodle::getCourseModule(11);

echo $module->cm->name; // Topic name
```

### Get Course Pages

[](#get-course-pages)

Once you know the course id you can get the pages for the course.

```
$pages = LaravelMoodle::getCoursePages(1);

echo $pages->pages[0]->name; // Page name
```

### Get Course Page

[](#get-course-page)

Get a specific course page by module id.

```
$page = LaravelMoodle::getCoursePage($courseId, $moduleId);
```

### Get Course Scorms

[](#get-course-scorms)

Once you know the course id you can get the scorms for the course.

```
$scorms = LaravelMoodle::getCourseScorms(1);

echo $scorms->scorms[0]->name; // Example scorm
```

### Get Course Scorm

[](#get-course-scorm)

Get a specific course scorm by module id.

```
$scorm = LaravelMoodle::getCourseScorm($courseId, $moduleId);
```

### Get Course Resources

[](#get-course-resources)

Once you know the course id you can get the resources.

```
$resources = LaravelMoodle::getCourseResources(1);
echo $resources->resources[0]->name;
```

### Get Course Resource

[](#get-course-resource)

Get a specific course resource by module id.

```
$resource = LaravelMoodle::getCourseResource($courseId, $moduleId);
```

### Get Course Completion

[](#get-course-completion)

You can get the course completion status by passing in the user id and the course id.

```
$completion = LaravelMoodle::getCourseCompletion(2, 2);
```

### Get Course Activities Completion

[](#get-course-activities-completion)

You can get details of a course's activities completion by passing in the user id and the course id.

```
$activities = LaravelMoodle::getCourseActivitiesCompletion(2, 2);

echo $activities->statuses[0]->state;
```

### Get Course Assignments

[](#get-course-assignments)

Get the assignments for a specific course by passing in the course id.

```
$data = LaravelMoodle::getCourseAssignments(2);

echo $data->courses[0]->assignments[0]->name;
echo $data->courses[0]->assignments[0]->id;
```

### Get Course Assignment

[](#get-course-assignment)

Get a specific course assignment by the module id.

```
$assignment = LaravelMoodle::getCourseAssignment($courseId, $moduleId);
```

### Get Assignment Submission Status

[](#get-assignment-submission-status)

Provides information on the previous attempts for an assignment. User id is optional as it defaults to the current user.

```
LaravelMoodle::getAssignmentSubmissionStatus($assignmentId, $userId);
```

### Save Course Assignment

[](#save-course-assignment)

Submit the online text for a specific assignment. Returns true on success.

```
$submit = LaravelMoodle::saveCourseAssignment($assignmentId, 'The content');

echo $submit; // true
```

If there is an issue submitting then an array of warnings will be returned, with the error details in the item and message.

```
$submit = LaravelMoodle::saveCourseAssignment($assignmentId, '');

echo $submit[0]->item; // Nothing was submitted
echo $submit[0]->message; // Could not save submission
```

### Get User Grades

[](#get-user-grades)

Get the grades for a user. Default to 0 for the current logged in user.

```
$grades = LaravelMoodle::getUserGrades();

echo $grades->grades[0]->courseid; // 2
echo $grades->grades[0]->grade; // A
```

### Get Course Grade for User

[](#get-course-grade-for-user)

Get the grade for a user for a specific course. Default to 0 for the current logged in user. Returns null for grade if course not found.

```
$grade = LaravelMoodle::getCourseGrade(2);

echo $grade->courseid; // 2
echo $grade->grade; // A
```

### Search Users

[](#search-users)

Search for users. Default search field is username if not provided.

```
// Defaults to searching by username
$users = LaravelMoodle::searchUsers('testuser');

// Override to search by email address
$users = LaravelMoodle::searchUsers('test.user@fake.email', 'email');

echo $users->users[0]->fullname; // Test User
```

### Enrol User On A Course

[](#enrol-user-on-a-course)

You can enrol a user onto a course by specifying the user id then the course id. By default they have the student role, but you can specify the role id.

The user performing the call must be an Admin or Manager in Moodle or a teacher in the course.

There is a `null` response from Moodle when successful, but enrolUserOnCourse returns `true` when successful and MoodleException if it fails.

```
// Defaults role to student
LaravelMoodle::enrolUserOnCourse(2, 2);

// Override role to editing teacher
LaravelMoodle::enrolUserOnCourse(2, 2, 3);
```

### Unenrol User On A Course

[](#unenrol-user-on-a-course)

You can unenrol a user on a course. Role id is not required. It will default to the student role.

```
LaravelMoodle::unenrolUserOnCourse($userId, $courseId, $roleId);
```

### Get Enrolled Users For A Course

[](#get-enrolled-users-for-a-course)

You can get a collection of users enrolled on a course. These are Moodle users and not Laravel user models.

```
$enrolledUsers = LaravelMoodle::getEnrolledUsersForCourse(2);

echo $enrolledUsers[0]->fullname; // Test User
echo $enrolledUsers[0]->roles[0]->shortname; // Student
```

### Get Categories

[](#get-categories)

Get all categories.

```
$categories = LaravelMoodle::getCategories();

echo $categories[0]->name; // Category name
```

### Search Categories

[](#search-categories)

Search for categories. Defaults to searching name if second parameter isn't passed. The search term is an exact match only.

```
$categories = LaravelMoodle::searchCategories('Business Briefing System');

echo $categories[0]->name; // Business Briefing System
```

### View Page Event

[](#view-page-event)

Trigger the view page event for activity auto completion. Pass in the page id. Returns true if successful and MoodleException if unsuccessful.

```
$pageViewed = LaravelMoodle::viewPageEvent(1);

dd($pageViewed); // true
```

HasDates Trait
--------------

[](#hasdates-trait)

The package has a HasDates trait that can be added to FlexibleDataTransferObjects to convert the timestamp from Moodle into a Carbon instance to allow easier formatting for presentation.

```
$data = LaravelMoodle::getCourses();

$data->courses[0]->asDate('startdate')->format('d/m/Y');
$data->courses[0]->dates()->startdate->format('d/m/Y');
$data->courses[0]->dates()->enddate->format('d/m/Y');
```

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance74

Regular maintenance activity

Popularity17

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~92 days

Recently: every ~64 days

Total

14

Last Release

204d ago

PHP version history (3 changes)0.0.0PHP &gt;=7.4

0.1.0PHP ^8

0.2.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/17785811?v=4)[Anthony Edmonds](/maintainers/AnthonyEdmonds)[@AnthonyEdmonds](https://github.com/AnthonyEdmonds)

---

Top Contributors

[![AnthonyEdmonds](https://avatars.githubusercontent.com/u/17785811?v=4)](https://github.com/AnthonyEdmonds "AnthonyEdmonds (116 commits)")

###  Code Quality

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/networkrailbusinesssystems-laravel-moodle/health.svg)

```
[![Health](https://phpackages.com/badges/networkrailbusinesssystems-laravel-moodle/health.svg)](https://phpackages.com/packages/networkrailbusinesssystems-laravel-moodle)
```

###  Alternatives

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[league/oauth1-client

OAuth 1.0 Client Library

99698.8M106](/packages/league-oauth1-client)[gesdinet/jwt-refresh-token-bundle

Implements a refresh token system over Json Web Tokens in Symfony

70516.4M35](/packages/gesdinet-jwt-refresh-token-bundle)[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)[beatswitch/lock

A flexible, driver based Acl package for PHP 5.4+

870304.7k2](/packages/beatswitch-lock)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
