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

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',
];

Related

Too few arguments to function Illuminate\Database\Eloquent\Model::created(), 0 passed (CrudPanel)

I updated a backpack project from backpack 4.0 to 4.1 and followed the upgrade guide that is provided on the backpack site. Laravel still runs on 6.x and has not been upgraded lately.
The list and /edit update views are working as intended. Only when trying to open a show view (happens on all models), then the following error occurs:
Too few arguments to function Illuminate\Database\Eloquent\Model::created(), 0 passed in /var/www/vendor/backpack/crud/src/app/Library/CrudPanel/CrudPanel.php on line 330 and exactly 1 expected
I tried to follow the stack trace but I can't find the source that throws the error. I also tried to remove all the methods from one model and just keep construct() and setup() and even then the errors is still thrown.
Edit: The error occurs for all models, this is the code of one random model.
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Vereine extends KVUser
{
}
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class KVUser extends Model
{
use CrudTrait;
use SoftDeletes;
protected $table = 'user';
public $incrementing = true;
/*
|--------------------------------------------------------------------------
| GLOBAL VARIABLES
|--------------------------------------------------------------------------
*/
protected $guarded = [];
public function __construct(array $attributes = [])
{
$this->creating([$this, 'onCreating']);
$this->updating([$this, 'onUpdating']);
parent::__construct($attributes);
}
public static function deleting($callback)
{
parent::deleting($callback);
$callback->update(['deleted' => 1]);
}
public function onCreating(\App\Models\KVUser $row)
{
// Placeholder for catching any exceptions
if (!\Auth::user()->id) {
return false;
}
$row->setAttribute('created_id', \Auth::user()->id);
}
public function onUpdating(\App\Models\KVUser $row)
{
// Placeholder for catching any exceptions
if (!\Auth::user()->id) {
return false;
}
$row->setAttribute('updated_id', \Auth::user()->id);
}
}
namespace App\Http\Controllers\Admin;
use App\Http\Requests\VereineRequest;
use App\Models\Vereine;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class VereineCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
public function __construct()
{
parent::__construct();
}
public function setup()
{
$this->crud->setModel('App\Models\Vereine');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/vereine');
$this->crud->setEntityNameStrings('Verein', 'Vereine');
$this->crud->setListView('vendor/backpack/crud/vereine/vereine_list');
$this->crud->setShowView('vendor/backpack/crud/vereine/vereine_show');
}
}
Screenshot Error Message
I would really appreciate some help - thank you!
For clearly to identify error you should attached image. Thanks

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

PHP Laravel save model properties via constructor

I am trying to simply save a model to the database via a controller without setting the fields directly but instead having them set in the constructor of said object.
Here is the class handling the logic. If the commented out line
//$todoItem->item = $todo; is uncommented, it works fine and saves whatever is entered in $todo in the database. However, I would like to set that value in the constructor of the task object and not need to manually specify it. I found this question: Laravel with Eloquent doesn't save model properties on database suggesting I could set the property as protected and have it work, but that still does not.
NewTodo.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class NewTodo extends Controller
{
public function saveTodoItem(Request $request)
{
$todo = $request->input('content');
$todoItem = new \App\Task($todo);
//$todoItem->item = $todo;
$todoItem->save();
return view('testview', ['name' => $todoItem->getItem()]);
}
}
Task.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $item = null;
function __construct($newItem)
{
$this->item = $newItem;
}
function getItem()
{
return $this->item;
}
}
Summary, database entry being stored as blank unless $todo->item is manually set when from what I can $todo->item is being set in the constructor.
You don't need to specify these in the constructor. You can use Mass Assignment
Model:
class Task extends Model
{
protected $fillable = ['item'];
}
Controller:
class NewTodo extends Controller
{
public function saveTodoItem(Request $request)
{
$todo = $request->input('content');
$todoItem = new \App\Task::create(['item' => $todo]);
return view('testview', ['name' => $todoItem->getItem()]);
}
}

Laravel 5.4 incompatiblity - share() or set-> error?

After trying to debug for a long time I run into an error of where I a variable does not seem to retrieve a value from the database.
Here is the code I use:
use App\Setting;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use View;
use DB;
class SettingsServiceProvider extends ServiceProvider
{
public function boot()
{
if(\DB::connection()->getDatabaseName() && Schema::hasTable('settings') && \DB::table('settings')->count()){
$setting = new Setting;
config()->set('website_desc', $setting->gets('general')->website_desc);
config()->set('website_keywords', $setting->gets('general')->website_keywords);
}
}
public function register()
{
// this approach worked before updating to 5.4
view()->share('website_desc',config('website_desc'));
view()->share('website_keywords',config('website_keywords'));
//does not work either
// View::share(['website_desc' => 'values', 'website_keywords' => 'values']);
}
}
my App/setting.php looks like this
namespace App;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = ['name','attributes'];
public function gets($name){
$attributes = $this->where('name',$name)->value('attributes');
if($attributes){
return json_decode($attributes);
}
return false;
}
}
Can anyone see anything that became incompatible?
This is the a database entry of the table settings and the column "attributes":
{"website_name":"name","website_title":"title","website_desc":"description","website_keywords":"keywords","website_footer_text":"footer"}
I am kind of at my wits end.

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