Skip to content

Creating relationships between exceptions and users

Tyler Arbon edited this page Apr 2, 2016 · 1 revision

Exceptions and Users

The version at the time of writing this is 3.2.0

Because LERN can collect the ID of the User, we can create an Eloquent Relationship between our Exceptions and Users. This could be helpful for example if you wanted to pull a list of all the errors from a specific user to try and resolve an issue that user is experiencing

For this example, let's create our own Error model that will extend LERN's ExceptionModel. Once created we can define our relationship like so:

/* 
 * app/Error.php 
 */
namespace App;

use Tylercd100\LERN\Models\ExceptionModel;

class Error extends ExceptionModel {

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

And now define the inverse on your User model:

/* 
 * app/User.php 
 */
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model {

    public function errors()
    {
        return $this->hasMany(Error::class);
    }
}

Now we can query our errors and print them out:

$user = App\User::with('errors')->find(1);
foreach($user->errors as $err){
    echo "{$err->class}: {$err->message}".PHP_EOL;
}
/*
 *App\Exceptions\File\ExceededUploadLimitException: File exceeded upload limit of 50MB.
 *App\Exceptions\Video\IncorrectVideoTypeException: Incorrect file type! pdf (application/pdf).
 */
Clone this wiki locally