Globally Hiding Attributes From Array Or JSON Conversion in laravel? - php

Sometimes you may wish to limit the attributes that are included in your model's array or JSON form, such as passwords. To do so, add a hidden property definition to your model:
class User extends Model {
protected $hidden = ['password'];
}
This is model specific.
Is there any method to hide globally?
ie,I want to hide deleted_at and created_by from all model json result.

The easiest way to do that is by creating a base model. Like this:
class BaseModel extends Model {
protected $hidden = ['deleted_at', 'created_by'];
}
And then all your models extend from that:
class User extends BaseModel {
}
Note that this way if you wanted to add some hidden fields for a specific model you would have to as well specify those two global hidden attributes:
class User extends BaseModel {
protected $hidden = ['deleted_at', 'created_by', 'password'];
}
If that bothers you, you could merge the global attributes in from the contructor:
class BaseModel extends Model {
private $globalHidden = ['deleted_at', 'created_by'];
public function __construct(array $attributes = array()){
$this->hidden = array_merge($this->globalHidden, $this->hidden);
parent::__construct($attributes);
}
}

Related

How to select foreign key value in Laravel

I've two tables one is car_category having the fields - id,type.
Another table named vehicle having field - c_id(FK Refers car - id).
Now I want to display the FK(c_id) value which is car-type.
I've below code in models,
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany('Vehicle');
}
}
vehicle model,
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo('Car');
}
}
What 'll be my query for this? I've tried this code, results error.
$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles
WHERE cars.id = vehicles.c_id";
How can I achieve this? Can anybody help me?
Try this
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany(Vehicle::class, 'c_id');
}
}
The vehicle model
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(Car::class, 'c_id');
}
}
Eloquent determines the foreign key of the relationship based on the model name. In this case, the Car model is automatically assumed to have a car_id foreign key. If you wish to override this convention, you may pass a second argument to the method
https://laravel.com/docs/5.5/eloquent-relationships#one-to-one
To get the Car along with their Vehicle information you can do a query using Eager Loading
$result = Car::with('vehicles')->get();
To get the Car along with their Vehicle information you can do a query using Eager Loading
$result = Car::with('vehicles')->get();
One more correction you have specified class name as string literals without specifying FQN, relationships in models should be defined using fully qualified name
Car Model
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany(\App\Models\Vehicle::class);
}
}
Vehicle Model
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(\App\Models\Car::class);
}
}
Change from class car to class Car
After that you can select with Car::first(), the related table data can be found in Car::first()->vehicles
You can also add a where() method on models, if you have more than one record, use a foreach()
In Model,
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(Car::class, 'c_id');
}
}
In controller,
$vehicles = Vehicle::all();
return view('vehicles.vehicle',['vehicles'=>$vehicles]);

I can not add methods to User Model in Laravel 5.4 ..!

I'm using Laravel 5.4. I have the methods I created in the User model. When I want to create an object from the User model and invoke my own methods, I can not get to the methods I added.
The User Model is derived from the Authenticable class at 5.4, which was derived earlier from the Model class. I think the problem is about it. What I really want to do is to set up the belong_to, has_many structure to relate the user model to the other models.
But with the User model I do not do that. What do you recommend ?
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getMakale()
{
return $this->hasMany(Makale::class, 'user_id', 'id');
}
}
$author = User::first();
return method_exists($author,'getMakale');
//eventually turns false
I believe you are potentially setting an accessor rather than a relationship. In this case I would think you want to name that function something like:
public function haberler()
{
return $this->hasMany(Makale::class, 'user_id', 'id');
}
or public function makales(). Prefixing your function name with get or set will have unintended consequences in Laravel.

Issue adding attribute values to Laravel model

I'm trying to create an additional attribute method in a model which appends a ratings label column to an existing rating model. I have the exact same code working for another model which adds click data. I'm getting an Undefined index: rating_label error - can't figure out why? Any help much appreciated.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Rating extends Model
{
protected $table = 'rating';
protected $primaryKey = 'rating_id';
protected $appends = array('rating_label');
/**
* Define a 1-many inverse relationship in eloquent
*/
public function Article()
{
return $this->belongsTo(Article::class, 'article_id');// (Model, primary_key)
}
/**
* Add additional column to Rating model for use in ClassifyingService class
*/
public function getRatingLabelAttribute()//accessor getter/setter
{
return $this->attributes['rating_label'];
}
}

Laravel's Eloquent's 'with' array is breaking

I am trying to abstract my models using a single base class. I have three models that inherit from the same base:
Repair
Inspection
Purchase
I am able to successfully create and persist the models to the DB, but when fetching I get a blank screen, no errors are thrown. When I remove the $with attribute everything seems to work.
Heres the code:
abstract class ItemType extends Model
{
public $timestamps = false;
protected $with = ['details'];
public function details()
{
return $this->morphOne(Item::class, 'type', 'item_details_type', 'item_details_id', 'id');
}
}
class Repair extends ItemType
{
protected $table = 'repairs';
protected $guarded = ['id', 'created_at', 'updated_at'];
protected $morphClass = self::class;
}
class Inspection extends ItemType {}
class Purchase extends ItemType {}
In the end I decided to use morphTo relationships without the abstract class to solve the issue.

Laravel Eloquent Model inserts all values as NULL

I have run into problems with Laravel Eloquent Model
I have a model as follow:
class Activity extends Eloquent {
protected $table = 'activity';
protected $timestamps = false;
public $item;
public $content;
public $year;
protected $fillable = array('item', 'content', 'year');
}
And the corresponding controller:
class ActivityController extends \BaseController {
public function create()
{
$activity = new Activity();
$actitity->item = 'Example';
$activity->content = 'Example content';
$activity->year = 2015;
$activity->save();
}
}
The above code should work fine and there should be a record in 'activity' table. However, all the value of columns of activity table are inserted as NULL when I run this code (except for the id column which is auto_increment).
In addition, when I var_dump the $activity (just before calling $activity->save()), the $activity with all of its properties are shown as expected (I mean, with values I've assigned before)
Is there any subtle error in my code?
You must not define database fields as actual class properties. The problem is that Laravel uses an $attributes array internally, not the models properties.
When doing
$activity->content = 'Example content';
Laravel uses the magic __set() method to update the value in it's $attributes array. But that setter method is never called because you have an actual property with that name.
What you need to do to resolve this problem is remove the properties:
class Activity extends Eloquent {
protected $table = 'activity';
protected $timestamps = false;
protected $fillable = array('item', 'content', 'year');
}
If you want to document the properties and have autocomplete support you can use the #property annotation:
/**
* #property string $item
* #property string $content
* #property int $year
*/
class Activity extends Eloquent {
This is because Eloquent uses magic setters/getters. If you did $model->randomAttribute then it would look into the models attributes array for the data.
Because you have explicitly defined each attribute it directly accesses the property and not the magic getter. When you call save(), the function saves all the data in the attributes array which contains nothing.
Remove the attribute definitions and it will work.
If you call $model->getAttributes() you will see there will be no data contained within.
Remove:
public $item;
public $content;
public $year;
from:
class Activity extends Eloquent {
protected $table = 'activity';
protected $timestamps = false;
public $item;
public $content;
public $year;
protected $fillable = array('item', 'content', 'year');
}

Categories