Return dummy info from laravel relationship - laravel

In laravel we specify foreign keys this way
public function creator() {
return $this->belongsTo('App\Models\User', 'creator_id', 'id');
}
Is there some way to return dummy user ('system') when creator_id is null?
Reason: to display it in template.
For example:
If creator_id = 10 => creator = {id: 1, name: 'John'}
If creator_id = null => creator = {id: 0, name: 'system'}

Try this in your template :
{{ (model->creator) ? model->creator->name : 'system' }}
model will replace with your variable name.

Create a dummy user with id = 0 and name = 'System'.
Give the creator_id a default value of 0 in the migration

Related

How to use Accessor as a condition in Laravel?

I have this Accessor bellow which returns one string result (example: 'Ready' or 'Ongoing' ...):
public function getMinimumStatusAttribute()
{
$statusIds = [];
$tasks = $this->tasks()->get();
foreach ($tasks as $task) {
array_push($statusIds, $task->task_status_id);
}
return taskStatus::orderBy('order', 'asc')
->where('operational_status', '=', true)
->whereIn('id', $statusIds)->value('name');
}
I have TeamleaderDeal model :
return TeamleaderDeal::all();
which returns:
[
{
"id": 4,
"teamleader_id": "8b03da5a-af1f-051d-ad6d-b6199c7f7c35",
"created_at": "2019-09-09 11:41:46",
"updated_at": "2019-09-14 20:57:03",
"title": "Brand identity #2",
"reference": "12",
"lead_company_id": "adeddc13-6962-0a19-ac72-6713d1cf1455",
"teamleader_company_id": 1,
"dealphase_id": "199a34fc-de5c-038d-a655-c61fa4d97d17",
"estimated_closing_date": null,
"po_number": "az215487",
"teamleader_deal_phase_id": 6,
"dealPhase": "Refused",
"tasksCount": 5,
"companyLanguage": "nl",
-------------------------
"minimumStatus": "ready", ||||||accessor results
-------------------------
"invoiced": 1,
(...)
I would like to filter TeamleaderDeal results by MinimumStatus to show for example only results where MinimumStatus equal to 'Ready' ?
Thanks
You may use
public function getMinimumStatusAttribute($minimumStatus = NULL) {
if($minimumStatus === 'Ready') {
// do the magic here
$statusIds = [];
$tasks = $this->tasks()->get();
foreach ($tasks as $task) {
array_push($statusIds, $task->task_status_id);
}
return taskStatus::orderBy('order', 'asc')
->where('operational_status', '=', true)
->whereIn('id', $statusIds)->value('name');
}
// else return default value
return $this->attributes['minimum_status'];
}
Edit
Regarding your updates you may use reject method provider by Laravel Collection
E.g
$teamleaderDeals = TeamleaderDeal::all();
return $teamleaderDeals->reject(function ($teamleaderDeal) {
return $teamleaderDeal->minimumStatus !== 'Ready';
});
I think you need this simple where clause:
return taskStatus::orderBy('order', 'asc')
->where('operational_status', '=', true)
->where('name', 'Ready')
->whereIn('id', $statusIds)->value('name');
What are accessors?
Accessors create a dummy attribute on the object which you can access as if it were a database column. So if your database has user table and it has FirstName and LastName column and you need to get full name then it will be like.
Syntax of accessors:
get{Attribute}Attribute
Example :
public function getFullNameAttribute(){ return $this->FirstName. " ".$this->LastName;}
After that you can get full user name with below accessors.
{{ $user->full_name }}
After that you can get full user name with below accessors.
{{ $user->full_name }}
What is Mutator ?
Mutator is use to set value of attribute, a mutator transforms an eloquent attribute value when it is set.
How to define a mutator,
set{Attribute}Attribute
Above method on your model where {Attribute} is the "studly" cased name of the column you wish to access.
Example :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Register extends Model
{
/**
* Set the user's first name.
*
* #param string $value
* #return void
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = strtolower($value);
}
}
Now you can use this in your controller like.
use App\Models\Register;
$register= Register::find(1);
$register->name = 'Websolutionstuff';

Laravel: How to define relations while the primary key of the model is changed to slug?

I like to define Many To Many Polymorphic Relations like the one that is mentioned in laravel documentation, but with one difference that I like the primary key to be changed to slug. I do that in the model by protected $primaryKey = 'slug' but when I do that I can not retrieve relations anymore. I guess I must change the arguments of morphToMany and morphedByMany method to fix this. However, I don't know how should I do that.
I would appreciate your help.
posts
id - integer
name - string
slug - string (primary key)
videos
id - integer
name - string
tags
id - integer
name - string
taggables
tag_id - integer
taggable_id - integer
taggable_type - string
This is how it looks like.
// morphToMany($related, $name, $table = null, $foreignPivotKey = null,
$relatedPivotKey = null, $parentKey = null,
$relatedKey = null, $inverse = false)
So try this one in your Post model.
class Post extends Model
{
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable', null, null, 'taggable_id');
}
}
Hope this will help you.

laravel morphToMany relationship create() method don't save relatedPivotKey expectly

It's a many-to-many relationship. [Attachment] can be used for user's avatar or comment detail attachment image. table structure:
CommentDetail
id - integer
cid - integer
content - text
User
id - integer
name - string
Attachment
id - integer
key - string
AttachmentRelationship
id - integer
target_type - string ('user_avatar' or 'comment_detail')
target_id - integer (User -> id or CommentDetail -> cid)
attachment_key - string (Attachment -> key)
first, in AppServiceProvider, I had custom morphMap:
Relation::morphMap([
'comment_detail' => CommentDetail::class,
'user_avatar' => User::class,
]);
then in CommentDetail model, define attachment() method to get all attachments:
public function attachments()
{
return $this->morphToMany(
Attachment::class,
"target",
"attachment_relationships",
"target_id",
"attachment_key",
"cid",
"key"
);
}
now the problem comes. when I create a attachment through commentDetail like this:
$commentDetail = CommentDetail::findOrFail(4);
$attachment = $commentDetail->attachments()->create([
'key' => (string)\Uuid::uuid4(),
]);
it will create a [Attachment] record:
id key
10 968e22b8-e4fb-4743-bf08-8ac9cd8ecd56
and a [AttachmentRelationship] record:
id target_type target_id attachment_key
1 comment_detail 7 10
my question: why the [AttachmentRelationship] record 'attachment_key' field's value is not the [Attachment] record 'key' field's value = 968e22b8-e4fb-4743-bf08-8ac9cd8ecd56 (now it's 'id' field's value = 10) ?

Eloquent relationship in Laravel

I'm having following table structure:
Table Name - Users
Column: id, name, email, etc
Table Name - Plugins
Column: id, theme_id, type_id, code,
Table Name - Templates
Column: id, theme_id, user_id, templatedata
Table Name - Userplugins
Column: id, user_id, plugins_id, contents
Now I'm calling the route with id of the templates, in which templatedata has JSON data, i'm able to get Plugins code by following code in my blade file as:
#foreach($gettemplate as $renderer)
{!! $plugins->find($renderer)->code !!}
#endforeach
but I'm unable to fetch contents in the UserPlugins table. Following is my controller where I'm trying to do so:
public function get_template($id)
{
$template = Template::findOrFail($id);
$gettemplate = json_decode($template->templatedata);
$plugins = Plugins::all();
$user = User::findorFail($id);
return $user->userplugins()->contents;
//return view('nitseditor.test', ['plugins' => $plugins, 'gettemplate' => $gettemplate, 'user' => $user]);
}
I've commented out my view just to check the output.
I've defined the relationship in the model my App/User.php file contains:
public function userplugins(){
return $this->hasMany('App\UserPlugin');
}
And in App\UserPlugin.php file I've:
protected $fillable = [
'contents',
];
I'm getting the following error:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$contents
Please help me out, Thanks.
In the following line:
return $user->userplugins()->contents;
When you call $user->userplugins() that mean you call an relation method. It's will not return Eloquent Collection or Eloquent Object for you.
You need to call
$user->userplugins
to get collection of UserPlugin
However, when you call
return $user->userplugins->contents;
you will get error, becauese return $user->userplugins is an Eloquent Collection, you can not get contents from it.
You can get the contents of specific UserPlugin. For example, the first UserPlugin of user like:
return $user->userplugins()->first()->contents;

Laravel - Convert database integer to an associated string

I have my users table with a column named status. In this column I just store a number, based off their status, 1 - admin, 2 - owner, etc. I know that I can display these values with {{ users->status }}, but only shows the stored number. How can I show the actual name instead of the stored number?
Use Eloquent Accessors & Mutators.
Define an array of statuses and use the status number from your database as a key to change the value in the model so that in the view {{ $users->status }} equals admin
class User extends Eloquent {
protected $statuses = array(
'1' => 'admin',
'2' => 'owner'
);
public function getStatusAttribute($value)
{
return $this->statuses[$value];
}
}
getStatusAttribute converts 1 to admin when retrieving a record.
You could also have a set method for when records are stored in the model.
In View {{ $user->status }} // echos 'admin'

Resources