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

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.

Related

$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'));
}
}

How to view two tables data on the same blade template (view)?

I have a DB with multiple tables. I want to display the DB data on my laravel application. I want to display two tables data on the same page. I have created the model, view, and controller for the app but I am being able to display only one table. I cannot show the other table.
I think I need to define a model with multiple relationships which I am not getting how to do.
My tables are called posts and videos I have nothing on my model. the controller and the view is given below.
Controller
namespace App\Http\Controllers;
use App\Post;
use App\Video;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function index()
{
$posts = Post::all();
return view('landing')->with('posts', $posts);
}
}
View
#extends('layouts.app')
#extends('layouts.navbar')
#section('title')
Landing Page
#endsection
#section('content')
<main class="py-4">
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Section 1</h3>
#foreach ($posts as $post)
<ul class="list-group">
<li class="list-group-item">
<a href="/posts/{{ $post->id }}">
{{ $post->title }}
{{ $post->brief }}
{{ $post->body }}
{{ $post->cover_image }}
</a>
</li>
</ul>
#endforeach
</div>
<div class="col-md-4">
<h3>Section 2</h3>
#foreach ($videos as $video)
<ul class="list-group">
<li class="list-group-item">
<a href="/videos/{{ $video->id }}">
{{ $video->title }}
</a>
</li>
</ul>
#endforeach
</div>
</div>
</div>
</main>
#endsection
Route on the web.php
<?php
use App\Http\Controllers\PagesController;
use Illuminate\Support\Facades\Route;
Route::get('/', 'PostsController#index');
Route::get('/', 'VideosController#index');
Route::get('/posts/{post}', 'PostsController#show');
Route::resource('posts', 'PostsController');
Route::resource('videos', 'VideosController');
Auth::routes();
Controller for videos data table
<?php
namespace App\Http\Controllers;
use App\Video;
use Illuminate\Http\Request;
class VideosController extends Controller
{
public function index()
{
$videos = Video::all();
return view('landing')->with('videos', $videos);
}
}
On this code I see this problem
If I remove the route for videos on my web.php I could see posts data.
So how could I display both the posts and the videos data at the same time?
Pass both Model together :
<?php
namespace App\Http\Controllers;
use App\Video;
use App\Post;
use Illuminate\Http\Request;
class VideosController extends Controller
{
public function index()
{
$videos = Video::all();
$posts = Post::all();
return view('landing', compact('videos','posts'));
}
}
public function profile($id)
{
$id = Crypt::decrypt($id);
$measurements = DB::select( DB::raw("SELECT * FROM measurements WHERE custom_id = '$id'") );
$customers = DB::table('customers')->where('customer_id', '=', $id)->get();
return view('measurements.profile', compact('measurements','customers'));
}

Laravel Trying to route the same way as Reddit does with their subreddits

