Fetch data from a Core Controller in CodeIgniter - php

I'm working on a Social Network app.
I'm facing a problem in which I'm trying to get the name and username from a table called users in my database.
To be able to do this without accessing to all the controllers individually I had to create a Core controller with the name of MY_Controller.
Here is the problem(MY_Controller without the public $users):
<?php
class MY_Controller extends CI_Controller
{
//public $users = array('username' => $this->input->post('username'));
function __construct()
{
parent::__construct();
//Get user data to make it available for both Admin and Public Controllers
$this->load->model('User_model');
$this->users = $this->User_model->get_list();
//Load Menu Library
$this->load->library('menu');
$this->pages = $this->menu->get_pages();
// Brand/Logo
$this->favicon = 'https://blogpersonal.net/wp-content/uploads/2017/08/favicon-v2-150x150.png';
$this->brand = 'Some Name';
$this->description = 'Some Description';
$this->credits = 'https://blogpersonal.net/';
$this->version = '1.1.1';
}
}
class Admin_Controller extends MY_Controller
{
function __construct()
{
parent::__construct();
if (!$this->session->is_admin) {
redirect('admin/login');
}
//some code here
}
}
class Public_Controller extends MY_Controller{
function __construct(){
parent::__construct();
//some code here
}
}
class Social_Controller extends MY_Controller
{
function __construct()
{
parent::__construct();
if (!$this->session->is_member) {
redirect('dashboard/login');
}
//some code here
}
}
As you can see I loaded the User_model using the __construct function to make it available and use it in all controllers.
I want to fetch data in a folder called templates.
views>templates>any document but when I try to fetch it in a view like this:
<?php if($this->users) : ?>
<li class="dropdown user user-menu">
<!-- Menu Toggle Button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<!-- The user image in the navbar-->
<img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
<!-- hidden-xs hides the username on small devices so only the image appears. -->
<span class="hidden-xs"><?php echo $this->users['username']; ?></span>
</a>
</li>
<?php endif; ?>
THIS IS THE OLD ERROR. it shows me an error. Am I doing something wrong? Can somebody explain me how to fix it. This is the first time in which I'm unable to fetch data.
This is the result that I get:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: users
Filename: Templates/public.php
Line Number: 161
Backtrace:
File:
C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
Line: 161 Function: _error_handler
File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
Line: 34 Function: view
File: C:\xampp\htdocs\codeigniter\application\controllers\Pages.php
Line: 12 Function: load
File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
require_once
Here is my model(User_model) in case you might need it:
<?php
class User_model extends CI_MODEL
{
function __construct()
{
parent::__construct();
$this->table = 'users';
}
public function get_list()
{
$query = $this->db->get($this->table);
return $query->result();
}
public function get($id)
{
$this->db->where('id', $id);
$query = $this->db->get($this->table);
return $query->row();
}
public function add($data)
{
$this->db->insert($this->table, $data);
}
public function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update($this->table, $data);
}
public function delete($id)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
public function login($username, $password)
{
$this->db->select('*');
$this->db->from($this->table);
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->row()->id;
} else {
return false;
}
}
}
Now with the changes that were suggested to me, it now shows a new error:
The New error:
A PHP Error was encountered
Severity: Notice Message: Undefined index: username Filename:
Templates/public.php Line Number: 168
Backtrace:
File:
C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
Line: 168 Function: _error_handler
File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
Line: 34 Function: view
File:
C:\xampp\htdocs\codeigniter\application\controllers\public\Dashboard.php
Line: 13 Function: load
File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
require_once
Now if a un-comment the public $users in the Core controller(MY_Controller) ,it shows me a new error as well:
New error with public $users out of __construct function
Fatal error: Constant expression contains invalid operations in
C:\xampp\htdocs\codeigniter\application\core\MY_Controller.php on line
6 A PHP Error was encountered
Severity: Compile Error
Message: Constant expression contains invalid operations
Filename: core/MY_Controller.php
Line Number: 6
Backtrace:
Here is a picture in which I'm trying to get the data to:
Am I doing something wrong? thanks for helping.
Here is the view (public.php) file:
<ul class="nav navbar-nav">
<?php if(!$this->session->is_member) : ?>
<li><?php echo anchor('public/users/login', 'Login'); ?></li>
<li><?php echo anchor('public/users/register', 'Register'); ?></li>
<?php else : ?>
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<!-- Menu toggle button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success">4</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 4 messages</li>
<li>
<!-- inner menu: contains the messages -->
<ul class="menu">
<li><!-- start message -->
<a href="#">
<div class="pull-left">
<!-- User Image -->
<img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
</div>
<!-- Message title and timestamp -->
<h4>
Support Team
<small><i class="fa fa-clock-o"></i> 5 mins</small>
</h4>
<!-- The message -->
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<!-- end message -->
</ul>
<!-- /.menu -->
</li>
<li class="footer">See All Messages</li>
</ul>
</li>
<!-- /.messages-menu -->
<!-- Notifications Menu -->
<li class="dropdown notifications-menu">
<!-- Menu toggle button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bell-o"></i>
<span class="label label-warning">10</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 10 notifications</li>
<li>
<!-- Inner Menu: contains the notifications -->
<ul class="menu">
<li><!-- start notification -->
<a href="#">
<i class="fa fa-users text-aqua"></i> 5 new members joined today
</a>
</li>
<!-- end notification -->
</ul>
</li>
<li class="footer">View all</li>
</ul>
</li>
<!-- Tasks Menu -->
<li class="dropdown tasks-menu">
<!-- Menu Toggle Button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-flag-o"></i>
<span class="label label-danger">9</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 9 tasks</li>
<li>
<!-- Inner menu: contains the tasks -->
<ul class="menu">
<li><!-- Task item -->
<a href="#">
<!-- Task title and progress text -->
<h3>
Design some buttons
<small class="pull-right">20%</small>
</h3>
<!-- The progress bar -->
<div class="progress xs">
<!-- Change the css width attribute to simulate progress -->
<div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">20% Complete</span>
</div>
</div>
</a>
</li>
<!-- end task item -->
</ul>
</li>
<li class="footer">
View all tasks
</li>
</ul>
</li>
<!-- User Account Menu -->
<?php if($this->users) : ?>
<li class="dropdown user user-menu">
<!-- Menu Toggle Button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<!-- The user image in the navbar-->
<img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
<!-- hidden-xs hides the username on small devices so only the image appears. -->
<span class="hidden-xs"><?php echo $this->users['username']; ?></span>
</a>
<ul class="dropdown-menu">
<!-- The user image in the menu -->
<li class="user-header">
<img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
<p><?php echo $this->users['name']; ?> - Web Developer<small>Member since Nov. 2012</small></p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="row">
<div class="col-xs-4 text-center">
Followers
</div>
<div class="col-xs-4 text-center">
Sales
</div>
<div class="col-xs-4 text-center">
Friends
</div>
</div>
<!-- /.row -->
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
Profile
</div>
<div class="pull-right">
Sign out
</div>
</li>
</ul>
</li>
<?php endif; ?>
<li>
<i class="fa fa-gears"></i>
</li>
<?php endif; ?>
</ul>

