代码之家  ›  专栏  ›  技术社区  ›  Stefan Avramovic

拉维尔控制器/商店

  •  0
  • Stefan Avramovic  · 技术社区  · 6 年前

    我是laravel的新手,我正试图将一条tweet存储到数据库中,我需要插入用户id,但这给了我一个错误

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Tweet;
    
    class TweetController extends Controller
    {
    
       public function store(Request $request){
    
    return Tweet::create([ 'tweet' => request('tweet'), 'user_id' => Auth::id()]);
    
        }
    }
    

    收到的错误:

    在文件中找不到app\http\controllers\auth' /应用程序/ampps/www/twitter/twitter/app/http/controllers/tweetcontroller.php

    知道吗?

    3 回复  |  直到 6 年前
        1
  •  2
  •   nakov    6 年前

    是的,您丢失了导入,这就是为什么它试图在 Controller 位置,所以放

    use Illuminate\Support\Facades\Auth;
    
    // or 
    
    use Auth; // you must have the Auth alias in the config/app.php array
    

    作为导入,或使用helper函数 auth()->id() 相反。

    因此,您可以在 User 模型添加:

    public function tweets()
    {
        return $this->hasMany(Tweet::class);
    }
    

    然后在控制器中执行以下操作:

    auth()->user()->tweets()->create([ 'tweet' => request('tweet') ]);
    
        2
  •  1
  •   Misagh Laghaei    6 年前

    您可以使用auth()helper获取用户ID:

    auth()->user()->id