Codeigniter 4 Call to a member function get() on null - php

i have one project in CI3 and update for CI4
i have problem in my template, i receive Call to a member function get() on null.
my view not working call $this->traducao->get('search_string'); please help-me for update in class and libraries
My Function in Libraries
<?php
namespace App\Libraries;
use Config\Database;
class menus {
public $listMenus;
public $listSeo;
public function __construct(){
$this->set();
}
public function set(){
$db = Database::connect();
$builder = $db->table('menu');
$query = $builder->where("parente", 0)
->where("ativo", 1)
->orderBy('posicao', 'asc')
->get()->getResultArray();
if(is_array($query)){
$menusPai = $query;
}
$query2 = $builder->where("parente > 0")
->where("ativo", 1)
->orderBy('posicao', 'asc')
->get()->getResultArray();
if(is_array($query)){
$menusFilhos = $query2;
}
// $menusFilhos = ($query2->countAllResults() > 0) ? $query2->getResultArray() : false;
$menus = [];
foreach ($menusPai as $key => $value)
{
$this->listSeo[$value['link']]['pagina_titulo'] = $value['pagina_titulo'];
$this->listSeo[$value['link']]['pagina_keywords'] = $value['pagina_keywords'];
$this->listSeo[$value['link']]['pagina_description'] = $value['pagina_description'];
$menus[$value['id']]['filhos'] = [];
$menus[$value['id']]['dados'] = $value;
if ($menusFilhos)
{
foreach ($menusFilhos as $k => $v)
{
if ($v['parente'] == $value['id'])
{
$this->listSeo[$v['link']]['pagina_titulo'] = $v['pagina_titulo'];
$this->listSeo[$v['link']]['pagina_keywords'] = $v['pagina_keywords'];
$this->listSeo[$v['link']]['pagina_description'] = $v['pagina_description'];
$menus[$value['id']]['filhos'][] = $v;
}
}
}
}
$this->listMenus = $menus;
}
public function get(){
return $this->listMenus;
}
public function seo($tag){
$uri = new \CodeIgniter\HTTP\URI();
print_r($uri);
$uri = ($this->CI->uri->uri_string() == '') ? '/' : $this->CI->uri->uri_string();
return $this->listSeo[$uri][$tag];
// return $this->listSeo[$uri][$tag];
}
}
My ControllerBase
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Libraries\My_parser;
use App\Libraries\Preferencia;
use App\Models\index_model;
use App\Libraries\Traducao;
use App\Libraries\Menus;
class BaseController extends Controller
{
protected $helpers = [];
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->_db = \Config\Database::connect();
$this->My_parser = new My_Parser();
$this->_model = new \App\Models\index_model();
$this->traducao = new Traducao();
}
public function output($data, $status){
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(
json_encode(
array(
'status'=> $status,
'response'=> $data
),
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
)
)->_display();
exit;
}
}
And my view
<div class="container">
<h2 class="text-center no-m"><?= $this->traducao->get('HOME_EMPRESAS_PARCEIRAS_TITULO') ?></h2>
and my index.php loading views layout
<?= $this->extend('template/head.php',array('css'=> $css, 'metatags'=> $metatags)) ?>
<?= $this->extend('template/header.php') ?>
<?= $this->extend('template/navbar.php') ?>
<?= $this->section('content')?>
<?= $this->endSection()?>

The short answer is it doesn't exist in the View because you never gave it to the View.
$this->traducao belongs to the Controller. It may have been constructed with the Controller but there's no immediate reason that any View would have access to it (or any data that wasn't passed directly to the View).
All incoming requests should be routed through Controllers; that is their most important purpose. Where is the Controller that's actually handling the request to your index.php file?
Any and all Views should be displayed by a Controller because that is where you have the ability to pass data (i.e. $this->traducao) into the View.
If this is actually CI4 as tagged, then you have a problem with CI3 code still being present as well; for example, $this->output isn't used to return Controller responses in CI4, it's $this->response instead.

Related

Codeigniter 4 pagination on function in model

