How to set a value using Mutators in a model? - laravel

I have a model where I am using a mutator for logged in user, assign id. But the value is not passed.
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
class Pass extends Model
{
use HasFactory;
protected $fillable = [
'title',
'user_id',
'source',
'category_id',
];
public function setUserIdAttribute()
{
$this->attributes['user_id'] = Auth::user()->id;
}
}

You should look at append Laravel documentation. Adding your attributes to the protected $appends array should add your attribute to your final model output.
So try:
protected $appends = ['user_id'];

Laravel has built-in methods to appends attributes to your model output. If for any reason, you cannot use those default methods, you can use setRawAttributes to dynamically add the field to your model. But laravel standard way should be better.
protected $attributes;
public function __construct(array $attributes = array())
{
$this->setRawAttributes(array(
'user_id' => Auth::user()->id), true);
parent::__construct($attributes);
}

Related

Polymorphic - Create inserting record and following up with blank record

I've setup a Polymorphic Relationship on my model for this, I've had to create matching fields to the table that the morph refers to.
So I've created a
Translation Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Translation extends Model
{
protected $table = 'translations';
protected $primaryKey = 'id';
protected $fillable = ['title', 'text_line1', 'text_line2', 'quote', 'language', 'content', 'translationable_type','translationable_id', 'content'];
use SoftDeletes;
public function translationable()
{
return $this->morphTo();
}
}
This is the Polymorph, Then in a seperate model - "Slides"
I've created this:
Slide Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Slide extends Model
{
/**
* Slide table
*/
protected $table = 'slides';
protected $primaryKey = 'id';
public function translations()
{
return $this->morphToMany('App\Models\Translation', 'translationable', 'translations', '', 'translationable_id');
}
}
Then in a controller, I've made a test script...
$slide = Slide::find(16);
$translations = array(
'text_line1' => $slide->text_line1,
'text_line2' => $slide->text_line2,
'language' => 'fr',
'translationable_id' => $slide->id,
'translationable_type' => 'App\Slide'
);
$slide->translations()->create($translations);
When I run this, It creates the record, But also creates another record that is totally blank other than referencing the translationable_id and translationable_type
Anyone know why it would do this?
Cheers.

Attach relation data directly to model

Article model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Articles extends Model
{
protected $table = 'articles';
protected $primaryKey = 'idArticle';
protected $fillable = [
'idArticle', 'Topic', 'Image', 'Content', 'Views',
];
protected $hidden = [
'idCategory', 'idUser',
];
public function category()
{
return $this->hasOne(Categories::class, 'idCategory', 'idCategory');
}
}
So now when i call $article = Articles::find(1);, it will returns data from articles table, when i add $article->category;, it adds data $article->category->Name. I would like to have that Name directly inside $article - something like $article->category (so $article->category->Name into $article->category) is it possible to define that just using model class or i need to map it inside controller?
You can assign custom attributes to your Model classes. But you can't use the same property name as your category() method, because it's already accessed by $article->category.
An example giving you a property called category_name
class Articles extends Model
{
// attributes to append to JSON responses
protected $appends = ['category_name'];
// ... your other properties and methods
// your custom attribute
public function getCategoryNameAttribute()
{
if (!is_null($this->category)) {
return $this->category->Name;
}
return '';
}
}
Use as:
$article->category_name
You can use appends, as mentioned by #matticustard or just use the ->with() method while retrieving your model:
$article = Articles::find($id)->with('category');
Then, you can access the category name with:
$categoryName = $article->category->name;
Hope it helps.

ORM not working in Default UserController & User Model in laravel

