'My coding mistake or problem with the integrity of the data?
I'm learning Laravel from Laracasts videos and so far I've made simple blog with 4 posts that are dynamic but only 2 of them when I click on the name of the post open up the other 2 show error 404 not found
Example of a working one - https://ctrlv.cz/dgUM Example of a not working one - https://ctrlv.cz/MZrP
web.php code with routes
<?php
use Illuminate\Support\Facades\Route;
use App\Models\Post;
use Spatie\YamlFrontMatter\YamlFrontMatter;
Route::get('/', function () {
$files = File::files(resource_path("posts"));
$posts = [];
foreach ($files as $file) {
$document = YamlFrontMatter::parseFile($file);
$posts[] = new Post(
$document->title,
$document->excerpt,
$document->date,
$document->body(),
$document->slug
);
}
return view('posts', [
'posts' => $posts
]);
});
Route::get('posts/{post}', function ($slug) {
return view ('post', [
'post' => Post::find($slug)
]);
})->where('post', '[A-z_\-]+');
post.php
<?php
namespace App\Models;
use Illuminate\Support\Facades\File;
class Post
{
public $title;
public $excerpt;
public $date;
public $body;
public $slug;
public function __construct($title, $excerpt, $date, $body, $slug)
{
$this->title = $title;
$this->excerpt = $excerpt;
$this->date = $date;
$this->body = $body;
$this->slug = $slug;
}
public static function all()
{
$files = File::files(resource_path("posts/"));
return array_map(fn($file) => $file->getContents(), $files);
}
public static function find($slug)
{
if (! file_exists($path = resource_path("posts/{$slug}.html"))) {
throw new ModelNotFoundException();
}
return cache()->remember("posts.{$slug}", 3600, fn() => file_get_contents($path));
}
}
Solution 1:[1]
I don't think your where filter for the posts route is going to work correctly.
- For regular expressions, in order to be case insensitive, you would need to use
[A-Za-z_\-]+for the character rangesA-Zanda-z. If you look at an ASCII table, you can seeA-zwould also include characters like[ \ ] ^ _etc. - In your second example, your post slug in the url uses a character with an accent mark, I think:
í. This is not in the regular ACSII alphabet, and is therefore not in the rangea-z. Instead, you can try using the regular expression value\wwith unicode mode enabled, or just\pLwhich will match any kind of letter from any language. If you use the latter, I'd also add\dwhich is equivalent to0-9.
So, basically, I think you should change the route's where filter to something like this:
where('post', '[-_\pL\d]+');
Or,
where('post', '/[-\w]+/u'); // NOTE: I do not know if Laravel supports adding regex modifiers, so this might not work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
