You need to define all your website routes in web.php under the routes folder.
To create a simple route:
Route::get('news', function () {
return view('news');
});
// Or you can
Route::view('news', 'news');
Passing the variable as Categoryname in this route: here ? is defined as an optional parameter. Without it, if you don’t define the variable in the route it gives a 404 error page.
Always we are passing data as an array so you have to define a key of value that you will access on the view page.
Route::get('news/{categoryname?}', function ($categoryname) {
return view('news', ['catname' => $categoryname]);
});
Its view news.blade.php should be like below. On the view page, the variables are defined with the $ symbol. {{$name}} – simply echo the variable value.
@isset($catname)
{{ $catname }}
@endisset
Passing an external variable data into routes using USE method in an anonymous function. Here we are passing id & news data into the view page.
$news = [
1 => [
"title" => "Modi wins again in 2024",
"category" => "Politics"
],
2 => [
"title" => "Rahul wins again in 2028",
"category" => "Fun"
]
];
Route::get('news/{id?}', function ($id) use ($news) {
return view('news', ['newsarray' => $news[$id]]);
});
So the URL should be http://127.0.0.1:8000/news/1 & http://127.0.0.1:8000/news/2
@isset($newsarray['category'])
{{ $newsarray['category'] }}
@endisset
@isset($newsarray['title'])
{{ $newsarray['title'] }}
@endisset
How to pass variables using WITH method in routes:
Route::get('contact', function () {
return view('contact')->with('myname', 'Dilip Parmar');
});
And access this {{$myname}} in related view file will print the value as ‘Dilip Parmar’