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

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.

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

Laravel excel library prints blank excel file

What's wrong with my code, I tried to export my data table using framework Laravel. The file is downloaded with empty content.
StockModel.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stock extends Model {
protected $table = 'stock_tb';
protected $primaryKey = 'id';
protected $fillable = ['stock_id', 'input_date', 'quantity'];
}
AdminController.php
use Excel;
use App\Stock;
use App\Exports\StockExport;
class adminController extends Controller {
public function __construct() { }
public function printStockReport(){
return Excel::download(new StockExport('07/01/2020'), 'ado.xlsx');
}
StockExport.php
namespace App\Exports;
use App\Stock;
use Maatwebsite\Excel\Concerns\FromQuery;
class StockExport implements FromQuery
{
protected $id;
public function __construct($date_var)
{
$this->date = $date_var;
}
public function query()
{
return Stock::query()->where('input_date', $this->date)->get();
}
}
Router
Route::get('admin/printStockReport', 'adminController#printStockReport');
Fyi: I run the SQL code on my RDBMS with criteria input date 07/01/2020. It returns 129 records.
Thank you
remove ->get() , according to laravel-excel documentation no need to that.

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

Getting no result from table , while fetching data using laravel model

I am trying to execute simple CRUD operation using laravel. but it gives an error code 500 , when I try to fetch data from table either by laravel framework as well as with plain PHP.
Here is my controller class.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\BookModel;
use \DB;
class AdminController extends Controller
{
function getItems()
{
$data = DB::select('select * from book');
$data = BookModel::all();
echo($data);
return compact('data');
}
}
axiom , which is been used. ---> "https://unpkg.com/axios/dist/axios.min.js"
Model Class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BookModel extends Model {
protected $table = "book";
public $timestamps = false;
}
It is returning no result from the table.
It worked after I changed my controller to
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\BookModel;
use \DB;
class AdminController extends Controller
{
function getItems()
{
$data = BookModel::all();
return $data;
}
}
But it was giving null result when I was doing something like below
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\BookModel;
use \DB;
class AdminController extends Controller
{
function getItems()
{
$data = BookModel::all();
return view('admin')->withTasks($data);
}
}
Can someone explain why it was not working earlier?
Anyways , Thanks everyone for your help.
Cheeeeeeeeerrsssss!!!!!!!
You need to add response() to return data without view.
Like below the code returns the JSON data from your BookModel that sometimes we need through the ajax request like axios.
class AdminController extends Controller
{
function getItems()
{
$data = BookModel::all();
return response()->toJson($data);
}
}
With view you can do the following:
class AdminController extends Controller
{
function getItems()
{
$data = BookModel::all();
return view('admin', compact('data'));
}
}
Where you can access the BookModel data through $data variable in your admin.blade.php

Laravel factory not returning correct object data

I've got the following factory in Laravel 5.7, when invoking it nothing is being returned:
<?php
use Faker\Generator as Faker;
use Illuminate\Database\Eloquent\Model;
$factory->define(App\Record::class, function (Faker $faker) {
return [
"name" => $faker->name,
];
});
Whereas my model is:
<?php
namespace App;
use App\Product;
use Illuminate\Database\Eloquent\Model;
class Record extends Model
{
protected $table = "records";
protected $fillable = ["name"];
function __construct()
{
parent::__construct();
}
}
And I'm invoking the factory here:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App;
use App\Product;
use App\Record;
use App\User;
class RecordTest extends TestCase
{
use RefreshDatabase;
use WithoutMiddleware;
/** #test */
public function when_record_page_for_existing_record_is_accessed_then_a_product_is_displayed()
{
//$record = factory(App\Record::class)->make();
$record = factory(App\Record::class)->create();
echo "\n\n$record->name\n\n";
}
}
when printing
$record->name
I'm getting nothing, not null, no empty string, just nothing. What seems to be the problem? If I save whatever is generated by the factory into a variable instead of returning it right away I can see that name is being populated, but after returning it nothing happens, it's gone
This piece of code is the problematic part:
function __construct()
{
parent::__construct();
}
You're not passing the attributes to the parent constructor. Eloquent accepts the model's attributes in the constructor, but your overriding constructor doesn't accept them, nor pass them up to the parent.
Change it to this:
function __construct(array $attributes = [])
{
parent::__construct($attributes);
}
BTW, you're overriding Eloquent's constructor, but you're not doing anything in there. Are you sure you actually want to override it?
By default phpunit won't print your echo.
To print it, please use phpunit -v

Categories