Hiding attributes per function - laravel

We can use:
protected $hidden = array('attribute');
to hide the attributes we don't want to send to our views.
And i found out writing:
$this->table = 'table';
In a specific function resulted in another that table being used.
But what would we do if we need to hide some attributes in a specific function only?
Kinda like this:
$this->hidden = array('attribute1', 'attribute2');
That didn't work though.

You should really understand how to use models.
In your model you can set several properties, for example, what table the model should use:
protected $table = 'my_users';
Or which attribtues of the model will be hidden:
protected $hidden = array('password');
Or which attributes are fillable (whitelisted), and so protecting from mass assignment vulnerabilities:
protected $fillable = array('first_name', 'last_name', 'email');
Or which attributes should be blacklisted:
protected $guarded = array('id', 'password');
So, you're not dealing with these properties/attributes by function, but by class (model).
If you set certain attributes as hidden in a model, they will be hidden from Array or JSON conversions regardless.

Related

Attempt to read property "id" on null Laravel 8 eloquent

I have a query that fetches comments of posts. It returns this error when a particular post has no comments. Below is my query.
$comments=PostComments::with('user:id,username')
->where('post_id',$this->id)->latest()->get();
This is my Comments model
protected $table = "post_comments";
protected $fillable = ['comment','post_id','user_id'];
protected $hidden = ["updated_at","laravel_through_key","post_id"];
// Carbon instance fields
protected $dates = ['created_at', 'updated_at'];
public function user(){
return $this->hasMany(User::class,'id','user_id')->latest();
Your $this must be null. You could show a screenshot of the error where it will show you the line where the error occurred, which would make debugging it easier.

Laravel / Eloquent - Prevent "deleted_at" Column From Being Returned by get() Method

I have a model that looks like:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Location extends Model{
use SoftDeletes;
// Name of our database table
protected $table = 'locations';
// Column for soft deletes
protected $dates = ['deleted_at'];
// Columns that are mass assignable
protected $fillable = ['name', 'address', 'city'];
}
When I call Location::get(), the deleted_at column is returned by default.
How do I prevent this column from being returned without explicitly specifying it?
You can use the $hidden property like this :
protected $hidden = ['deleted_at'];
From the documentation :
Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a $hidden property to your model:

Bypass "mass assignement" laravel

I have hundreds of fields in my table and I dont want to write all the field in the$fillablearray. Is there any way tobypass $fillable process` ?
class MyClass extends Eloquent {
protected $fillable = array('firstField', 'secondField',.......);
}
You could do it the opposite way:
Specify the guarded attributes (all fields that should not be fillable).
protected $guarded = array('id', 'created_at', '...');
And remove the $fillable completely.

Eloquent attribute type casting doesn't work in some models

Eloquent attribute casting is awesome, this is great feature that is useful to cast from DB type to native language types.
Boolean in my db is int(1), so I need to cast it to the bool type.
I have several models in my application, first model is User, and it works like a charm.
1 is converted into true, 0 into false, like I need.
class User extends Model {
protected $table = 'user';
protected $guarded = ['password','login','id','activationEmail'];
protected $hidden = [ 'password' ];
protected $casts = [
'activationEmail' => 'boolean',
'activationSMS' => 'boolean',
];
Everything is okay here, but I need to do the same trick in another model NewsArticle.
class NewsArticle extends Model
{
protected $table = 'news';
public $timestamps = false;
protected $casts = [
'Actual' => 'boolean',
];
}
But in this case cast doesn't work at all, I have tried to cast manually and it works, but casts array is ignored at all.
Is there any ideas where the problem can be ?
Thanks.
Sorry, I have made a mistake in file name of my class model, but the class name itself was correct and it successfully loaded because of some tricks with bootstrap file I have done in order to implement another task.
After file was renamed everything works like expected.

How do I prevent fetching data multiple times inside a Repository?

My EloquentUserRepository (concrete implementation) has some methods like getCompanies($userId) and getProfile($userId), for example.
In both cases, before returning stuff, they fetch the user, like so:
$user = User::find($userId);
So, when I need to call those two methods in the same request, the data is fetched twice.
Am I missing something or am I using repositories wrongly?
What if you approached it from the relationship side instead? I'm assuming that Companies live in a different table. So could you acquire the companies with something like this?
<?php
class User extends Model {
protected $table = 'users';
protected $fillable = ['name', 'email', 'avatar'];
protected $hidden = ['password', 'remember_token'];
public function companies()
{
return $this->hasMany('App\Company', 'user_id');
}
}
Then you could find the companies with:
$user = User::find($userId)->load('companies')->get();
and you'd already have the companies loaded.
If the profile is in a different table you could do a similar relationship, like this:
<?php
class User extends Model {
protected $table = 'users';
protected $fillable = ['name', 'email', 'avatar'];
protected $hidden = ['password', 'remember_token'];
public function profile()
{
return $this->hasOne('App\Profile', 'user_id');
}
}
I'm not certain if this is exactly what you are looking for, but it's the approach I like to use when finding items that are related to a particular model.

Resources