Call to undefined method CodeIgniter\Database\MySQLi\Connection::like() - php

I have i like query in my model but it doesn't work
Model:
<?php namespace App\Models;
use CodeIgniter\Model;
class SearchModel extends Model
{
protected $table = 'sport_tbl';
protected $primaryKey = 'id';
protected $returnType = 'array';
public function search($word)
{
$this->db->like('title', $word);
$res = $this->db->get('sport_tbl')->result_array();
return $res;
}
}
Controller:
<?php namespace App\Controllers\api;
use App\Controllers\BaseController;
use App\Models\SearchModel;
class Search extends BaseController
{
public function index()
{
$searchModel = new SearchModel();
$data['allnews'] = $searchModel->search('test');
return view('welcome_message', $data);
}
}
And this is error:
Call to undefined method CodeIgniter\Database\MySQLi\Connection::like()

You are basically using the old query builder style from Codeigniter 3 instead of Codeigniter 4.
In Codeigniter 4 your code should look like this.
<?php namespace App\Models;
use CodeIgniter\Model;
class SearchModel extends Model
{
protected $table = 'sport_tbl';
protected $primaryKey = 'id';
protected $returnType = 'array';
public function search($word)
{
$db = \Config\Database::connect();
$builder = $db->table('sport_tbl');
$builder->like('title', $word);
return $builder->get()->getResultArray();
}
}
In this case your controller should be just the same.
However there's another way of doing the same without creating a new database object and using the same one that is being automatically created for you.
<?php namespace App\Models;
use CodeIgniter\Model;
class SearchModel extends Model
{
protected $table = 'sport_tbl';
protected $primaryKey = 'id';
protected $returnType = 'array';
public function search($word)
{
$this->like('title', $word);
return $builder->get()->getResultArray();
}
}
In this case your controller should be a bit different:
<?php namespace App\Controllers\api;
use App\Controllers\BaseController;
use App\Models\SearchModel;
class Search extends BaseController
{
public function index()
{
$searchModel = new SearchModel();
$data['allnews'] = $searchModel->search('test')->getAll();
return view('welcome_message', $data);
}
}
The second version of the code is actually better because that way your can have as many functions you want in your model and then just call them in a chain statement always returning $this.

Related

Dynamic type-hint in Laravel for Form Request

I've created a Base Controller and I want to dynamically type-hint the store method to use the proper Form Request class. How can I do that?
Here's my base controller (simplified):
class BaseController extends Controller
{
protected $baseClass;
protected $baseResourceClass;
protected $baseStoreRequestClass;
public function index()
{
$items = $baseClass::paginate(10);
return $baseResourceClass::collection($items);
}
// the $baseStoreRequestClass doesn't work, and that's what I'm trying to figure it out
public function store(**$baseStoreRequestClass** $request)
{
$validatedFields = $request->validated();
$newItem = $baseClass::create($validatedFields);
return new $baseResourceClass($newItem);
}
}
Then, from the controller that will extend, I would have just to declare the 3 variables. Example:
class UserController extends BaseController
{
protected $baseClass = '\App\User';
protected $baseResourceClass = '\App\Http\Resources\UserResource';
protected $baseStoreRequestClass = '\App\Http\Requests\StoreUser';
}
class ProductController extends BaseController
{
protected $baseClass = '\App\Product';
protected $baseResourceClass = '\App\Http\Resources\roductResource';
protected $baseStoreRequestClass = '\App\Http\Requests\StoreProduct';
}
How could I make the $baseStoreRequestClass works?
You can't specify a dynamic type as a function parameter. It's just not valid PHP syntax. Here's what I suggest. Your base class would be the boilerplate:
class BaseController extends Controller
{
protected $baseClass;
protected $baseResourceClass;
public function index()
{
$items = $baseClass::paginate(10);
return $baseResourceClass::collection($items);
}
public function store(FormRequest $request) // Or other base request object you might create
{
$validatedFields = $request->validated();
$newItem = $baseClass::create($validatedFields);
return new $baseResourceClass($newItem);
}
}
Then each subclassed controller would need an explicit request type:
class UserController extends BaseController
{
protected $baseClass = '\App\User';
protected $baseResourceClass = '\App\Http\Resources\UserResource';
public function store(StoreUser $request) {
return parent::store($request);
}
}

