Class ' not found in laravel 5.0.16 - laravel

I am beginner in laravel. And I am using Laravel 5.0.16 in my wamp server. I have been learning laravel by free video tutorial available in laracasts.com. I have been trying to fetch data from database. I have checked that my app is already connected to database.
I do have below structure in app folder:
-app
-Http(folder)
-Other folders (folder)
-Article.php (file)
-User.php (file)
In side Http folder:
-Controllers (folder)
-Middleware (folder)
-Requests (folder)
-Kernel.php (file)
-routes.php (file)
In Controllers folder:
-ArticleController.php (file)
Below is code in side routes, controllers and model file:
/*routes*/
Route::get('articles','ArticleController#index');
/*Controller file*/
use App\models\Article;
namespace App\Http\Controllers;
use App\Http\Request;
use App\Http\Controllers\Controller;
class ArticleController extends Controller {
public function index()
{
$users = Article::all();
return $users;
}
}
/*Model file - Article.php*/
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
protected $table = 'users';
protected $fillable = ['id','firstname', 'lastname', 'email','reg_date'];
}
Where users is DB table with fields.
I am getting below arror:
FatalErrorException in ArticleController.php line:
Class 'App\Http\Controllers\Article' not found
I have check other SO forums but they didn't help me, can anyone suggest me what am I missing?

There are two issues here. One the namespace declaration should happen before any use statements.
Second your models uses the model namespace but your models aren't in a model directory. The namespace should match the directory structure. So you either need to change the namespace to use App\Article (also change the namespace in the model file) or move the model files into a models directory.
So to fix this without moving files update the code to look like this
namespace App\Http\Controllers;
use App\Article;
use App\Http\Request;
use App\Http\Controllers\Controller;
class ArticleController extends Controller {
public function index()
{
$users = Article::all();
return $users;
}
}
/*Model file - Article.php*/
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
protected $table = 'users';
protected $fillable = ['id','firstname', 'lastname', 'email','reg_date'];
}

Add this line to the top of a controller:
use App\models\Article;
Or use the full namespace when working with this model:
\App\models\Article::all();

Related

Laravel: Class not found if it is called from a Trait

After creating several Apps with Laravel and using softDelete properties I realized that methods like destroy(), restore() and kill() are exactly the same among several controllers. Therefore I am trying to put themn in a trait and use it from diferent Controllers.
My code is as follows:
ProfilesController.php
<?php
namespace App\Http\Controllers;
use App\Profile;
class ProfilesController extends Controller
{
public function destroy(Profile $profile)
{
Profile::del($profile, 'profiles');
return redirect()->route('profiles.index');
}
public function trashed()
{
Profile::trash('Profile');
}
}
Profile.php (model)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Profile extends Model
{
protected $fillable = ['user_id', 'role_id', 'title', 'subtitle', 'slug', 'birthday', 'about'];
use SoftDeletes, Helpers, commonMethods;
public function getRouteKeyName()
{
return 'slug';
}
// ... more code here
}
trait file: commonMethods.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use App\Profile;
use Session;
trait commonMethods
{
public static function del($element, $page_name)
{
$element->delete();
Session::flash('success', $element . ' successfully deleted!');
}
public static function trash($model)
{
$total = $model::onlyTrashed()->get();
$total_tr = count($total);
$all_tr = $model::all();
return view('partials.templates.trashed', compact('total', 'total_tr', 'all_tr'));
}
// ...more code here
}
The problem:
I try to visit the view "Trashed" that will list all elements "softdeleted" but not "killed", the method.
I pass the $model variable with the method trash($model)
I get the following error:
Class App/Profile does not found. Try to call App/Profile
I have debugged and the $model variable contains exactly what I need, the string 'Profile' which is what I need to build the Query:
$total = Profile::onlyTrashed()->get();
This query works while in the ProfilesController, but does not work while in a trait, since the model class is not found.
Any idea how could I make it work?
I am using Laravel 6.
If you need to use a class as a string you will want to use its full name. 'App\Profile' instead of 'Profile'.
$model = 'Profile';
new $model; // will use `\Profile`
$model = 'App\Profile';
new $model; // will use '\App\Profile';
In your controller( ProfilesController ) write :
use App\Profile;
In your model write :
use App\commonMethods;

Laravel: a simple MVC example

I'm new to Laravel and the documentation's basic task list returns Views from the Route(web.php) but I want to use a Controller to return an image file.
So I have for my route:
Route::get('/products', 'ProductController#index');
Then my ProductController action (please ignore comments as I'm using index to simplify things):
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
#return \Illuminate\Http\Response
Fetch and return all product records.
*/
public function index()
{
//
//return response()->json(Product::all(), 200);
return view('/pages/product', compact('product'));
}
And my product.blade.php (nested in views/pages/product):
<img src="/images/product/Frozen_Ophelia_800x.png">
I keep getting a ReflectionException Class App\Product does not exist.
I got this working when I just returned a view from the route. I'm getting a ReflectionException
Class App\Product does not exist so I think it's something at the top, ie. use App\Product; that is wrong.
Edit (below is my App\Product nested in app/Providers):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
//
use SoftDeletes
protected $fillable = [
'name', 'price', 'units', 'description', 'image'
];
public function orders(){
return $this->hasMany(Order::class);
}
}
Assuming App\Product model exists, correct code should be:
public function index() {
$product = Product::all();
return view('pages.product', compact('product'));
}
Check the docs.
PS did you call a $ composer dumpautoload? ReflectionException Class error is often related to new class autoloading (eg. new classes in a packages)
view function should have any view template not any url or route. Of you have file views/pages/product.blade.php then use
view('pages.product',compact('product'));

How can i get result from model in laravel 5