You currently have this... and I am only showing snippets here...
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
//Get user data to make it available for both Admin and Public Controllers
$this->load->model('User_model');
$data['users'] = $this->User_model->get_list();
<<<<snip>>>>
It was suggested that you turn your locally defined $data['users'] into a "Property"
So we now have two changes...
1 Declare the Property
2 Set the property.
class MY_Controller extends CI_Controller
{
public $users = array(); // Add the property $user, safe def of an empty array
function __construct()
{
parent::__construct();
//Get user data to make it available for both Admin and Public Controllers
$this->load->model('User_model');
//$data['users'] = $this->User_model->get_list();
// Give the property something to share.
$this->users = $this->User_model->get_list();
<<<<snip>>>>
Now all of your controllers that extend your MY_Controller now have access to $this->users created in MY_Controller...
So you reference $this->users where you want to use it.
I'd suggest you read up on Classes, Properties, Methods and Inheritance to begin with. Usually that is enough to make you dangerous. It takes a little getting used to but its worth the effort...
Update:
In your controller that calls your View you would do
$data['users'] = $this->users;
And in your view, you now refer to it as $users->field_name just like before.
All we have done is define $users in your base class which is now accessible as $this->users so it's accessible to all your controllers / methods that extend the MY_Controller class.

you currently have this.
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
//Get user data to make it available for both Admin and Public Controllers
$this->load->model('User_model');
$data['users'] = $this->User_model->get_list();
you should use $this->data['users'] in place of $data
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
//Get user data to make it available for both Admin and Public Controllers
$this->load->model('User_model');
$this->data['users'] = $this->User_model->get_list();
when you load your view use the code below
$this->load->view('view_name',$this->data);
it will show all your variable(in view) stored in parent classes construct function

Related

I got route not defined when run make:controller controller_name --resource

web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PostsController;
use App\Http\Controllers\AboutController;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\TagController;
use App\Http\Controllers\AdminControllers\DashboardController;
use App\Http\Controllers\AdminControllers\AdminPostsController;
use App\Http\Controllers\AdminControllers\AdminCategoriesController;
use App\Http\Controllers\AdminControllers\TinyMCEController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [HomeController::class,'index'])->name("home");
Route::get('/posts/{post:slug}',[PostsController::class,'show'])->name("posts.show");
Route::post('/posts/{post:slug}',[PostsController::class,'addComment'])->name("posts.add_comment");
Route::get('/contact', [ContactController::class , 'create'])->name("contact.create");
Route::post('/contact', [ContactController::class , 'store'])->name("contact.store");
Route::get('/about', AboutController::class)->name("about");
Route::get('/categories/{category:slug}',[CategoryController::class,'show'])->name("categories.show");
Route::get('/categories',[CategoryController::class,'index'])->name("categories.index");
/// /tags/{tag:slug} === SHOULD BE /tags/{tag:name}
Route::get('/tags/{tag:name}',[TagController::class,'show'])->name("tags.show");
// Admin Dashboard
//Route::get('/admin',[DashboardController::class,'index'])->name("admin.index");
Route::prefix('admin')->name('admin.')->middleware(['auth','isadmin'])->group(function(){
Route::get('/',[DashboardController::class,'index'])->name("index");
Route::post('upload_tinymce_image',[TinyMCEController::class,'upload_tinymce_image'])->name('upload_tinymce_image');
Route::resource('posts',AdminPostsController::class);
Route::resource('categories',AdminCategoriesController::class);
});
require __DIR__.'/auth.php';
AdminCategoriesController.php
<?php
namespace App\Http\Controllers\AdminControllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Models\Category;
class AdminCategoriesController extends Controller
{
public function index()
{
return view('dashboard.categories.index');
}
public function create()
{
return view('dashboard.categories.create');
}
public function store(Request $request)
{
}
public function show(Category $category)
{
return view('dashboard.categories.show', [
'category' => $category
]);
}
public function edit(Category $category)
{
return view('dashboard.categories.edit', [
'category' => $category
]);
}
public function update(Request $request, Category $category)
{
}
public function destroy(Category $category)
{
}
}
nav.blade.php
<!--sidebar wrapper -->
<div class="sidebar-wrapper" data-simplebar="true">
<div class="sidebar-header">
<div>
<img src="{{asset('assets/images/logo-icon.png')}}" class="logo-icon" alt="logo icon">
</div>
<div>
<h4 class="logo-text">MYBLOG</h4>
</div>
<div class="toggle-icon ms-auto"><i class='bx bx-arrow-to-left'></i>
</div>
</div>
<!--navigation-->
<ul class="metismenu" id="menu">
<li>
<a href="" target="_blank">
<div class="parent-icon"><i class='bx bx-home-circle'></i></div>
<div class="menu-title">Dashboard</div>
</a>
</li>
<li>
<a href="javascript:;" class="has-arrow">
<div class="parent-icon"><i class='bx bx-message-square-edit'></i>
</div>
<div class="menu-title">Posts</div>
</a>
<ul>
<li> <i class="bx bx-right-arrow-alt"></i>All Posts
</li>
<li> <i class="bx bx-right-arrow-alt"></i>Add New Post
</li>
</ul>
</li>
<li>
<a href="" class="has-arrow">
<div class="parent-icon"><i class='bx bx-menu'></i>
</div>
<div class="menu-title">Categories</div>
</a>
<ul>
<li> <i class="bx bx-right-arrow-alt"></i>All Categories
</li>
<li> <i class="bx bx-right-arrow-alt"></i>Add New Category
</li>
</ul>
</li>
</ul>
<!--end navigation-->
</div>
<!--end sidebar wrapper -->
I develop a blog and I have a resource controller for posts and worked fine when I created another one for categories gave my that error "Route [admin.categories.index] not defined." .
Just I put the route in dashboard the error raise and gone if I commented the two routes for categories in nav.blade.php file
According to Laravel 9 Documentation
Route::resources([
'posts' => AdminPostsController::class,
'categories'=> AdminCategoriesController::class
]);
then I ran php artisan route:clear.
finally the routes appears.

How to show only one data in blade that coming from collection in Laravel?

im new at Laravel, so i have following problem:
I have db with issue table, that contains 15 names of diseases with it's description. This is my model
class Issue extends Model
{
use HasFactory;
use SoftDeletes;
protected $guarded = false;
public function gender() {
return $this->belongsTo(BodyPart::class);
}
}
And here's controller:
use App\Http\Controllers\Controller;
use App\Models\Issue;
class IndexController extends Controller
{
public function __invoke()
{
$eye_issues = Issue::all();
return view('app.issues.man.eyes.index', compact('eye_issues'));
}
}
And finally below my blade file:
<main>
<section id="schedule" class="section-with-bg">
<ul class="nav nav-tabs" role="tablist" data-aos="fade-up" data-aos-delay="100">
#foreach($eye_issues as $issue)
#if($issue->body_part_id == 2 and $issue->gender_id == 1)
<li class="nav-item">
<a class="nav-link" href="#issue-{{ $issue->id }}" role="tab"
data-bs-toggle="tab">{{ $issue->issue }}</a>
</li>
#endif
#endforeach
</ul>
<div class="tab-content row justify-content-center" data-aos="fade-up" data-aos-delay="200">
#foreach($eye_issues as $issue)
#if($issue->body_part_id == 2 and $issue->gender_id == 1)
<div role="tabpanel" class="col-lg-9 tab-pane fade show active" id="issue-{{ $issue->id }}">
<div class="row schedule-item justify-content-center">
<div class="col-md-10" style=text-align:center>
<h4>{{ $issue->description }}</h4>
Test yourself
</div>
</div>
</div>
#endif
#endforeach
</div>
</div>
</section>
</main>
So problem is, after loading the page, navigation tabs should show all disease names (as it does) and the description section must be empty and show according description of disease that selected from nav-tabs and change description if disease is changed from nav-tabs. But after loading page, in the description section, there are all disease description, even nav-tabs selected to none onload. Only after selecting all diseases from nav-tabs, page works properly.
P.S I use MySQL if case u wanted to know. i tried to use all JS and CSS hide and show functions and other methods from internet, but no one works, and i guess it depends only on laravel it self. if you dont understand what i mean, comment it, i'll leave link for demo video of the issue

$post->user->name not working (ErrorException Trying to get property 'name' of non-object) || Laravel 8

I was trying to show the name who have posted the post. It was working well. But after a few days, It is showing an error (ErrorException Trying to get property 'name' of non-object). I was searching for a solution for the last few days. And I have found laravel 8 introduced jetstream for authentication purposes. But I have already started with the laravel ui.
I have checked the model of mine. But I could not find anything which could solve the problem. Here are my codes.
view
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
#foreach ($posts as $post)
<div class="post-preview">
<a href="{{route('singlePost',$post-> id )}}">
<h2 class="post-title">
{{$post->title}}
</h2>
<h3 class="post-subtitle">
{!!$post->content!!}
</h3>
</a>
<p class="post-meta">Posted by
{{$post->user->name}}
on {{date_format($post->created_at,'F d,Y')}}
|| <i class="fa fa-comment" aria-hidden="true"></i> {{$post->comments->count()}}
</p>
</div>
<hr>
#endforeach
<!-- Pager -->
<div class="clearfix">
<a class="btn btn-primary float-right" href="#">Older Posts →</a>
</div>
</div>
</div>
</div>
<hr>
#endsection
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function user(){
return $this->belongsTo('App\Models\User');
}
public function comments(){
return $this->hasMany('App\Models\PostComments');
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PublicController extends Controller
{
//This is the function which is showing posts
public function index(){
$posts = Post::all();
return view("welcome",compact('posts'));
}
public function contact(){
return view("contact");
}
public function about()
{
return view('about');
}
public function samplePost(Post $post){
return view('samplePost', compact('post'));
}
}

view can't find variable (laravel)

I have the following action in my controller:
public function viewPost($id)
{
$current_post = forum_post::with('replies')->where('id', $id)->get();
return view('forumViewPost',['currentPost', $current_post]);
}
Then I have the following view:
#extends('layout.app')
#section('content')
<div class="container">
<div class="nk-gap-2"></div>
<ul class="nk-forum nk-forum-topic">
<li>
<div class="nk-forum-topic-author">
<img src="assets/images/avatar-2-sm.jpg" alt="Kurt Tucker">
<div class="nk-forum-topic-author-name" title="Kurt Tucker">
{{$currentPost->nickname}}
</div>
<div class="nk-forum-topic-author-role">
Member
</div>
</div>
<div class="nk-forum-topic-content">
{{$currentPost->content}}
</div>
<div class="nk-forum-topic-footer">
<span class="nk-forum-topic-date">June 19,
2017</span> <span class="nk-forum-action-btn"> Reply</span>
<span class="nk-forum-action-btn"> Spam</span>
<span class="nk-forum-action-btn"><span class="nk-action-heart liked"><span class="num">1</span>
Like</span></span>
</div>
</li>
#foreach($currentPost->replies as $replies)
#endforeach
</ul>
</div>
#endsection
now when I run this. I get the following error:
Undefined variable: currentPost
Can anyone tell me what I've done wrong?
If you use [] you may write this ['currentPost' => $current_post]
All
public function viewPost($id)
{
$current_post = forum_post::with('replies')->where('id', $id)->get();
return view('forumViewPost',['currentPost' => $current_post]);
}
You can also you compact(''); and as Wreigh mentioned change $current_post to $currectPost
public function viewPost($id)
{
$currentPost = forum_post::with('replies')->where('id', $id)->get();
return view('forumViewPost', compact('currentPost'));
}

codeigniter template header white Data

how can I embed a foreach with my header?
I have already tried as in the code.
But with the output I get only "Undefined variable: header_warenkorbs" raus.
Although I am involved in the controller with the value data.
What am I doing wrong?
Controller:
<?php
class Warenkorb extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function header()
{
$data['header_warenkorbs'] = $this->Admin_model->header_warenkorbs();
$this->load->view('templates/header', $data);
// $this->load->view('test/index');
// $this->load->view('templates/footer');
}
}
Model:
<?php
class Warenkorb_model extends CI_Model
{
public function header_warenkorbs()
{
$this->db->select('*');
$this->db->from('db_artikel');
$query = $this->db->get();
return $query->result_array();
}
}
View:
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<span class="glyphicon glyphicon-shopping-cart"></span><span class="cart-items-count"><span class=" notification-counter">243</span></span>
<ul class="dropdown-menu dropdown-cart" role="menu">
<?php foreach($header_warenkorbs as $warenkorb): ?>
<li>
<span class="item">
<span class="item-left">
<span class="item-info">
<span>Item name</span>
<span>23$</span>
</span>
</span>
<span class="item-right">
<button class="btn btn-xs btn-danger pull-right">x</button>
</span>
</span>
</li>
<?php endforeach; ?>
<li class="divider"></li>
<li><a class="text-center" href="<?php echo base_url(); ?>warenkorb/index">Warenkorb</a></li>
</ul>
</li>
</ul>
Unless it is a typo or you're not showing us something the problem could be with this line.
$data['header_warenkorbs'] = $this->Admin_model->header_warenkorbs();
The model code you show is Warenkorb_model not Admin_model. Seems like the above code should maybe be
$data['header_warenkorbs'] = $this->Warenkorb_model->header_warenkorbs();
You don't show where you load the model. It is loaded somewhere... right? It is common practice to load models in the constructor of the Controller that uses the model.
class Warenkorb extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Warenkorb_model');
}
// other code
}
Do you realize you are not actually doing anything with the $header_warenkorbs in your foreach loop? You never use $warenkorb.
you need to echo it (example:)
<?php
echo '<table>
<tr>
<td>Name</td>
<td> .$name.</td>
</tr>
</table>';
?>
just edit it to your needs, im too lazy

Categories