Class 'App\Model\Users' not found in Codeigniter4

I am working with the latest version of codeigniter framework. Something is wrong with my code, it gives me an error like:
Class 'App\Model\Users' not found
Controller
Filename: Auth.php
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use App\Model\Users as CodeIgniterUsers;
class Auth extends ResourceController
{
public function login()
{
$model = new CodeIgniterUsers();
var_dump($model);
}
public function register()
{ }
}
Model
File name: Users.php
<?php
namespace App\Model;
use CodeIgniter\Model;
class Users extends Model
{
protected $db;
protected $table = 'user';
protected $returnType = 'array';
protected $allowedFields = ['name', 'email', 'password'];
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
If you haven't change your directory names in app, you need to change namespaces from App\Model\Users (without "s" at the end) to App\Model\User.
Namespaces should follow directory structure, unless you change (or extends) CI4's core classes or at least app/Config/Autoload.php
Extends your model with CI_Model for it will be recognized .
class Auth_model extends CI_Model {
//you can always put function construct
public function __construct (){
parent::__construct ();
}
}
In controller :
class User extends CI_Controller {
public function __construct () {
parent:: __construct();
//you can load here the model that you will just often so will load it everytime to use it in a function
$this->load->auth_model('model-name(exam- public function test_uer()');
}
}

Laravel eloquent with() returns null

namespace App;
use App\Model\Service\Area;
use App\Model\Bid\Service;
use Illuminate\Database\Eloquent\Model;
class Bid extends Model
{
protected $table = "bid";
protected $primaryKey = 'bid_id';
protected $guarded = [];
protected $with = ['services'];
public function services() {
return $this->hasMany(Service::class, 'bid_id');
}
public function area() {
return $this->belongsTo(Area::class, 'area_id', 'area_id');
}
}
namespace App\Model\Service;
use Illuminate\Database\Eloquent\Model;
class Area extends Model
{
protected $table = "location_area";
protected $primaryKey = 'area_id';
protected $guarded = [];
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
}
Area table Migration and data
Bid table Migration and data
When I am trying to access
Bid::with('area')->find(BID_ID);
It is returning Null
Query is firing wrong:
"select * from `location_area` where `location_area`.`area_id` in (0)"
But if I am doing like:
$bid = Bid::find(BID_ID);
dd($bid->area);
It returns Area table values. What is going wrong? Please Help me. I
am having this problem for a long time. Thank You in advance :)
you must be declared a method in your MID model
public function area()
{
return $this->belongsTo(Area::class, 'bid');
}
something like this
after this, you access area in with()
Bid::with('area')->find(BID_ID);
Change this function in your Bid model :
public function area() {
return $this->belongsTo(Area::class, 'area_id');
}

Laravel 5.4 call a model function on an instance returned by another laravel model function

