Annonym Annonym - 3 months ago 9
PHP Question

Laravel5: What does the extra slash in belongsToMany('\App\Article') do?

While going through Laracasts Laravel 5 Tutorial, the tutor mentions nothing about an extra slash before the namespace reference [ belongsToMany('\App\Article') ] in Episode 21: Many to Many Relationships. What could be its significance?

If I remove the extra \, I get an error:


No query results for model [App\Article].


Article.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Article extends Model
{
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}


App/Tag.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{

public function articles()
{
return $this->belongsToMany('\App\Article');
}
}

Answer

Answer regarding the title of your post:

Like mentioned in the comments, the \ refers to the global namespace . Not The App namespace.

You could also do

public function articles()
    {
        return $this->belongsToMany(Article::class);
    }

if that's more clear to you. This will also give the opportunity to click on the class to go directly to the definition of it.(in most IDE's )

Answer regarding the error you are receiving

No query results for model [App\Article].

This error is mostly created if you have something like this in your controller:

$article = Article::findOrFail($id)

If the article is not found it will throw that exception. Which means that in this case the $id passed through does not exist.

Comments