I want to get User wise Role. here is I'm facing error ....
UserController.php ( user controller file )
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use App\Employee;
use App\Role;
use App\User;
use App\Site;
use App\Client;
use App\ProjectType;
use App\UserPermission;
use Auth;
use DB;
use App\Project;
class UsersController extends BaseController {
public function __construct() {
$this->isSetClientAndProjectType();
$data = User::with('Role')->first();
echo "<pre>";print_r(json_decode($data)); die;
}
}
User.php ( user model file )
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable {
use SoftDeletes;
use Notifiable;
protected $fillable = [
'name', 'role_id', 'password', 'siteid', 'email', 'status', 'allowed_to_bypass_pm', 'allowed_to_bypass_admin'
];
protected $hidden = [
'password', 'remember_token',
];
// Get users roles
public function Role() {
return $this->hasMany('App\Role', 'role_id', 'id');
}
}
Error is
How can i solve this error?
Help me guys.
Thank You.
If a user has many "roles" it should be public function roles().
You have defined:
A single user has a role_id
Therefore you need:
If a user has a single role it would be:
public function role() {
return $this->belongsTo('App\Role');
}
The reverse on the Role model would be:
public function users() {
return $this->belongsToMany('App\User');
}
Since many users can have the same role.
Hope this helps.
You need to add belongsTo relationship
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable {
use SoftDeletes, Notifiable;
protected $fillable = [
'name', 'role_id', 'password', 'siteid', 'email', 'status', 'allowed_to_bypass_pm', 'allowed_to_bypass_admin'
];
protected $hidden = [
'password', 'remember_token',
];
// Get user's role
public function role() {
return $this->belongsTo('App\Role');
}
}
Now fetch data
$user = User::with('role')->find(1);
$role = $user->role;
You need to make sure your table structure and foreign key references are compatible with the model relationship methods used.
For example, you have used "HasMany" relationship on User model. For that, you will have to make sure that each record/row in users table(User model) "has many" associated records/rows in roles table(Role model).
Here HasMany method assumes a foreign key "role_id" on roles table(Role Model). On not finding of which, it throws error.
You first need to take in consideration the table structure of roles and users table(User and Role model) as per your requirement, and than add model relationship methods accordingly.
It can be a bit tricky if you are using the methods for the first time, you can refer the laravel documentation for the same:
eloquent-relationships

How to make hash password if import excel laravel 5.1

How to make hash password in the model laravel 5.1? any idea?
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Members extends Model {
//
protected $fillable = ['id', 'email', 'password', 'name', 'status_members'];
protected $table = 'members';
}
Put this in your model class
public function setPasswordAttribute($value){
$this->attributes['password'] = Hash::make($value);
}
This will hash the value everytime to send a password to the model.
As for the excel side of things please update your question with the current code you are using.

Laravel 5.2 eloquent returns soft deleted records

I am using Laravel 5.2.
I have a model as below:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
class ZoomMeeting extends BaseModel {
public $timestamps=true;
protected $table = 'zoom_meetings';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = ['user_id', 'uuid', 'meeting_id', 'host_id', 'topic', 'status', 'type', 'start_url', 'join_url', 'created_at'];
public function users() {
return $this->belongsTo('App\Models\User');
}
}
And the base model is as below:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Auth;
use Carbon\Carbon;
class BaseModel extends Model {
public $timestamps = false;
protected static function boot()
{
//parent::boot();
static::creating(function($model) {
if(empty($model->created_at))
{
$model->created_at = date('Y-m-d H:i:s');
}
return true;
});
static::updating(function($model) {
$model->updated_at = date('Y-m-d H:i:s');
return true;
});
}
}
I am using softdeletetrait in ZoomMeeting model, and soft deleting is working fine.
However, if I fetch records from the same model using eloquent, it returns the soft deleted records too. I am using code below to get the records:
$record = ZoomMeeting::where("user_id", $user_id)->where("meeting_id", $meeting_id)->orderBy("id", "DESC")->first();
The eloquent is building the query as:
select * from `zoom_meetings` where `user_id` = 3 and `meeting_id` = 707070707 order by `id` desc limit 1
See, there is no deleted at is null set in where statement. It is not preventing the deleted records.
I am not sure where am I making mistake?
It looks like you are overriding the boot method, but you aren't ever actually calling the parent boot method (it's commented out), so the trait is never getting initialized correctly. I believe that also means the data you have been deleting is actually being deleted from the database.
Is there a reason you need to override the boot method? What you are adding is already done handled by the framework, so it doesn't appear to be necessary.

Resources