I have 3 tables and the corresponding models which are connected as shown below:
Telephones.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Telephones extends Model {
protected $table = 'telephones';
protected $primaryKey = 'telephone_id';
public function UserTelephone() {
return $this->hasOne('App\Models\Users','user_id','user_id');
}
}
Addresses.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Addresses extends Model {
protected $table = 'addresses';
protected $primaryKey = 'address_id';
public function UserAddress() {
return $this ->hasOne('App\Models\Users','address_id','address_id');
}
}
Users.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model {
protected $table = 'users';
protected $primaryKey = 'user_id';
}
In my view I want to connect user's telephone with user's address so I do the following:
<?php $user_telephone = $telephone->UserTelephone()->first();
$address = $user_telephone->UserAddress()->first();
?>
but it fails with error:
BadMethodCallException in Builder.php line xxxx:
Call to undefined method
Illuminate\Database\Query\Builder::UserAddress()
Any ideas how I could solve it?
On your telephones and address model, I would say to use Belongs to instead of Has One.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Users;
class Addresses extends Model {
protected $table = 'addresses';
protected $primaryKey = 'address_id';
public function UserAddress() {
return $this->belongsTo(Users::class);
}
}
class Telephones extends Model {
protected $table = 'telephones';
protected $primaryKey = 'telephone_id';
public function UserTelephone() {
return $this->belongsTo(Users::class);
}
}
From https://laravel.com/docs/5.4/eloquent-relationships#one-to-one
Defining The Inverse Of The Relationship
The reason your case doesn't work on user address is because you may not have the address_id field on your user model.
return $this->hasOne('App\Models\Users','id','user_id');
You are creating a relationship so therefore you need to let it know how they're connected. I would suggest read more about relationships: https://laravel.com/docs/5.4/eloquent-relationships
Try to call your model functions like this :
$user_telephone = $telephone->UserTelephone;
$address = $user_telephone->UserAddress;
this will be okay only if $telephone its a Telephone model
EDIT
Your error is in the place you declare you model relationship
change this:
return $this->hasOne('App\Models\Users','user_id','user_id');
to this
return $this->hasOne(Users::class,'user_id','user_id');
and the same with your other function
*make sure what is your models name.. most of the times is User
Telephone Model :
public function UserTelephone() {
return $this->belongsTo('App\Models\Users','user_id','user_id');
}
Address Model :
public function UserAddress() {
return $this->belongsTo('App\Models\Users','address_id','address_id');
}
Controller :
$telephone =Telephone::find(1); //get first telephone
$user_telephone = $telephone->UserTelephone; // get User
$address = $user_telephoneObject->UserAddress; //get Address Of the user
Finally I managed to solve it, the issue was that I was trying to call a model's function on the wrong object.
My goal was to get the address when user was known. To be more specific I had the following relationship: telephone->user->address. As you could see to the initial posted code, I declared 2 functions, UserTelephone and UserAddress. Then I called UserTelephone on a telephone object and UserAddress on a recipient object. This was the reason that my code failed. Had to create a new function on Users model to be able to get the address when user was know. Working code posted below:
Telephones.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Telephones extends Model {
protected $table = 'telephones';
protected $primaryKey = 'telephone_id';
public function UserTelephone() {
return $this->belongsTo('App\Models\Users','user_id','user_id');
}
}
Addresses.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Addresses extends Model {
protected $table = 'addresses';
protected $primaryKey = 'address_id';
public function UserAddress() {
return $this ->belongsTo('App\Models\Users','address_id','address_id');
}
}
Users.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model {
protected $table = 'users';
protected $primaryKey = 'user_id';
public function Address() {
return $this->hasOne('App\Models\Addresses','address_id','address_id');
}
}
In my view:
<?php $address = $telephone->UserTelephone->Address()->first();?>

Laravel 4 to 5 upgrade: Eloquent relationships not working

I'm trying to upgrade my existing Laravel 4 project to version 5.
Model relationships are not working fine. Every time I try to access a property from property_price table it returns null.
My models are located in App/Models directory.
Property Model
class Property extends \Eloquent {
protected $guarded = array('id');
protected $table = 'properties';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $softDelete = true;
public function propertyPrice()
{
return $this->hasOne('PropertyPrice','pid');
}
}
PropertyPrice Model
class PropertyPrice extends \Eloquent {
protected $guarded = array('id');
protected $table = 'property_pricing';
public function property()
{
return $this->belongsTo('Property');
}
}
Usage
$property = Property::find($id);
$price = $property->property_price->per_night_price; // null
The code is working fine in Laravel 4.
You need to specify namespace in relation methods.
If you're using php5.5+ then use ::class constant, otherwise string literal:
// App\Models\PropertyClass
public function property()
{
return $this->belongsTo(Property::class);
// return $this->belongsTo('App\Models\Property');
}
// App\Models\Property model
public function propertyPrice()
{
return $this->hasOne(PropertyPrice::class,'pid');
// return $this->hasOne('App\Models\PropertyPrice','pid');
}
Of course you need to namespace the models accordingly:
// PSR-4 autoloading
app/Models/Property.php -> namespace App\Models; class Property

Categories