I'm currently stuck with the built-in pagination of CI4.
I try to paginate the results of a function in my model, which does not work:
My model:
<?php
namespace App\Models;
use CodeIgniter\Model;
class CategoriesModel extends Model
{
protected $table = 'categories';
protected $allowedFields = [];
protected $beforeInsert = ['beforeInsert'];
protected $beforeUpdate = ['beforeUpdate'];
//Kategorie(n) laden
public function getCategories($categoryID = null)
{
$db = \Config\Database::connect();
if (!$categoryID) {
$builder = $db->table('categories');
$query = $builder->get();
$results = $query->getResultArray();
} else {
$builder = $db->table('categories');
$query = $builder->where('categoryID', $categoryID);
$query = $builder->get();
$results = $query->getRow();
}
return $results;
}
}
In my controller, i try to paginate the results of the "getCategories"-function from the model:
<?php
namespace App\Controllers;
use App\Models\CategoriesModel;
use App\Models\PodcastsModel;
class Categories extends BaseController
{
public function index($page = 1)
{
$this->request->setLocale(session()->get('locale'));
//Helper laden
helper(['form', 'template', 'userrights']);
$data['template'] = getTemplate();
$model = new CategoriesModel;
$data['categories'] = $model->getCategories()->paginate(5, 'test', $page, 2);
$data['pager'] = $model->pager;
//Recht "13" (Benutzergruppen) prüfen
if ($data['userrights'][13] == 0) {
return redirect()->to('/admin');
}
//Views aufbauen
echo view($data['template'] . '/templates/header', $data);
echo view($data['template'] . '/backend/navigation');
echo view($data['template'] . '/templates/sidebar');
echo view($data['template'] . '/backend/categories');
echo view($data['template'] . '/templates/footer');
}
}
So the line
$data['categories'] = $model->getCategories()->paginate(5, 'test', $page, 2);
will cause the following error:
Error
Call to a member function paginate() on array
When i use
$data['categories'] = $model->paginate(5, 'test', $page, 2);
it works just fine. But it paginates ALL results from the categories table, as declared in the model.
But as i want to paginate the results from the function, depending on variables i pass to the model,
Is there a way to use the pagination class for model-functions?
You're not using the paginate library correctly. It must be used at the end of your query builder instead of a get() for example.
Your model could return the paginate object.
public function getCategories($nb_paginate, $categoryID = null)
{
$db = \Config\Database::connect();
if (!$categoryID) {
$results = $this->paginate($nb_paginate);
} else {
$results = $this->where('categoryID', $categoryID)->paginate($nb_paginate);
}
return $results;
}
And then catch it with your controller
$data['categories'] = $model->getCategories(5);
$data['pager'] = $model->pager;
You might want to give a look at the doc aswell : https://codeigniter.com/user_guide/libraries/pagination.html
No idea if this is "valid code" (i'm new to this formal CI4 models namespaces etc). But this works fine for me. Just make sure to filter your "search" in production properly for security
Controller:
$filter['search'] = $this->request->getGet('search');
$this->template->data['customers'] = $customer_model->get_customers_index($filter)->paginate(50);
$this->template->data['pager'] = $customer_model->pager;
Model:
function get_customers_index($filter)
{
if (isset($filter['search']) and $filter['search'])
{
$this->like('id_number', $filter['search']);
}
return $this;
}

Model not updating laravel

I can't seem to update my user and school table anymore but was able to update hobby table now.
Keep getting error: implode(): Invalid arguments passed when updating data --> linking back to the question before
Controller:
//update for user
public function edit($id){
$object = user::find($id);
return view('edit', compact('object'));
}
public function update(Request $request, $id){
$object = user::find($id);
$object->Name = $request->input('Name');
$object->update();
return redirect('/home');
}
//update for Schools table
public function edit1($id){
$object2 = school::find($id);
return view('edit1', compact('object2'));
}
public function update1(Request $request, $id){
$object2 = school::find($id);
$test = array();
$test['School'] = implode(' , ', $request->School);
$test['SDate'] = implode(' , ', $request->SDate);
$test['EDate'] = implode(' , ', $request->EDate);
$object2->update($test);
return redirect('/home');
}
// The error starts here after putting this whole thing in.
// (I tried putting it into another separate controller but the error
// still continues)
public function edit2($id) {
$object3 = hobby::find($id);
return view('edit2', compact('object3'));
}
public function update2(Request $request, $id){
$object3 = hobby::find($id);
$test2 = array();
$reading_book = (array)$request->reading_book;
$test2['reading_book'] = implode(' , ',$reading_book );
$computer_game = (array)$request->computer_game;
$test2['computer_game'] = implode(' , ',$computer_game );
$object3->update($test2);
return redirect('/home');
}
Hobby model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Eloquent;
class hobby extends Eloquent
{
protected $fillable = array('reading_book','computer_game','user_id');
public function users() {
return $this->belongsTo('App\user, 'user_id', 'id');
}
}
Route: (currently using these for updating)
Route::get('/user/show/{id}/edit', 'HomeController#edit');
Route::put('/user/show/{id}','HomeController#update');
Route::get('/user/show/{id}/edit1', 'HomeController#edit1');
Route::put('/user/show/{id}','HomeController#update1');
Route::get('/user/show/{id}/edit2', 'HomeController#edit2');
Route::put('/user/show/{id}','HomeController#update2');
The problem is in your routes :
Route::put('/user/show/{id}','HomeController#update');
Route::put('/user/show/{id}','HomeController#update1');
Route::put('/user/show/{id}','HomeController#update2');
It's the same route for three methods.
Just for testing you can do that :
Route::put('/user/show/{id}','HomeController#update');
Route::put('/user/showupdate1/{id}','HomeController#update1');
Route::put('/user/showupdate2/{id}','HomeController#update2');
And change in the view this will work perfectly :)

reuse mysql query code among few methods in same controller - Laravel 5.4

I have few queries which I would like to use it to few methods in the same controller.for example below code:
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
I need to call above query in 4 methods in UserController.
I thought of doing something like:
public function john_doe()
{
$lastlogin = User::select('lastlogin')->where('id',Auth::user()->id)->get()->pluck('lastlogin');
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$notifications = Notification::where('created_at','>',$lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}
Then
UserController
public abc (){john_doe();}
public def (){john_doe();}
public ghi (){john_doe();}
public jkl (){john_doe();}
But I get an error. How do I do this so when I change the code in one place it reflects everywhere?
Updated question
public function notify()
{
$bio = User::where('id',Auth::user()->id)->value('bio');
$photo = User::where('id',Auth::user()->id)->value('photo');
$friends = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
$notifications = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
$status = User::where('id',Auth::user()->id)->value('search_status');
}
public function index()
{
$this->notify();
return view('/users/index',compact('send_requests','accept_rejects','sent_requests','users','bio','photo','friends','status','seeks','filters','notifications'));
}
That is a poorly written code. You get everything except notifications from the logged in user model.
public function fetchData()
{
$user = auth()->user();
$notifications = Notification::where('created_at', '>' , $user->lastlogin)->get();
$data = [
'lastlogin' => $user->lastlogin,
'bio' => $user->bio,
'photo' => $user->photo,
'search_status' => $user->search_status,
'notifications' => $notifications,
];
return (Object)$data;
}
public function test()
{
$data = $this->fetchData();
// $data->lastlogin;
// $data->bio;
// $data->photo;
// $data->search_status;
// $data->notifications;
}
Your UserController could looks like this
class UserController extends BaseController {
public function notify()
{
$array['bio'] = User::where('id',Auth::user()->id)->value('bio');
$array['photo'] = User::where('id',Auth::user()->id)->value('photo');
$array['friends'] = Friend::where('user_id',Auth::user()->id)->where('reqs_status',2)->get();
$array['notifications'] = Notification::where('created_at','>',Auth::user()->lastlogin)->get();
$array['status'] = User::where('id',Auth::user()->id)->value('search_status');
return $array;
}
public function index()
{
return view('/users/index', $this->notify());
}
}

Pass setting data from database to layout

I want to pass data from de setting table from the database to my layout view.
How do I get it done?
$item = Setting::find(1);
return view($this->controller.'/show')->with( 'item', $item);
Solution:
public function boot() {
if( !isset( $_SESSION['adminTitle'] ) ){
$item = Setting::find(1);
$item = $item->toArray();
$_SESSION['adminTitle'] = $item['title'];
$_SESSION['adminEmail'] = $item['email'];
$_SESSION['adminLogo'] = $item['logo'];
}
}
Why not simply this?:
// File app/Http/Controllers/ExampleController.php
//
class ExampleController extends Controller
{
public function show()
{
//
$setting = Setting::find(1);
return view('example', ['setting' => $setting]);
}
}
Within the Blade view:
<!-- resources/views/example.blade.php -->
{{ $setting->title }}
{{ $setting->logo }}
...
But, if you want to share settings between all your views, you can add this middleware:
// File app/Http/Middleware/ViewShareSettingMiddleware
//
class ViewShareSettingMiddleware
{
public function handle($request, Closure $next)
{
$setting = Setting::find(1);
view()->share('setting', $setting);
return $next($request);
}
}
Create your view in:
\resources\views\
Example: \resources\views\index.blade.php
$data['item'] = Setting::find(1);
return view('index')
->with( $data);
Or
$item = Setting::find(1);
return view('index', compact('item');
View: {{$item}}

How to pass and retrieve data between two controllers in Laravel

I'm trying to get to grips with Laravel and not finding the documentation any help at all. It seems to assume you know so much instead of actually walking new users through each section step by step.
I've got to the point where I need to make an internal call to another class, and sticking with MVC I can't seem to do what should be a simple thing.
My code:
class UsersController extends BaseController {
protected $layout = 'layouts.templates.page';
protected $messages;
public function getIndex()
{
$input = array('where', array('field' => 'email', 'operator' => '=', 'value' => 'tony#fluidstudiosltd.com'));
$request = Request::create('user/read', 'GET');
$users = json_decode(Route::dispatch($request)->getContent());
var_dump($users); exit;
$this->pageTitle = 'Fluid Customer Status :: Admin Users';
$this->content = View::make('layouts.admin.users');
}
}
Class UserController extends Base Controller
public function getRead()
{
$userId = (int) Request::segment(3);
if ($userId)
{
$user = User::findOrFail($userId);
return $user;
}
else
{
$users = new User;
var_dump(Input::all()); exit;
if (Input::has('where'))
{
var_dump(Input::get('where')); exit;
}
return $users->get();
}
}
Why isn't the input data from UsersController#getIndex available in UserController#getRead

Categories