Good day, i'm trying to get the result from my model that called with Mainmodel through my controller, my controller is MainController.
Here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Mainmodel;
class MainController extends Controller
{
function index(){
echo "Kok, direct akses sih?";
}
function get_menu(){
$menu = app\Mainmodel::request_menu();
dd($menu);
}
}
Here is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mainmodel extends Model
{
function request_menu(){
$menu = DB::table('menu')
->orderBy('[order]', 'desc')
->get();
return $menu;
}
}
my routes
Route::get('menu','MainController#get_menu');
with my script above i get this
FatalErrorException in MainController.php line 17: Class
'App\Http\Controllers\app\Mainmodel' not found
how can i fix this ? thanks in advance.
Note: I'm bit confuse with laravel. I'm using codeigniter before. And i have a simple question. In laravel for request to database should i use model ? or can i just use my controller for my request to database.
sorry for my bad english.
I would imagine it's because your using app rather than App for the namespace.
Try changing:
app\Mainmodel
To:
App\Mainmodel
Alternatively, you can add a use statement to the top of the class and then just reference the class i.e.:
use App\Mainmodel;
Then you can just do something like:
Mainmodel::request_menu();
The way you're currently using you models is not the way Eloquent should be used. As I mentioned in my comment you should create a model for each table in your database (or at least for the majority of use cases).
To do this run:
php artisan make:model Menu
Then in the newly created Menu model add:
protected $table = 'menu';
This is because Laravel's default naming convention is singular for the class name and plural for the table name. Since your table name is menu and not menus you just need to tell Laravel to use a different table name.
Then your controller would look something like:
<?php
namespace App\Http\Controllers;
use App\Menu;
class MainController extends Controller
{
public function index()
{
echo "Kok, direct akses sih?";
}
public function get_menu()
{
$menu = Menu::orderBy('order', 'desc')->get();
dd($menu);
}
}
Hope this helps!
You can solve it by different solution. The solution is you don't have to call request_menu(); you can get it in your controller.
MainController
use use Illuminate\Support\Facades\DB;
public function get_menu(){
$menu = DB::table('menu')
->orderBy('Your_Field_Name', 'DESC')
->get();
dd($menu);
}

Class 'App\' not found on laravel 5.2

I want to add data to the database after a successful validation,but i get this error.'
FatalThrowableError in AboutController.php line 51:
Class 'App\About' not found.
My Controller
<?php
namespace App\Http\Controllers;
use App\About;
use Illuminate\Http\Request;
use App\Http\Requests;
class AboutController extends Controller
{
public function store(Request $request)
{
//
$about = $request->about;
$validation = \Validator::make($about, About::$rules);
if($validation->passes())
{
About::create($about);
return route('about/admin')->compact(about);
}
}
my Model
<?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
class About extends Model
{
//
protected $guarded = array('id');
protected $fillable = array('about');
public static $rules = array('about' => 'required|5');
}
location of controllers and Model:
App\Http\Controllers\AboutController
App\About
I have tried to run
php artisan cache:clear
php artisan clear-compiled
composer dump-autoload
I'm stuck can anyone tell me what is causing this?
As #webNeat said you should change the namespace that you are using in your Model.
Your Model About
<?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
class About extends Model
{
Controller
<?php
namespace App\Http\Controllers;
use App\About; // You have declared App\Http\Controllers in your Model
Model About Fixed
<?php
namespace App; // change to this namespace
use Illuminate\Database\Eloquent\Model;
class About extends Model
{
If you're a bit lost with Laravel or namespaces I strongly recommend you to use php artisan with each of its commands, and see and study what they do by reading all the code generated. For this case with:
php artisan make:model About
You will get a fresh new About model prepared for receive all your code with the correct namespace.
changing the namespace of your model to App should fix the issue.
<?php
namespace App; // <- here
use Illuminate\Database\Eloquent\Model;
class About extends Model
{

Polymorphic relations in upgraded Laravel app from 4.2 to 5

Short: some related models are returning instances correctly, but some aren't (the polymorphic ones).
I have those three models:
app/Models/User.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function company()
{
return $this->hasOne('App\Company');
}
}
app/Models/Company.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
public function address()
{
// Also tested with morphMany, without success
return $this->morphOne('App\Address', 'addressable');
}
}
app/Models/Address.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model {
public function addressable()
{
return $this->morphTo();
}
}
And the controller:
app/Http/Controllers/MyController.php
<?php namespace App\Http\Controllers;
// ... many "use" clauses not relevant to the question
use Auth;
// ...
use App\Address;
use App\Company;
use App\User;
class MyController extends Controller {
// Ok here
$user = Auth::user();
// Ok here, too
$company = $user->company()->first();
// Here is the problem; $address is null
$address = $company->address()->first();
}
The line $company->address()->first(); is always returning null to $address in Laravel 5, but it worked well in Laravel 4.2
In L4 models were not namespaced by default, so they were saved as ModelName in your table, while now in L5 they are rather Namespace\ModelName and are retrieved the same way.
That said, your data saved in L4 needs to be adjusted so it matches your current models, or you can use protected $morphClass on the models.
However take this into consideration for the latter solution.
If you open your database - you'll see the relationship in your old L4 data stored as: User or Company
You need to run a script that updates the columns to the new namespace names - such as App\User or App\Company
This is because you are now namespacing your models - so Laravel needs to know which namespace to call.
Along with #The Shift Exchange's answer and following my question's example, you can follow this approach:
Instead of adding the namespace in addressable_type column values from address table (and this is a valid solution), you can use $morphClass:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
protected $morphClass = 'Company';
public function user()
{
return $this->belongsTo('App\User');
}
public function address()
{
// Also tested with morphMany, without success
return $this->morphOne('App\Address', 'addressable');
}

Resources