Laravel 5.1给予" Class' App / User'找不到"尽管名称空间正确,但config / auth.php和文件位置

时间:2016-04-06 01:34:20

标签: php laravel laravel-5.1

我有 app / User.php 的用户模型类,namespace App;。此外, config / auth.php 将其标记为'model' => App\User::class

尽管如此,我的一个控制器似乎仍然存在其命名空间导入问题。下面的控制器文件将在Model.php第765行中引发" FatalErrorException:Class' App / User'如果调用orderProduct函数,则找不到" 异常。尽管使用了User类,但调用product函数不会抛出相同的错误。我想知道错误是否与导入有关,而更多的是与User类有关,不喜欢将它与OrderHeader模型关联的尝试。

<?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");
    }
}
?>

值得注意的是,AuthController与此控制器具有相同的导入功能,但在登录时没有任何问题。

<?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']),
        ]);
    }
}

为了您的利益,用户模型的内容:

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

config / auth.php 读取:

<?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,
    ],

];

OrderHeader模型。

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

(另一方面,如果您在ProductController中发现任何其他潜在错误,请告诉我 - 由于系统中的其他问题导致无法测试,我必须编写很多我的第一个真正的控制器而不进行测试。)

1 个答案:

答案 0 :(得分:2)

您的user()shippingAddress()关系使用了错误的斜杠。

return $this->belongsTo("App/User", 'id', 'OrderID');

应该是:

return $this->belongsTo("App\User", 'id', 'OrderID');