Call to undefined method App\Models\BrandCodeModell::fromRawAttributes() in Laravel - php

I have a model called BrandCodeModell :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BrandCodeModell extends Model
{
use HasFactory;
public function brand()
{
return $this->belongsTo(Brand::class, 'brand_id', 'id');
}
public function modell()
{
return $this->belongsTo(Modell::class, 'modell_id', 'id');
}
public function codeModell()
{
return $this->belongsTo(CodeModell::class, 'code_id', 'id');
}
}
And this is Modell relation with Brand Model :
public function modells()
{
return $this->belongsToMany(Modell::class)->using(BrandCodeModell::class)
->withPivot('code_id');
}
When I try too add new modell to database I get this error :
BadMethodCallException
Call to undefined method App\Models\BrandCodeModell::fromRawAttributes()
Here is my controller to save modell to database :
$brand = Brand::where('id', $id)->first();
$brand->modells()->detach();
$modells = collect($request['modells']);
$modells->each(function ($item) use ($brand) {
if (is_null($item['name'])) return;
$mod = Modell::firstOrCreate([
'name' => $item['name'],
'sort' => $item['sort']
]);
$mod_code = $mod->codeModell()->firstOrCreate([
'name' => $item['code']
]);
$brand->modells()->attach($mod->id, [
'code_id' => $mod_code->id
]);
});
In this code, Modell::firstOrCreate and $mod_code = $mod->codeModell()->firstOrCreate will be create successfully but this part of code $brand->modells()->attach($mod->id, ['code_id' => $mod_code->id]); does not work.
Where is the problem ?
Tell me if you need more details

Per the documentation:
Custom many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\Pivot class
So your pivot class should look like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\Pivot;
class BrandCodeModell extends Pivot
{
//
}
However, unless you're adding additional methods on to the pivot class, there's no need to define it; Laravel will automatically use the appropriate pivot table. Likewise there's probably no need for it to import the HasFactory trait, as entries would be automatically created by related model creation.

Related

Laravel 8 – Model instance error - too few arguments to function __construct()

I’m kind of new to Laravel and the whole API architecture, so my question may seem dumb at first.
My basic setup:
Laravel 8;
PHP 8;
routes\api.php
Route::post('/categories/',[ApiCategoriesInsertController::class, 'insertCategories'], function($insertCategoriesResults) {
return response()->json($insertCategoriesResults);
})->name('api.categories.insert');
\app\Http\Controllers\ApiCategoriesInsertController.php (created with php artisan make:controller)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// Custom models.
use App\Models\CategoriesInsert;
class ApiCategoriesInsertController extends Controller
{
private mixed $ciAPI;
public function __construct(Request $req)
{
}
public function insertCategories(Request $req): array
{
$this->ciAPI = new CategoriesInsert(['testing'=>'debug']);
return [‘status’ => ‘OK’];
}
}
\app\Models\CategoriesInsert.php (created with php artisan make:model)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CategoriesInsert extends Model
{
use HasFactory;
public function __construct(array $objParameters)
{
}
}
When I make a post to http://localhost:8000/api/categories, Laravel logs the following error:
local.ERROR: Too few arguments to function App\Models\CategoriesInsert::__construct(), 0 passed in … Too few arguments to function App\\Models\\CategoriesInsert::__construct(), 0 passed in …
Anyone knows what’s wrong or missing in my architecture?
Thanks!
Make your model's constructor compatible with parent.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CategoriesInsert extends Model
{
use HasFactory;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
}
}
Also, notice, that when you call new CategoriesInsert(['testing'=>'debug']), you do not save the data in your database. Use:
$insert = new CategoriesInsert(['testing'=>'debug']);
$insert->save();
Or:
CategoriesInsert::create(['testing'=>'debug']);
you don't need to pass data to model
change your code to bellow code:
public function insertCategories(Request $req): array
{
CategoriesInsert::create(['testing' => 'debug']);
return [‘status’ => ‘OK’];
}
key of passed array is your filed name in database, and value stored data
also you should define fillable parameter in model
protected $fillable = [
'title',
'slug',
'priority',
];

How can I use laravel Auditor in controller

I used laravel Auditor in a model and it works very well as following:
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;
class Contracts extends Model implements Auditable
{
use \OwenIt\Auditing\Auditable;
protected $fillable=['condatereceived'];
public function user()
{
return $this->belongsTo(User::class);
}
}
But I want to used it in the controller as :
public function updatecomplated(Request $request, $id,Contracts $contract ,Auditor $auditor)
{
Contracts::where('id', $id)
->update(['complated' => 50, 'conuploadby' => Auth::id(),'constatus' =>'Need To Active' ]);
if ($audit = $auditor->execute($contract)) {
$auditor->prune($contract);
}
return redirect()->back();
}
The code in controller give me error:
Call to undefined method OwenIt\Auditing\Facades\Auditor::execute()
any ideas to use auditor in the controller, please.
try this package its easy with good documentation
simply add this to your table
$table->auditable();
and this to your model
namespace App;
use Yajra\Auditable\AuditableTrait;
class User extends Model
{
use AuditableTrait;
}
thats it now simply get your auditor by calling
$user->creator // for who create
and
$user->updater //for who update data
for more information click here for check trait
Hope this helps

How to get all data from two related tables in Laravel [one to many]

