mardi 5 avril 2016

Laravel 5.1 giving "Class 'App/User' not found" despite correct namespace, config/auth.php and file location

I have the User model class at app/User.php, with namespace App;. Also,config/auth.php marks it as 'model' => App\User::class.

Despite this, one of my controllers still seems to have a problem with its namespace imports. The below controller file will throw an "FatalErrorException in Model.php line 765: Class 'App/User' not found" exception if the orderProduct function is called. Calling the productfunction does not throw the same error, despite its usage of the User class. I'm wondering if the error has less to do with the import and more to do with the User class not liking the attempt to associate it with the OrderHeader model.

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\OrderDetail, App\OrderHeader, App\Product, App\Shipping;
use App\User;
use Auth;
use DB;
use Illuminate\Http\Request;

class ProductController extends Controller{

    public function __construct(){
        $this->middleware('auth');
    }
    public function product(Product $id){

        //$var = DB::select('select * from Product where pID = ?', [$id]);
        //return var_dump($var);
        //return view('product', ['product' => $var]);
        $id = Auth::user()->id;
        $user = User::find($id);
        return $user;//$id;
    }
    public function products(){
        $var2 = DB::select('select * from Product');
        return view('products', ['products' => $var2]);

    }

    public function orderProduct(Request $request){
        //Try and find the current incomplete order. If find fails, then create new order.
        $order;
        try{
            $order = OrderHeader::where("UserID","=", Auth::user()->id)
            ->where('OrderCompleted', '=', false)->firstOrFail();
        }catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
            $order = new OrderHeader;
            //find user
            $id = Auth::user()->id;
            $user = User::find($id);
            //associate user
            $order->user()->associate($user);
            //mark order incomplete
            $order->OrderCompleted = false;
            $order->save();
        }
        //ind matching or create new order detail. Update or add details and ave it to order. 
        $orderDetail;
        try{
            $orderDetail = $order->orderDetails()->where("ProductID", "=", $request->input("pID"))->firstOrFail(); 
            //add feilds assignment
        }catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
            $orderDetail = OrderDetail::create(['ProductID'=> $request->input("pID"), 'QtyOrdered' => $request->input("qty")]);
        }

    cartView($order);
    }
    /**
     * This controller is called when updates are made from the cart page. 
     * It is capable of deleting an OrderDetail when the quantity is set to zero.
     * 
     * @param Request $request 
     * The request must contain an OrderID and OrderDetailID, as well as an qty feild.
     */
    public function orderUpdateProduct(Request $request){
        //get the order, and then the associated order detail record
        $order = OrderHeader::find($request->input("OrderID"));
        $orderDetail = $order->orderDetails()->find($request->$input("OrderDetailID"));

        //get the product qty. If zero, delete detail, if not, update qty. 
        $qty = $request->input("qty");
        if($qty === 0){
            $orderDetail->delete();
        }
        else{
            $orderDetail->QtyOrdered = $qty;
            $orderDetail->save();
        }
        //get view data and reload page.
        cartView($order);
    }
    function cartView(OrderHeader $order){
        if(($order->OrderCompleted === false)&& ($order->UserID === Auth::user()->id)){

            $orderDetails = $order->orderDetails();
            $products[0] = "You've got a problem.";
            $i = 0;
            foreach($orderDetails as $item){
                $products[$i] = array("orderDetail" => $item, "product" => Product::where("id","=",$item->ProductID()));
                $i++;
            }
            return view("cart",['products'=> $products]);
        }else{
            return redirect("products");
        }

    }
    function finalizeOrder(Request $request){
        $ccn = $request->ccn;
        $ver = $request->ver;
        $encrypted_credit = encrypt_text($ccn);
        $encrypted_verification_num = encrypt_text($ver);
        $order;
        try{
            $order = OrderHeader::where("UserID","=", Auth::user())
            ->where('OrderCompleted', '=', false)->firstOrFail();
        }catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){
            return veiw("welcome");
        }

        //TODO: Check this whole section to make sure db names match
        $order->CreditCardNumber = $encrypted_credit;
        $order->VerficationNumber = $encrypted_verification_num;
        $order->OrderComplete = true;
        $order->save();

        $orderDetails = $order->orderDetails();
        foreach($orderDetails as $orderDetail){
            $product = Product::where("pID","=", $orderDetail->pID);
            $stockQty = $product->Qty;
            $product->Qty = $stockQty - $orderDetail->QtyOrdered;
            $product->save();
        }
        return view("shipping");
    }
}
?>

Noteabley, the AuthController has the same import as this controller, but has no issues signing me in.

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }
    protected $redirectPath = '/home';
    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

For your benefit, the contents of the User model:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'Users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
    public function orderHeader(){
        return $this->hasMany('App\OrderHeader', 'UserID', 'id');
    }
}

And config/auth.php reads:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Authentication Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the authentication driver that will be utilized.
    | This driver manages the retrieval and authentication of the users
    | attempting to get access to protected areas of your application.
    |
    | Supported: "database", "eloquent"
    |
    */

    'driver' => 'eloquent',

    /*
    |--------------------------------------------------------------------------
    | Authentication Model
    |--------------------------------------------------------------------------
    |
    | When using the "Eloquent" authentication driver, we need to know which
    | Eloquent model should be used to retrieve your users. Of course, it
    | is often just the "User" model but you may use whatever you like.
    |
    */

    'model' => App\User::class,

    /*
    |--------------------------------------------------------------------------
    | Authentication Table
    |--------------------------------------------------------------------------
    |
    | When using the "Database" authentication driver, we need to know which
    | table should be used to retrieve your users. We have chosen a basic
    | default value but you may easily change it to any table you like.
    |
    */

    'table' => 'Users',

    /*
    |--------------------------------------------------------------------------
    | Password Reset Settings
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You can also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'password' => [
        'email' => 'emails.password',
        'table' => 'password_resets',
        'expire' => 60,
    ],

];

The OrderHeader model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class OrderHeader extends Model
{
    //
    protected $table = 'OrderHeader';
    protected $primaryKey = 'OrderID';
    protected $fillable = array('ShippingID');  

    public function orderDetails(){
        return $this->hasMany('App\OrderDetail','OrderHeaderID','OrderID');
    }
    public function shippingAddress(){
        return $this->belongsTo("App/Shipping", 'ShippingID', 'ShippingID');
    }
    public function user(){
        return $this->belongsTo("App/User", 'id', 'OrderID');
    }
}

(On a side note, if you see any other potential errors in the ProductController, let me know - I had to write a lot of my first real controller without testing due to other issues in the system that made it impossible to test.)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire