【问题标题】:Confused with a Laravel syntax error: unexpected '.' (seems fine to me)对 Laravel 语法错误感到困惑:意外的 '.' (对我来说似乎很好)
【发布时间】:2019-12-01 06:15:10
【问题描述】:

我是 Laravel 的新手。

我不断收到此语法错误:

Symfony\Component\Debug\Exception\FatalThrowableError
syntax error, unexpected '.' 

有问题的行是这样的:

  $post = .\DB::table('posts')->where('slug', $slug)->first();

这是不工作的整个代码:

<?php

namespace App\Http\Controllers;

class PostsController extends Controller

{
  public function show($slug)
  {
    $post = .\DB::table('posts')->where('slug', $slug)->first();

    dd($post);

     // This was to simulate a database
     // $posts = [
     //   'my-first-post' => 'Hello This is my first blog post',
     //   'my-second-post' => 'Hello This is my second blog post',
     // ];

     // if it doesn't exist then throw this error:
     if (! array_key_exists($post, $posts)){
       abort(404, 'Sorry, that post was not found.');
     }

     // return this view:
      return view('post', [
        'post' => $posts[$post]
      ]);
  }

}

我在这里错过了什么!?

谢谢

【问题讨论】:

  • 您认为使用.$post 分配有何作用?为什么你认为这很好?

标签: php laravel


【解决方案1】:

您不应该使用.\。 请将您的代码$post = .\DB::table('posts')-&gt;where('slug', $slug)-&gt;first(); 更改为$post = DB::table('posts')-&gt;where('slug', $slug)-&gt;first();,不要忘记导入数据库use DB

【讨论】:

  • 如果他们将其称为 FQCN,则不需要别名 DB\DB ...这只是 . 的问题
  • 不使用别名是可以的,但是导入类/外观或别名更容易,然后只需在函数中调用它即可。人们会像我朋友亨利那样犯一些小错误,因为他们不知道如何直接在函数内部调用类...
【解决方案2】:

您应该在变量$post 之后删除./,因此将此行更改为

  $post = DB::table('posts')->where('slug', $slug)->first();

【讨论】:

  • 请在您的答案中添加一些解释,以便其他人可以从中学习
【解决方案3】:

和我一样,您显然一直在学习 laracast 教程。 由于某种原因,正在使用的 IDE 使“\”看起来像一个“.\”

这是它在 VS 代码中的样子

只要去掉句号就可以了!

【讨论】:

  • 答案需要一张图片。该用户遇到的问题是由于代码在教程中以图形方式显示的方式。打字的提取物不会展示相同的人工制品。如果您想要文本中的代码,请告诉我,我很乐意为您分享。
  • 哦!我不知道,对不起。
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多