Call to a member function on a non-object eloquent attach - laravel

I am having an issue with laravel not seeing my tags() method for attaching new tags on a new entry. I keep getting Call to a member function on a non-object when I try to run the method and attach tags to my Tile model. All methods are returning their relations. I followed the same order as the documentation says eloquent.
Controller
$tile = \Tiles\Tile::find($tile_id);
$tile->tags()->attach($tag_array);
Model
<?php namespace Tiles;
use Illuminate\Database\Eloquent\Model;
class Tile extends Model {
/**
* The Tile table
* #var string
*/
protected $table = 'tiles';
/**
* Pivot table for tags
* #var string
*/
protected $pivot = 'tag_tile';
/**
* Get the tags associated with the given tile
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags() {
return $this->belongsToMany('Tiles\Tag', $this->pivot, 'tile_id', 'tag_id')->withTimestamps();
}
}

Try it
Model
public function tags() {
return $this->belongsToMany('Tiles\Tag', $this->pivot, 'tag_id', 'tile_id')->withTimestamps();
}

Thanks for all your help. I figured out the solution. I created a method in my model and pushed each to an array and fed it to the attach method. It works now.

Related

Laravel - add a class attribute to array

In my Eloquent Model I have added a class attribute:
/**
* #return bool
*/
public function getIsViewable()
{
return $this->isViewable;
}
This attribute is not saved in the database as it is just a computed value.
In my controller I have an Eloquent Collection of this object which I convert to an array:
$images = $query->get();
$images = $images->toArray();
How can I add the class attribute property to each image item in the array?
Method should be named getMyVariableAttribute ie. getIsViewableAttribute
On the model add the following protected $appends = ['is_viewable'] in order to get the computed property when serializing.
Your method name is missing the Attribute part. Rename getIsViewable() to getIsViewableAttribute()
/**
* #return bool
*/
public function getIsViewableAttribute()
{
return $this->isViewable;
}
https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

Laravel Nova BelongsTo Field Appending Namespace To Current Namespace

I am currently using laravel 5.8 with laravel nova.
When i use a model class inside my nova action file, like this:
Namespace App\Nova\Actions;
use App\Nova\User;
use Orlyapps\NovaBelongsToDepend\NovaBelongsToDepend;
class PlayerDD extends Action
{
public $name = 'Spelers toekennen';
/**
* Perform the action on the given models.
*
* #param \Laravel\Nova\Fields\ActionFields $fields
* #param \Illuminate\Support\Collection $models
* #return mixed
*/
public function handle()
{
}
/**
* Get the fields available on the action.
*
* #return array
*/
public function fields()
{
return [
BelongsTo::make(User::class)
];
}
}
Laravel returns the error: Class 'App\Nova\Actions\App\Nova\User' not found.
While i am using the root namespace for the User model, the namespace gets appended to the current namespace.
Is there a fix for this, and where should i look for conflicts?
Thanks in advance!
BTW, i tried this \App\Nova\User

Laravel Relationship Find UUID

I have make a Trait for UUID. I use a lot of relationschip inside my code. On a relationship you can do find() and findOrFail() but i have write a code for findU() and findUOrFail() but i can't use it inside a relationship. How can i fix it?
Trait:
<?php
namespace App\Modules\Base\Traits;
use Ramsey\Uuid\Uuid;
/**
* Trait Uuids
*
* #package Modules\Core\Traits
*/
trait Uuids
{
/**
* Boot function from laravel.
*/
public static function bootUuids ()
{
static::creating(function ($model) {
$model->uuid = Uuid::uuid4()->toString();
});
}
/**
* #param $uuid
*
* #return mixed
*/
public static function findU ($uuid)
{
return static::where('uuid', '=', $uuid)->first();
}
/**
* #param $uuid
*
* #return mixed
*/
public static function findUOrFail($uuid)
{
$post = static::where('uuid', '=', $uuid)->first();
if( is_null($post) ) {
return abort(404);
} else {
return $post;
}
}
}
Controller:
/**
* Show
*/
public function show(Request $request, $uuid)
{
return responder()->success($request->user()->projects()->findUOrFail($uuid))->respond();
}
Error:
Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany::findUOrFail()
Assuming you don't need id since you're using uuid
In your migration file you need:
$table->uuid('uuid');
$table->primary('uuid');
In your model:
use Uuids;
protected $primaryKey = 'uuid';
public $incrementing = false;
Or much easier
In your migration file:
$table->uuid('id');
$table->primary('id');
In your model:
use Uuids;
public $incrementing = false;
You don't need to override findOrFail or find
It should help to have the function referenced directly in the model rather than trying to access it directly in a trait. I am assuming that you are including the Uuids trait above in your projects model. If so, try creating a method on the projects model like this:
public function tryFindUOrFail($uuid)
{
return $this->findUOrFail($uuid);
}
Then you would write your show method as:
return responder()->success($request->user()->projects()->tryFindUOrFail($uuid))->respond();
If this doesn't work, you may need to include your method with the $appends array so that it is directly accessible through the relationship.

Delete on Eloquent doesn't delete Laravel 5.4

I am trying to make a delete functionality for pictures which users can upload. The model of the picture class:
class Picture extends Model
{
use SoftDeletes;
/**
* The attributes that are mass assignable.
* #var array
*/
protected $fillable = ['original_file', 'resized_file'];
/**
* The attributes that should be mutated to dates.
* #var array
*/
protected $dates = ['deleted_at'];
/**
* Get the category that owns the question.
*/
public function user()
{
return $this->belongsTo(User::class);
}
Migration:
$table->timestamps();
$table->softDeletes();
The delete function which I have:
public function destroyProgress(Picture $progress){
$progress->delete();
dd($progress);
return view('client.home.profile', ['user' => Auth::user()]);
}
This code is executed and stoped at the dd($progress);. I would expect that this would return null because the $progress has been deleted. But this still returns an instance! Could someone please explain to me what I am doing wrong because I am lost for words.
Hard to explain, the object $progress created by dependency injection is not actually a model instance. Therefore, the delete event will not be fired.
You should use delete method on a model instance:
$picture = App\Picture::find(1);
$picture->delete();

Laravel Model accessing a value of an instance of its self

I've got a model and the model its self could be linked to multiple other databases but only one at a time.
Instead of having a eloquent method for all the possible databases; it could have one that will use a variable from the self instance to choose the database and return just that.
It will save alot of work, as returning each one and testing to see if there are any results is cumbersome.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Feature extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'companies';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'db_name',
'enabled',
];
/**
* Uses the its own database name to determine which input to return.
*/
public function inputs() {
// if this->hidden->db_name == 'input type 1'
// return $this->HasMany(InputType1::class);
.... and so on
} // end function inputs
}
This is definitely a strange behaviour but I think you can achieve what you are looking for like so :
//in your model
public function inputs()
{
switch ($this->attributes['db_name']) {
case : 'input type 1':
return $this->hasMany(InputType1::class);
case : //some other database name
return //another relation
}
}
Expanding on shempognon answer, what I actually got to work was
switch($this->db_name) {
case 'Input_Timesheet':
return $this->hasMany(Input_type1::class);
}

Resources