I am pretty new in Laravel and need write a simple backend API.
I am doing smething wrong and I dont know what, because I get some of data from Suppliers table and empty array payments:[ ].
I am trying to get all data from two related tables - PAYMENTS and SUPPLIERS.
It`s a one to many relation SUPPLIERS_ID in PAYMENTS table is connected with ID in SUPPLIERS. Here I give You a graphic representation:
Here`s my code:
Suppliers.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments');
}
}
Payments.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->hasOne('App\Suppliers');
}
}
PaymentsController.php
use App\Payments;
use App\Suppliers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class PaymentsController extends Controller
{
public function index()
{
$payments = Suppliers::with('payments')->get();
return response($payments, Response::HTTP_OK);
}
}
And i get the following answear:
[{"id":1,"name":"Ekonaft","adress":"33-100 Tarnow ","email":"ekonaft#gmail.com","payments":[]},
{"id":2,"name":"Orlen","adress":"Ares testowy","email":"email#email.pl","payments":[]}]
What I`m doing wrong that I get te empty array payments:[ ] on the end of each object?
Try the inverse relationship on payments
belongsTo = has a foreign key to another table
Quoting an example
Should i use belongsTo or hasOne in Laravel?
This is how you can access suppliers from Payments
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo('App\Suppliers');
}
}
This is payments from suppliers
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments','suppliers_ID','id');
}
}
Also, make sure the id's are visible on the output (if id's are hidden, laravel can't work with the relationship). You can also specify the keys on the relationship if you want to use hasOne
Edit: add the keys names within the relation, your fk naming is in capslock
Change you relations like bel
Suppliers.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany(App\Payments::class, 'suppliers_ID', 'id');
}
}
Payments.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo(App\Suppliers::class, 'suppliers_ID', 'id');
}
}
then try again..... :)
You are getting empty array of payments:[] due to miss-matching table relationship key name.
Please, make few changes in both relational function.
public function payments()
{
//return $this->hasMany('App\Model', 'foreign_key', 'local_key');
return $this->hasMany('App\Payments', 'suppliers_id');
}
public function suppliers()
{
//return $this->belongsTo('App\Model', 'foreign_key', 'other_key');
return $this->belongsTo('App\Suppliers', 'suppliers_id');
}
You can learn more about eloquent relationship directly from Laravel documentation for better understanding. https://laravel.com/docs/5.7/eloquent-relationships#one-to-many
Let me know if you still getting same error.

get data from model with condition laravel 5.7

I have Users_group model in my Laravel project.
Code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function getGroupData()
{
return $this->hasOne('App\Group','id','group_id');
}
}
And when I want to get data from this model I use this my custom method:
$data = App\Users_group ::get();
It's working great
I want to get the data from model with condition not like this:
$data = App\Users_group::where('group_id','>',5)->get();
I need to put the condition inside the model file thats make the model return the data everytime I call User_group::get() return it when condition inside the model.
Thanks!
You can use query scopes to achieve this. Query scopes allow you to add a global constraint to a model.
In your case, you could add the following boot method to your model:
protected static function boot()
{
parent::boot();
static::addGlobalScope('groupOver5', function (Builder $builder) {
$builder->where('group_id', '>', 5);
});
}
try this one in by using scope in model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function scopeGetGroupData($query,$value,$opertor = '>')
{
return $query->where('group_id', $opertor, $value);
}
}
get data in controller like this u can pass also parameter in method
App\Users_group::GetGroupData($value)->get();

Laravel 5 - How do I return a oneToMany relationship?

I'm new to Laravel, and using Laravel 5 i'm having trouble returning an array from my database.
I have several "acts", and each act has many "banners". Whenever I try to get output from my array of banners ( $act->banners->count() ), i find it throws an error because it is null.
Here is the code:
routes.php:
Route::model('banners', 'Banner');
Route::model('acts', 'Act');
// Controller routes
Route::resource('acts', 'sf_ActController');
Route::resource('acts.banners', 'sf_BannerController');
Route::bind('banners', function($value, $route) {
return App\Banner::whereact_id($value)->first();
});
Route::bind('acts', function($value, $route) {
return App\Act::whereact_id($value)->first();
});
Act.php (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Act extends Model
{
protected $table = 'sf_act';
protected $primaryKey = 'act_id';
public function act() {
return $this->hasMany('Banner');
}
}
Banner.php (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Banner extends Model
{
protected $table = 'sf_banner';
protected $primaryKey = 'banner_id';
public function banner() {
return $this->belongsTo('Act' , 'act_id' , 'act_id');
}
}
sf_ActController.php (controller)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Act;
use App\Banner;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Redirect;
class sf_ActController extends Controller
{
public function show(Act $act)
{
//pass object to correct view
return view('pages.acts.show' , compact('act'))->with('banner', Banner::find($act));
}
acts/show.blade.php (view)
<!-- /resources/views/acts/show.blade.php -->
#extends('app')
#section('content')
<h2>{{ $act->act_title }}</h2>
{{ $act->banners->count() }}
at this point I get the following error:
FatalErrorException in a03036ad81fb4e6d90e9fe5e3da62c65 line 7:
Call to a member function count() on null
Why am I not fetching my banner data!? (The title variable in the h2 tags outputs fine, so the db and everything up until that point is working.)Thanks.
You need to specify the complete "route" to the model in the relationships including the namespace:
public function act() {
return $this->hasMany('App\Banner');
}
And the same on belongsTo:
public function banner() {
return $this->belongsTo('App\Act' , 'act_id' , 'act_id');
}
Could be a good idea to include the name of the foreign kay in the hasMany method.
public function act() {
return $this->hasMany('App\Banner', 'act_id');
}
Also possibly you don't need to include the third parameter in the belongs to.
Hope it helps. Also can share with you a link to learn about Laravel step-by-step: Learn Laravel 5.0 => 5.1
You currently have your hasMany relationship setup like this:
public function act() {
return $this->hasMany('Banner');
}
However in your view your calling this relationship:
$act->banners->count()
Shouldn't it be:
$act->act()->count();

Categories