Models
there is a model class that contains some useful and shorthand methods. in continue, we will introduce the features of our model class.
Paginatable
You can determine the default number of items in pagination for each model
separately. to do so, you can override the $perPageMax
property or just
call setPerPageMax
method inside of booted
method.
1use Hans\Valravn\Models\ValravnModel;
2
3class Example extends ValravnModel {
4
5 protected static int $perPageMax = 20;
6
7 protected static function booted() {
8 self::setPerPageMax(20);
9 }
10
11}
However, you can override the amount of items per page by per_page
query
string.
domain/api/blog/categories?per_page=5
Available methods
aliasForModelAttributes
This method is useful when you want to define an alias for an attribute or a foreign key of a model. its usage should be something like this:
1use Hans\Valravn\Models\ValravnModel;
2
3class Comment extends ValravnModel {
4
5 protected $fillable = [
6 'content',
7 'its_post_id'
8 ];
9
10 public function itsPostId(): Attribute {
11 return new Attribute( get: fn() => $this->{Post::foreignKey()} );
12 }
13
14 protected static function booted() {
15 self::saving(
16 fn( self $model ) => self::aliasForModelAttributes(
17 $model,
18 [
19 Post::foreignKey() => 'its_post_id'
20 ]
21 )
22 );
23 }
24
25
26}
And the itsPostId
attribute method helps us get the related value using the
same way of a real attribute.
table
It's a shorthand for getting table name of a model class.
1Example::table()
2// instead of
3( new Example )->getTable();
foreignKey
It's a shorthand for getting foreign key of a model class.
1Example::foreignKey()
2// instead of
3( new Example )->getForeignKey();
Contracts
Valravn arrives with a couple of contracts that each one brings some features to your model class.
Available contracts
EntityClasses
Force you to implement methods that used for getting related repository and services classes.
Filterable
Using this interface you can determine your filterable columns that could be access through api requests. there is an example of implementing this interface.
1public function getFilterableAttributes(): array {
2 return [
3 'id',
4 Post::foreignKey() => 'its_post_id',
5 'title',
6 'description',
7 'status',
8 'created_at',
9 ];
10}
As you can see, you can set alias for a column.
Loadable
This contract ables you to define what relations can be loaded and what resource class is responsible for. there is an example of how you should implement it.
1public function getLoadableRelations(): array {
2 return [
3 'category' => CategoryResource::class,
4 'comments' => CommentCollection::class,
5 ];
6}
ResourceCollectionable
By implementing this contract, you can access resource classes of a model. this is very useful and handy in writing codes.