Model class can not run in Codeigniter 4 - codeigniter

I am creating model and I want to access method in controller, but query gives error:
mysqli_sql_exception #1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':0: AND 1 = :1: LIMIT 1' at line 3
What is mistake in my code?
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model{
protected $table='users';
protected $allowedFields=['employee_name','employee_email','employee_phone','employee_dept','employee_grade','employee_password','employee_cpassword','emp_image'];
public $db;
public function __construct()
{
$this->db = \Config\Database::connect();
}
public function getEmployee($id=false)
{
if($id==null)
{
return $this->findAll();
}
return $this->where(['id',$id])->first();
}
}
Controller:
public function edit($id) {
$model = model(UserModel::class);
$data['emp']=$model->getEmployee($id);
print_r($data['emp']);
exit();
}
Routes:
$routes->get('/edit/(:num)','Admin::edit/$1');

Change from:
return $this->where(['id',$id])->first();
to
return $this->where('id', $id)->first();
or
return $this->where(['id' => $id])->first();
Take a look at the document here

Related

Laravel : need a controller to be called on all views

What i want is to load a sidebar with a controller inside, on my layouts/app.blade.php.
i have read that the best way is to load it on AppServiceProvider, so i tried this :
View::composer('layouts.app', function ($view) {
$data = \App\Http\Controllers\DeliveryController::index();
$view::share('Delivery',$data);
});
That works, but the DeliveryController::index gave me this error :
Using $this when not in object context
The way that really works is to forget the AppServiceProviers and to do it on every views controller like this :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Management\DeliveryManagement;
class WelcomeController extends Controller
{
protected $deliveryManagement;
protected $nbLastsDelivery = 3;
public function __construct(DeliveryManagement $deliveryManagement)
{
// $this->middleware('auth');
$this->deliveryManagement = $deliveryManagement;
}
public function index()
{
$deliveries = $this->deliveryManagement->getLasts($this->nbLastsDelivery);
return view ('welcome', compact('deliveries'));
}
}
Unfortunately i think AppServiceProviers is a better way, right ?
If someone can help me i would be very grateful !
EDIT :
I add code of DeliveryController and DeliveryManagement :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\DeliveryRequest;
use App\Management\DeliveryManagement;
class DeliveryController extends Controller
{
protected $deliveryManagement;
protected $nbLasts = 3;
public function __construct(DeliveryManagement $deliveryManagement)
{
$this->deliveryManagement=$deliveryManagement;
}
public function index()
{
$deliveries=$this->deliveryManagement->getLasts($this->nbLasts);
return $deliveries;
}
and :
<?php
namespace App\Management;
use App\Models\Delivery;
class DeliveryManagement extends ResourceManagement
{
protected $delivery;
public function __construct (Delivery $delivery)
{
$this->model=$delivery;
}
public function getLasts($limit)
{
$req = $this->model->orderBy('deliveries.id', 'desc')->skip(0)->take($limit)->get();
$i=0; $render = array();
foreach($req as $delivery)
{
if($i=0)
$render = [$delivery, 'latest'];
else
$render = [$delivery, 'older'];
$i++;
}
return $render;
}
}

Parse error: syntax error, unexpected '__construct' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

I have this problem. When I click on add to cart button there is an error:
Parse error: syntax error, unexpected '__construct' (T_STRING),
expecting function (T_FUNCTION) or const (T_CONST)
I'm new in Laravel and I really have no idea what I have to do,
This is my code on button add to Cart:
Add to cart
This is my route:
Route::get('add-to-cart/{id}', 'WebController#addToCart')->name('get.addToCart');
This I have in webcontroller:
public function addToCart(Request $request, $id){
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product,$product->id);
$request->session()->put('cart',$cart);
dd($request->session()->get('cart'));
return redirect()->route(get.product);
}
And this is my cart.php
<?php
namespace App;
class Cart{
public $items=null;
public __construct($oldCart){
if($oldCart){
this->$items=$oldCart->items;
}
}
public function add($item,$id){
$storedItem= ['name'=>$item];
if(this-> $items)
{
if(array_key_exists($id, this->$items)){
$storedItem=this->$items[$id];
}
}
this->$items[$id]=$storedItem;
}
}
Your __construct needs to have the word function in front of it, or better yet public function
Change the line to:
public function __construct($oldCart)
Read out here: Line no 8
there is missing function keyword before __construct
<?php
namespace App;
class Cart{
public $items=null;
public function __construct($oldCart){
if($oldCart){
$this->items=$oldCart->items;
}
}
public function add($item,$id){
$storedItem= ['name'=>$item];
if($this->items)
{
if(array_key_exists($id, $this->items)){
$storedItem=$this->items[$id];
}
}
$this->items[$id]=$storedItem;
}
}
this->$items[$id]=$storedItem;
See, this is a keyword and is $this, and when accessing variables through this no need to do the $ sign on the accessed variable (in this case items), so it should always be:
$this->items[$id] = $storedItem;
And please indent and organise your code better, this is pretty chaotic and there is probably more than one error.
You should try this:
<?php
namespace App;
class Cart{
public $items=null;
public function __construct($oldCart){
if($oldCart){
this->$items=$oldCart->items;
}
}
public function add($item,$id){
$storedItem= ['name'=>$item];
if(this-> $items)
{if(array_key_exists($id, this->$items)){
$storedItem=this->$items[$id];
}
}
this->$items[$id]=$storedItem;
}
}

Get onlyTrashed() does not exist in query builder

I am trying to get trashed rows from table messages:
public function trash() {
return $this->onlyTrashed()
->where('user_id', '=', $this->_u)
->orWhere('receiver', '=', $this->_u)
->orderBy('deleted_at', 'desc')->get();
}
I get this error:
Method Illuminate\Database\Query\Builder::onlyTrashed does not exist.
I checked up Builder and SoftDeletes files for onlyTrashed method and it does not exist, how can I look up to trashed messages from message table?
The only way I think about is to create method that doesn't return messages where delete_at is not null and for trashed to return only those where it is not null. But I am still wondering why this doesn't work since it is in documentation at this url:
https://laravel.com/docs/5.6/eloquent#soft-deleting
MORE INFO
Yes it is inside model and yes I added use SoftDeletes:
use Illuminate\Database\Eloquent\SoftDeletes; - on top
use SoftDeletes; after opening the class
Let me paste entire model here:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
class Messages extends Model
{
use SoftDeletes;
protected $fillable = [
'user_id', 'subject', 'text', 'receiver'
];
public $_u;
protected $dates = ['deleted_at'];
public function __construct() {
$this->_u = auth()->user()->user_id; //or some id as string
}
public function trash() {
return $this->onlyTrashed()
->where('user_id', '=', $this->_u)
->orWhere('receiver', '=', $this->_u)
->orderBy('deleted_at', 'desc')->get();
}
public static function trashed() {
return self::onlyTrashed();
}
}
And controller has:
public function __construct() {
$this->middleware('auth');
}
public function index($field = 'trash') {
if ($field !== "new") {
$messages = (new Msg)->$field();
$user = auth()->user();
return view('pages.messages', compact('messages', 'user'));
}
return view('pages.messages.new', compact('messages', 'user'));
}
I tried calling static as well and I tried doing it from tinker and still keep getting:
onlyTrashed() doesn not exist
You have to call the parent constructor:
public function __construct() {
parent::__construct();
$this->_u = auth()->user()->user_id;
}
I think what you want is to define the trash method static:
public static function trash() {
return self::onlyTrashed()
->where('user_id', '=', $this->_u)
->orWhere('receiver', '=', $this->_u)
->orderBy('deleted_at', 'desc')->get();
}
Then call this function by:
$messages = Messages::trash();
This should work
# YourModelController.php
/**
* Show only trashed
*
* #return \Illuminate\Http\Response
*/
public function trashed()
{
...
$trashed = YourModel::onlyTrashed()->get();
...
}
I have researched a little further and I got this:
From https://laravel.com/api/5.6/Illuminate/Database/Eloquent.html
I should have
SoftDeletesTrait
but I have
SoftDeletes
. In softdeletestrait we have onlyTrashed method but in SoftDeletes we do not.
So I copied that method from this page:
https://github.com/laravel/framework/blob/7d9e7068c49f945385673014d4cba4de28accd5e/src/Illuminate/Database/Eloquent/SoftDeletingTrait.php#L119
And added it to SoftDeletes class, now it works like it should. I haven't find why it doesn't exist inside SoftDeletes class so if anyone find out let us know!

Need to set a 1 to many relationship in the same table in Laravel 4

I have the following models
Category:
<?php
class Category extends Eloquent {
protected $table = "category";
protected $fillable = array('title','parent','metatit','metadsc','metake','metaurl','image');
public function categoryitems(){
return $this->hasMany('CategoryItem','catid');
}
public function parent(){
return $this->hasMany('category','parent');
}
public function child(){
return $this->belongsTo('Category','parent');
}
}
Need to set a 1 to many relationship in the category table
Ex category "cities" is a child of category "countries"
the error happen when i try to use the following code
<?php
$parent = Category::where('id','=',$cat->id)->parent;
echo $parent->title;
?>
The error :
ErrorException (E_UNKNOWN)
Undefined property: Illuminate\Database\Eloquent\Builder::$parent (View: /var/www/phpWithAngulerJS/app/views/admin/category-edit.blade.php)
First off, fix the relations as follows:
public function children() {
return $this->hasMany('Category','parent');
}
public function parent() {
return $this->belongsTo('Category','parent');
}
And your query needs to be executed first:
$parent = Category::where('id','=',$cat->id)->first()->parent;
// btw since you have $cat, you probably can do simply:
$cat->parent;
echo $parent->title;

error for inserting data in database in view in joomla

I want to insert a data in database but it show error
Fatal error: Call to a member function getform() on a non-object in
\components\com_enquiry\views\form\view.html.php
on line 9
my code is:
enqiry.php:
public function getform($data)
{
$db=JFactory::getDbo();
$db=$this->getDbo();
$query=$db->getQuery(true);
$reg=new stdClass();
$reg->name=$data['name'];
$reg->email=$data['email'];
$reg->phone=$data['phone'];
$reg->comments=$data['comments'];
$reg=$db->insertObject('#__enquiry',$reg);
}
and view.html.php:
public function display()
{
$this->msg = 'enquiry form';
$model=$this->getModel();
$data =$model->getform();
$this->assignRef('data', $data );
parent::display();
parent::display();
}
controller:
class enquiryController extends JControllerLegacy
{
public function display()
{
$vname=JRequest::getCmd('view','form');
JRequest::setVar('view',$vname);
JRequest::setVar('layout','default');
parent::display();
}
public function show()
{
$data['name']=$_POST['name'];
$data['email']=$_POST['email'];
$data['phone']=$_POST['phone'];
$data['comments']=$_POST['comments'];
$sname=JRequest::getCmd('view','thanx');
JRequest::setVar('view',$sname);
print_r($data);
}
}
could someone help me solve this error?
The problem is that your model is not loaded by the line:
$model=$this->getModel();
This either means that your model in enquiry.php is not named correctly
ComponentNameModelEnquiry
or that your view is not named enquiry.
You can try to specify which model you want, like
$model = $this->getModel('enquiry');

Resources