Null values instead of an Value in CodeIgniter - php

I have this code that is returning a NULL instead of a value. Here is my Controller with the name Agents, this code runs on the Admin side but when I used the code for Agents user levels it's returning NULL:
<?php namespace App\Controllers;
use App\Models\ClientModel;
class Agent extends BaseController{
public $modelClients;
public function __construct(){
$this->modelClients = new ClientModel();
}
function getClientsToAgent($id){
$data = ([
"title" => "Lead Generation",
"client" => $this->modelClients->where("clientsId", $id)->first(),
"tasks" => $this->modelTasks->orderby("taskId", "ASC")->findAll()
]);
echo view('agentTemplate/header',$data);
echo view('agents/loadLeadGenView');
echo view('agentTemplate/footer');
}
}
and on my view named loadLeadGenView:
<?php
var_dump($client);
?>
here's my Model name ClientModel:
<?php namespace App\Models;
use CodeIgniter\Model;
class ClientModel extends Model{
protected $table = "tblclients";
protected $primaryKey = "clientsId";
protected $returnType = 'array';
protected $allowedFields = ["clientsId","clientsFirstname","clientsMiddlename", "clientsLastname","clientsBusinessName","clientsCampaignGoals","clientsDateStarted","clientsJointVenture","clientsEmailAddress"];
}
Another this on my Routes.php:
$routes->get('agents/getClientsToAgent/(:num)', 'Agents::getClientsToAgent/($1)');
that is why I'm wondering. why it's returning NULL instead of a value?

fix your route, remove brackets around $1
$routes->get('agents/getClientsToAgent/(:num)', 'Agents::getClientsToAgent/$1');
https://codeigniter4.github.io/CodeIgniter4/incoming/routing.html#examples

Related

Class "App\Models\User" not found in CodeIgniter 4

I'm new to CodeIgniter 4 but I have previously used Laravel - so I do know what I'm doing for the most part. I'm trying to build a simple CRUD app on CI4 and in my UserController, it keeps saying that App\Models\User is not found. And as a result - anything I get from the model class, is NULL.
Here's my Model & Controller code:
<?php
namespace App\Models;
use CodeIgniter\Model;
class User extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email'];
public function getUsers()
{
return $this->findAll();
}
}
UserController.php:
<?php
namespace App\Controllers;
use App\Models\User;
class UserController extends BaseController
{
public function index()
{
$model = model(User::class);
$data['users'] = $model->getUsers();
return view('user_view', $data);
}
public function create()
{
return view('add_user');
}
public function store()
{
$model = model(User::class);
$data = [
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email')
];
$model->insert($data);
return $this->response->redirect(site_url('users-list'));
}
}
The error is in the index() method. If I use the $model = model() approach - I get "getUsers() is NULL" error. If I use the $model = new User(); approach - I simply get "Model not Found". And as you can see - I already have included the App\Models\User in the header.
What am I missing?

Appending an attribute to a Laravel 7.9.2 model?

Here is my code:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Unit_Live extends Model
{
protected $table = 'live_data_units';
public function getUnitNameAttribute()
{
return "{$this->unitName}";
}
protected $appends = ['unit_name'];
}
Output:
If I change the $appends array, I can see default:
protected $appends = ['unit_name' => 'default'];
The expected output should be unit_a. unitName is a column in my table, value is shown under #attributes in image 1.
Docs:
https://laravel.com/docs/7.x/eloquent-serialization#appending-values-to-json

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 - nested relationship shows null

I have a tw-tier nested hasOne relationship and the final relationship appears to be giving null values.
My JobApplication relationship has the following:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class JobApplication extends Model
{
protected $table = 'job_applications';
protected $primaryKey = 'job_application_id';
public function jobrequest()
{
return $this->hasOne('App\Model\JobRequest', 'job_request_id', 'job_request_id');
}
}
My JobRequest Model has the following:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class JobRequest extends Model
{
protected $table = 'job_requests';
protected $primaryKey = 'job_request_id';
public function jobgroup()
{
return $this->hasOne('App\Model\JobGroup', 'job_group_code', 'job_group_code');
}
public function jobapplication()
{
return $this->belongsTo('App\Model\JobApplication', 'job_request_id');
}
}
And my JobGroup has the following:
<?php
namespace App\Model;
use Carbon;
use Illuminate\Database\Eloquent\Model;
class JobGroup extends Model
{
protected $table = 'job_groups';
protected $primaryKey = 'job_group_code';
public function jobrequest()
{
return $this->belongsTo('App\Model\JobRequest', 'job_group_code');
}
}
I access them in my controller like so:
$job_applications = JobApplication::with(['jobrequest', 'jobrequest.jobgroup'])
->where('user_id', Auth::id())
->first();
It queries right on the Debugbar (and yes the query for job_groups gives out data), but when I dumped $job_applications, jobgroup shows null
Dont need to eager load it. I can access it like so
$job_applications = JobApplication::with('jobrequest')->where('user_id', Auth::id())->first();
dd($job_applications->jobrequest->jobgroup);

Eloquent Relationship

Why am I getting this error for such a simple relationship query?
Call to undefined method Illuminate\Database\Query\Builder::country()
I just want to get a list of lookup values from my lookup table called pc_country. I have even included the namespaces!
Controller;
$tableName = $postcode_tablename->dataset; //eg 201502_postcode
$country = PostcodeExtract::fromTable($tableName)
->country() //this is generating the error!
->distinct()
->select('description')
->get();
var_dump($country);
exit;
Country Model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model {
protected $connection = 'postcodes';
public $table = 'pc_country';
protected $fillable = ['description', 'country_id', 'code'];
public function postcodeExtract()
{
return $this->hasMany('App\Models\PostcodeExtract');
}
}
PostCode Extract Model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PostcodeExtract extends Model {
protected $connection = 'postcodes';
protected $fillable = ['country'];
public function scopeFromTable($query, $tableName)
{
return $query->from($tableName);
}
public function country()
{
return $this->belongsTo('App\Model\Country');
}
}
My 201502_postcode table has a country_id and my pc_country table has a id field for it to do the lookup on. Is that correct? I don't see the problem...
You used fromTable method(scope) it returns eloquent query builder so your relations wont be available. Consider same code without calling that method.
If you want to change table of model create an instance and then call setTable method on the created instance then use your instance to query
$instance = new PostCodeExtract();
$instance->setTable ("table");
$country = $instance->country()->........
Sorry im on mobile couldn't provide good example code but you can achieve it with this method

Categories