Hello fellow Stackoverflow users,
I am currently working on a hobby-project (a Reddit clone) using Laravel.
What I am trying to achieve is to use a similar routing to posts as Reddit does.
In my case I want to navigate to a page using the current subreddit-name and ID of the post (b/subreddit-name/postId) to determine where the website has to route to. I made it work to request the ID of the post, but I couldn't manage to get it done with the current subreddit-name the user clicks on (Subbie).
By the way: Subbie's the name which I am using instead of the term "subreddit", each post has a column stored in the database with the name of the subbie, as well as the ID of the post, so it should be all retrievable.
How can I make it possible so Laravel recognizes the "{subbie}" variable?
(Maybe I am using the wrong words to describe my problem, but I hope it all makes sense.)
Here is the code that I am using:
Router: web.php:
<?php
/*
|--------------------------------------------------------------------------
| 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('/', 'IndexController#index');
Route::get('/b/{subbie}/{id}', 'IndexController#post');
Controller: IndexController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Index;
class IndexController extends Controller
{
public function index() {
$posts = Index::all();
return view('index', ['posts' => $posts]);
}
public function post($id) {
$posts = Index::findOrFail($id);
return view('post', ['posts' => $posts]);
}
}
Model: Index.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Index extends Model
{
protected $table = 'posts';
protected $primaryKey = 'id';
}
View: index.blade.php:
#extends('layouts.app')
#section('content')
<div class="container mt-5">
<div class="col-12">
#if(count($posts) > 0)
<ul class="list-group">
#foreach ($posts as $post)
<a href="{!! url()->current() !!}/b/{{ $post->subbie }}/{{ $post->id }}">
<li class="list-group-item" style="text-decoration: none;">b/{{ $post->subbie }} · Posted by u/Test</li>
<li class="list-group-item" style="text-decoration: none;"><h5 class="h5">Tekst: {{ $post->body }}</h5></li>
</a>
#endforeach
</ul>
#else
<h1>Helaas zijn er nog geen artikels beschikbaar</h1>
#endif
</div>
</div>
#endsection
View 2: post.blade.php:
#extends('layouts.app')
#section('content')
<ul class="list-group">
<li class="list-group-item">ID: {{ $posts->id}}</li>
</ul>
#endsection

LINK PREVIOUS AND NEXT POST in a php blog

I'm a new developer and I'm trying to make work my very simple blog.
I want to set a previous and a next link to my previous and next articles in the blog. This is my current code.
POSTS CONTROLLER
public function move($id)
{
$post = DB::table('posts')->find($id);
$previous = DB::table('posts')->where('id', '<', $post->id)->max('id');
$next = DB::table('posts')->where('id', '>', $post->id)->min('id');
return view('posts.show')->with('previous', $previous)->with('next', $next);
}
WEB.PHP
<?php
Route::get('/', 'PostsController#index')->name('home');
Route::get('/posts/create', 'PostsController#create');
Route::post('/posts', 'PostsController#store');
//Route::get('/posts/{post}', 'PostsController#show');
Route::get('/posts/tags/{tag}', 'TagsController#index');
Route::post('/posts/{post}/comments','CommentsController#store');
Route::get('/posts/{id}/edit', 'PostsController#edit');
Route::get('/edit/{post}', 'PostsController#update');
Route::patch('/post/{post}', 'PostsController#update');
Route::get('/register', 'RegistrationController#create');
Route::post('/register', 'RegistrationController#store');
Route::get('/login', 'SessionsController#create');
Route::post('/login', 'SessionsController#store');
Route::get('/logout', 'SessionsController#destroy');
Route::get('/posts/{id}', 'PostsController#move');
SHOW.BLADE
#extends ('layouts.master')
#section ('content')
<div class="col-sm-8 blog-main">
<h1> {{$post->title}}</h1>
#if (count($post->tags))
<ul>
#foreach($post->tags as $tag)
<li>
<a href="/posts/tags/{{ $tag->name}}">
{{ $tag->name }}
</a>
</li>
#endforeach
</ul>
#endif
{{$post->body}}
<hr>
Modifica
<hr>
<div class='comments'>
<ul class="list-group">
#foreach ($post->comments as $comment)
<li class="lista-commenti">
<strong>
{{$comment->created_at->diffForHumans()}}:
</strong>
{{ $comment -> body}}
</li>
#endforeach
</ul>
</div>
<hr>
<div>
<div>
<form method="POST" action="/posts/{{$post->id}}/comments">
{{csrf_field()}}
<div>
<textarea name="body" placeholder="Il tuo commento" class="form-control" required></textarea>
</div>
<div>
<button type="submit" class="bottone">Invia Commento</button>
</div>
</form>
#include('layouts.errors')
</div>
<div class="row">
<ul>
<li> Previous</li>
<li> Next
</li>
</ul>
</div>
</div>
</div>
#endsection
POST.PHP
<?php
namespace App;
use Carbon\Carbon;
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function addComment($body)
{
$user_id= auth()->id();
$this->comments()->create(compact('user_id','body'));
}
public function scopeFilter($query, $filters)
{
if(!$filters)
{
return $query;
}
if ($month = $filters['month'])
{
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if ($year = $filters['year']) {
$query->whereYear('created_at', $year);
}
}
public static function archives()
{
return static::selectRaw('year(created_at) year, monthname(created_at) month, count(*) published')
->groupBy('year','month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags(){
return $this->belongsToMany(Tag::class);
}
}
This gives me an error about the undefined variables previous and next and also about the www.
Sorry but this is my first post and I can't upload any images. Hope someone can help me.
Thanks
Alessandro
use url() helper method:
<li> Previous</li>
<li> Next</li>
Edit: remove this Route::get('/posts/{post}', 'PostsController#show'); line or change your code like move method in your show method.
For your new error, add this line at top-
use Illuminate\Support\Facades\DB;
When you're going to post/1, you're executing the show method and not move.
Also, change the code to:
<li> Previous</li>
<li> Next</li>
You've said, "and also about the www". I'm pretty sure you're not getting the error about the $previous or $next but you get the error about the www... because you're trying to use text as variable in your code.

Fetch data from a Core Controller in CodeIgniter

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

Categories