I have model something like that with custom attribute
class MyModel extends Model
{
public function getExtraAttribute(){
return 'some string'; //etc.
}
}
And for controller method i have this
return MyModel::where('user_id', Auth::user()->id)->get();
But i don't see 'extra' attribute on json response
P.s. extra isn't column from database.
Add the attribute to $appends.
class MyModel extends Model {
...
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = ['extra'];
...
}
As per the docs here: https://laravel.com/docs/5.4/eloquent-serialization#appending-values-to-json
class User extends Model
{
protected $appends = ['extra'];
public function getExtraAttribute()
{
return $this->attributes['extra'] = 'some string...';
}
}
Related
I was introduced to Spatie\LaravelData when I was searching for how to implement DTOs in Laravel.
Using Data classes for insert/update for a single model is pretty straightforward. I tend to keep my updates atomic in this way.
However I have a problem for using LaravelData to retrieve objects and send to front end, specially with nested models.
I have this example I have Post and Category models:
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'category_id'
];
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}
class Category extends Model
{
use HasFactory;
protected $fillable = [
'category',
'description'
];
}
I have these Data classes:
class PostData extends Data
{
public function __construct(
public string $title,
public string $category_id,
) {
}
}
class CategoryData extends Data
{
public function __construct(
public string $category,
public string $description
) {
}
}
I want to be able to send a STO object with Post and its Category, also would love to be able to have a collection of Posts and their Categories for index page.
I tried using this approach as described in their documentation, but first it gives an error and second I'm not sure how to return that from index() or view() methods in controller:
class PostData extends Data
{
public function __construct(
public string $title,
public string $category_id,
#[DataCollectionOf(CategoryData::class)]
public DataCollection $category,
) {
}
}
Anyone ever used Spatie\LaravelData for returning DTOs to from end?
You are trying to use a DataCollection when you should be using nesting. This is because your post has a BelongsTo relationship with the category model.
class PostData extends Data
{
public function __construct(
public string $title,
public string $category_id,
public CategoryData $category,
) {
}
}
How can I declare my model relationships and custom attributes properly so that they will be available from auto-completion and have the warning "property accessed via magic method" disappear?
I have nothing above my Model class and I've tried a few examples but none seems to work. i.e #method, #param or I just can't figure out the proper syntax for it.
quantity_remaining is a custom attribute for my Model.
I have it like this ATM:
class MyModel extends Model
{
/**
* #return HasOne
*/
public function packages(): HasOne{
return $this->hasOne(Package::class, 'related_id', 'related_id');
}
public function getQuantityRemainingAttribute(): Int{
//more codes here but not needed for this example
return 1;
}
}
You might want to define properties in the class doc block. I renamed the packages relationship to package, because it is a hasOne relationship.
/**
* #property Package $packages
* #property int quantity_remaining
*/
class MyModel extends Model
{
public function package(): HasOne{
return $this->hasOne(Package::class, 'related_id', 'related_id');
}
public function getQuantityRemainingAttribute(): Int{
return 1;
}
}
You will need to define fields in model class like:
public mixed $name;
public mixed $surname;
public mixed $email;
public mixed $password;
while your fillables are:
protected $fillables = ['name', 'surname', 'email', 'password'];
I'm quite new to Laravel and now I'm trying to move parts of a former application from a small self written framework into Laravel. The address book is multilingual therefor the table structure is a little more complicated.
db-structure
And this is my source code:
AddressBookController.php
namespace App\Http\Controllers;
use App\AddressBook as AB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class AddressBookController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$entries = AB::all();
return view('addressBook')->with([
'class' => __CLASS__,
'function' => __FUNCTION__,
'line' => __LINE__,
'entries' => $entries,
]);
}
}
Model AddressBook.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AddressBook extends Model
{
protected $table = 'address';
protected $primaryKey = 'address_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
protected $searchable = [
'columns' => [
'address.address_surname' => 10,
'address.address_company' => 5,
'address.address_vatid' => 2,
],
];
public function country() {
return $this->hasOne('country', 'country_id', 'country_id');
}
public function addresstype() {
return $this->hasOne('addresstype', 'addresstype_id', 'addresstype_id');
}
}
Model Country.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
protected $table = 'country';
protected $primaryKey = 'country_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
public function translation() {
return $this->hasOne('translations', 'translations_id', 'translations_id');
}
public function addressbook() {
return $this->belongsTo('address', 'country_id', 'country_id');
}
}
Model AddressType
namespace App;
use Illuminate\Database\Eloquent\Model;
class AddressType extends Model
{
protected $table = 'addresstype';
protected $primaryKey = 'addresstype_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
public function translation() {
return $this->hasOne('translations', 'translations_id', 'translations_id');
}
public function addressbook() {
return $this->belongsTo('address', 'addresstype_id', 'addresstype_id');
}
}
Model Translation.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Translation extends Model
{
protected $table = 'translations';
protected $primaryKey = 'translations_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
public function country() {
return $this->belongsTo('country', 'translations_id', 'translations_id');
}
public function addresstype() {
return $this->belongsTo('addresstype', 'translations_id', 'translations_id');
}
}
The request "$entries = AB::all();" works in general but I get the id's and maybe I'm completely wrong here but I thought that data from foreign keys will be replaced with the respective models (if configured correctly). so my question is:
a. did I make a mistake during configuration and if yes, where exactly is the error?
or
b. is my assumption of replacing id's with objects is completly wrong?
Thanks in advance!
Steve
Laravel Eloquent models do not replace the foreign keys of the active records with the relational data, it only appends a new property with the same name as the method relating the classes and in that property it puts all the Model instances of the resulted query, this ONLY if you access the property, its called Eager Loading.
It is explained here (Ofiicial Documentation)
$addressBook = App\AddressBook::find(1); //this only will return the active record with the id 1 and nothig more.
$addressBook->country; // The property "country" does not exist in the AddressBook Classs but eloquent models will return a "fake" property with the value of the result of the query by the method with the same name (only if the method returns an Eloquent Relation).
This Eloquent behavior is natural, and is a very clever way to minimize the number of queries, Eloquent will never load a relation if there is no need to.
If you want to load a relation in a set the models at the same time that those models are retriving from the db you need to explicitly especify wich relations you want to load.
$addressBook = App\AddressBook::with(['country', 'addresstype', 'anotherRelation'])->get(); // this will retrive all the addressBook models and in each one will attach the relations specified.
[EDITED]
Also you have to place the entire namespace of the related model class in the relation methods so you need to replaced like:
class Translation extends Model
{
protected $table = 'translations';
protected $primaryKey = 'translations_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
// ****** You need to put the entire namespace of the Model class
public function country() {
return $this->belongsTo('App\Country', 'translations_id', 'translations_id');
}
I am having a problem accessing morphOne relationship
In my controller I have
$post = Post::with('content')->where('id', 1)->get();
dd($post);
this gives
This is setup of my classes:
Post.php
class Post extends Model
{
use Contentable;
Contentable.php
trait Contentable {
public function content()
{
return $this->morphOne(Content::class, 'contentable');
}
Content.php
class Content extends Model
{
protected $table = 'content';
public $timestamps = false;
}
If in controller I do this:
dd($post->content());
I get Method content does not exist.
or
dd($post->content);
I get Property [content] does not exist on this collection instance.
I'm trying to display the user group name in a view using Auth::user()->user_group->name, but apparently that doesn't work as I keep getting Trying to get property of non-object.
The code goes as follow
User_Group.php Model
<?php
class User_Group extends Eloquent {
protected $table = 'user_groups';
public function users() {
return $this->hasMany('User');
}
}
User.php Model
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function user_group()
{
return $this->belongsTo('User_Group', 'user_groups_id');
}
public function getGravatarAttribute()
{
$hash = md5(strtolower(trim($this->attributes['email'])));
return "http://www.gravatar.com/avatar/$hash?s=100";
}
public function isAdmin()
{
return $this->user_groups_id == 1;
}
}
My profile.blade.php view
<small><p class="pull-right">{{ Auth::user()->user_group->name }}</p></small>
Doing the following will print the user group id reference though:
{{ Auth::user()->user_groups_id }}
Rename the method to group instead of user_group