How to call a Variable in Models in Laravel - 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!

Related

Laravel TypeError in many to many relationship

I have 3 models: Order, Products, OrderProducts:
class Order extends Model
{
use HasFactory;
protected $fillable = [
'name',
];
public function products(){
return $this->belongsToMany(OrderProduct::class);
}
}
class Products extends Model
{
use HasFactory;
protected $fillable = [
'name', 'link', 'buyprice', 'sellprice','weight',
];
public function orders(){
return $this->belongsToMany(OrderProduct::class);
}
}
class OrderProduct extends Model
{
use HasFactory;
protected $fillable = [
'order_id', 'product_id',
];
public function orders() {
return $this->belongsToMany(Order::class);
}
public function products() {
return $this->belongsToMany(Products::class);
}
}
When i view a specific Order i want to display all associated products, which i try to retrieve like this in my controller:
public function show($id)
{
//$products = Products::all();
$order = Order::where('id',$id)->first();
$orderList = $order->products();
return $orderList;
}
The error i get it:
TypeError
Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, called in D:\laravel\pricing\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 72
How can i get collection of all products for a specific order?

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.

laravel make a model have an attribute with value

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;

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();

How to use "select" method to reduce data transfer when using Eager Loading

I have a API and its taking long time to get all the info and its because I'm only hidding some data but I want to omit not to hidde. I found select() method to chose wich data send and reduce the time to query all information I really need.
Im trying to use select just after the relation just like this, just to retrieve only name from OPR_User table:
public function creatorUser() {
return $this->belongsTo('Knotion\OPR_User', 'idCreatorUser', 'idUser')->select('name');
}
but is not working
This is my Model code
<?php
namespace Knotion;
use Illuminate\Database\Eloquent\Model;
class CTL_Resource extends Model {
protected $table = "CTL_Resource";
protected $primaryKey = "idResource";
public $incrementing = false;
public $timestamps = false;
public static $snakeAttributes = false;
protected $hidden = [
'coachVisibility', 'thumbnail',
'studentVisibility', 'isHTML','studentIndex', 'coachIndex',
'isURL', 'source', 'path', 'status', 'updateTime', 'isfolder',
'parentResource', 'idModifierUser', 'idResourceType', 'idCreatorUser', 'idCreationCountry'
];
protected $fillable = ['idResourceType','productionKey', 'idCreatorUser', 'idModifierUser', 'idCreationCountry', 'title', 'description', 'URL', 'fileName', 'extension', 'minimumAge', 'maximumAge', 'productionKey'];
public function creatorUser() {
return $this->belongsTo('Knotion\OPR_User', 'idCreatorUser', 'idUser');
}
public function creationCountry() {
return $this->belongsTo('Knotion\CTL_Country', 'idCreationCountry', 'idCountry');
}
public function resourceType() {
return $this->belongsTo('Knotion\CTL_ResourceType', 'idResourceType', 'idResourceType');
}
public function quickTags() {
return $this->belongsToMany('Knotion\CTL_QuickTag', 'CTL_Resource_has_QuickTags', 'idResource','idQuickTag');
}
public function tags() {
return $this->belongsToMany('Knotion\CTL_Tag','CTL_Resource_has_Tags', 'idResource', 'idTag');
}
public function relatedTo() {
return $this->belongsToMany('Knotion\CTL_RelatedTo', 'CTL_Resource_has_RelatedTo', 'idResource', 'idRelatedTo');
}
}
this is my relation model code (just in case needed):
<?php
namespace Knotion;
use Illuminate\Database\Eloquent\Model;
class OPR_User extends Model {
protected $table = "OPR_User";
protected $primaryKey = "idUser";
public $incrementing = false;
public $timestamps = false;
public static $snakeAttributes = false;
protected $hidden = ['firstName', 'secondName', 'firstSurName', 'secondSurName', 'password', 'picture', 'status', 'createTime', 'updateTime', 'idUserType', 'email'];
public function resources() {
return $this->hasMany('Knotion\CTL_Resource', 'idResource');
}
public function userType() {
return $this->belongsTo('Knotion\CTL_UserType', 'idUserType', 'idUserType');
}
}
and this is my Controller code:
public function index(Request $request) {
$resources = CTL_Resource::all();
$resources->resourceType->select('name');
return $resources->load('creatorUser', 'creationCountry', 'resourceType', 'tags', 'quickTags', 'relatedTo');
}
When you add the ->select after the ->belongsTo it's no longer an actual relationship type, it's a query builder. You need to add the select afterwards before you call the ->load.
To fix the problem I had to include the id also in the relation, something like this:
public function resources() {
return $this->hasMany('Knotion\CTL_Resource', 'idResource')->select('idResource', 'name');
}

Resources