laravel make a model have an attribute with value - laravel

I have a model called template and field template - when being called it doesn't exist, so how do I create a property or attribute called template when calling it this is being called through ajax. I tried making an accessor but it's not creating the attribute 'template' getTemplateAttribute($value) so I made a with('template') and I can't seem to create the attribute template in my model when being called.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Template extends Model
{
protected $table = 'templates';
protected $fillable = ['title', 'directory', 'filename', 'created_at', 'updated_at'];
public function template() {
$this->attributes['template'] = 'test';
}
}
// and when calling it
public function show(Template $template)
{
$template = Template::findOrFail($template->id)->with('template');
return $template;
}

Use appends in model.. then use getAppendTypeAttribute(); the AppendType must be exact name as appends value..
class Template extends Model
{
protected $table = 'templates';
protected $fillable = ['title', 'directory', 'filename', 'created_at', 'updated_at'];
protected appends = ['template'];
public function getTemplateAttribute() {
return "test";
}
}
then
$template = Template::findOrFail($template->id);
return $template->template;

Related

How to call a Variable in Models in Laravel

I am trying to call a variable in my Models/Images.php which is for a very good reason but cannot.
My variable $langtitle = 'title'.config('app.LANG_COLUMN_CODE'); which I want to use instead of 'title' within protected $searchable
Here is my whole code:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\Traits\Search;
class Images extends Model
{
use Search;
protected $guarded = array();
public $timestamps = false;
protected $fillable = [
'title', 'description', 'categories_id', 'metakeywords', 'hash', 'subgroup','subcategories_id'];
protected $searchable = [
'title',
'metakeywords',
'subgroup'
];
public function user() {
return $this->belongsTo('App\Models\User')->first();
}
public function category() {
return $this->belongsTo('App\Models\Categories', 'categories_id');
}
public function subcategories() {
return $this->belongsTo('App\Models\Subcategories', 'subcategories_id');
}
public function tags() {
return $this->hasMany('App\Models\Images', 'metakeywords');
}
}
I get errors like Constant expression contains invalid operations
As $searchable is getting called somewhere, better to use it directly where this $searchable is gettinh called.
See for $this->searchable and replace with:
$langtitle.",".'subgroup, metakeywords';
Hint: As I can understand, this might be in Search Traits!

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.

Custom pivot model class does not exist in controller

I got a pivot table which holds extra data. So i created a custom pivot model like shown in the docs for Laravel 5.6.
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PersonaTreeleave extends Pivot
{
public $timestamps = false;
protected $table = 'persona_treeleave';
protected $fillable = [
'FK', 'RoleTitle', 'Merkmale'
];
public function treeleave_id(){
return $this->hasOne('App\Treeleave');
}
public function persona_id(){
return $this->hasOne('App\Persona');
}
}
In a controller file i want to attach a user to an already existing "treeleave".
App\Treeleave::where('cid',$P['OE'])
->where( 'tree', $Baum->id)->first()
->Persons()->attach($DBUser, [
'FK' => $P['FK'],
'RoleTitle' => $P['RoleTitle'],
'Merkmale' => json_encode($P['Merkmale'])
]
);
I keep getting an error like "Class 'App\PersonaTreeleave' not found".
I dont get why that happens. It doesn't help if i add "Use App\PersonaTreeleave" in the controller file.
If i do this
dump(class_exists('App\Treeleave'));
dump(class_exists('App\PersonaTreeleave'));
it generates this output:
true
false
Anybody got a hint?
The classes for "treeleave" and "persona"
namespace App;
use Illuminate\Database\Eloquent\Model;
class Treeleave extends Model
{
protected $table = 'treeleaves';
public $timestamps = false;
protected $fillable = ['parent','lft','rgt','ebene','oe_titel','tree','meta'];
public function Baum(){
return $this->belongsTo('App\Tree');
}
public function Persons(){
return $this->belongsToMany('App\Persona')
->withPivot('FK', 'RoleTitle', 'Merkmale')
->using('App\PersonaTreeleave')
;
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Persona extends Model
{
public $timestamps = false;
protected $attributes = [
'titel' => ''
];
protected $fillable = [
'nachname', 'vorname', 'titel', 'projekt', 'email', 'geschlecht', 'cid'
];
public function logins(){
// erwartet Relations-Tabelle "login_project" (alphabetische Reihenfolge der beteiligten Tabellen, Namen im Singular)
return $this->belongsToMany('App\Login');
}
public function OE(){
return $this->belongsToMany('App\Treeleave')
->withPivot('FK', 'RoleTitle', 'Merkmale')
->using('App\PersonaTreeleave')
;
}
public function setTitelAttribute($value)
{
$this->attributes['titel'] = (string)$value;
}
}
Try running:
composer dump-autoload
To update your autoload file with the new class info.

Any Way to Auto Guarded Timestamps?

$fillable = ['*']
Model::create($request->all()); // frontend can inject 'created_at'
$guarded = ['created_at', 'updated_at', 'deleted_at']
Can we auto guard timestamp?
I don't want to do this:
$fillable = ['field_1........field_20']
You can use except() method of Illuminate\Http\Request that will return all request fields but will exclude of the list the specified keys.
// try this...
Model::create($request->except('created_at', 'updated_at', 'deleted_at'));
You can create a BaseRequest class that override the Illuminate\Http\Request, same as:
<?php
namespace YourClass\Name\Space;
class BaseRequest extends Illuminate\Http\Request
{
const EXCEPT_FIELDS = ['created_at', 'updated_at', 'deleted_at'];
public function all()
{
return $this->except(self::EXCEPT_FIELDS);
}
}
and inject the new BaseRequest class into your controller instead of the Illuminate\Http\Request class.

RelationNotFoundException in RelationNotFoundException.php

each product hasMany property.
when I use with function:
dd(Product::with(ProductProperty::class)->get());
I got this error :
RelationNotFoundException in RelationNotFoundException.php
Call to undefined relationship [App\Models\ProductProperty] on model [App\Models\Product].
class Product extends Model
{
protected $table = 'products';
protected $fillable = [
'user_id' ,'brand_id' , 'title', 'price', 'current_buy','max_buy','min_buy_per_bill',
'max_buy_per_bill','count','off','seri','short_description','long_description',
];
public function ProductProperty()
{
return $this->hasMany('App\Models\ProductProperty');
}
}
class ProductProperty extends Model
{
protected $table = 'products_properties';
protected $fillable = [
'product_id' ,'parent_id' , 'title','value', 'price', 'current_buy','max_buy','min_buy_per_bill',
'max_buy_per_bill','count','off','seri','short_description','long_description',
];
public function Product()
{
return $this->belongsTo('App\Models\Product');
}
}
Looking at your code you can't use ::class with the with() function. The main reason is the ::class will return the full path with namespace.
Product::with(ProductProperty::class)->get(); is incorrect.
Replace it with Product::with('ProductProperty')->get();

Resources