Laravel pass exact parameter to route - laravel

i have translated url which i need to redirect to the specific controller function, but i need also to pass an exact parameter.
For example i want to show all football news, but in the url i do not have the ID of the sport football (id=1) so i need to pass the parameter id=1 to the index() function.
Route::get('/football-news/', ['as' => 'news.index', 'uses' => 'NewsController#index']);
it is not an option to pass 'football' as a parameter, because it is just an example. The real route is translated and the code looks like that:
Route::get(LaravelLocalization::transRoute('routes.football.news'), ['as' => 'news.index', 'uses' => 'NewsController#index']);

suppose you have a NewsController to fetch all news be like
class NewsController extends Controller
{
public function index()
{
$news = News::all(); //you have to create News model
return view('news.index', compact('news')); //use to pass data in view
}
public function show($id)
{
$news_detail=News::find($id); //to fetch detail of news from database
return view('news.show', compact('news_detail'));
}
}
create index.php and show.php in views/news folder. in index.php
#foreach($news as $news_item)
<div>
{{ $news_item->title }}
</div>
#endforeach
here using "/news/{{$news_item->id}}" you can pass id of specific news into route file.
in show.php
<h1>news</h1>
<h1>
{{ $news_detail->title }}
</h1>
<ul class="list-group">
#foreach($news_detail->detail as $details)
<li class="list-group-item">{{$details}}</li>
#endforeach
</ul>
in route file
Route::get('/news/{news}', 'NewsController#show');
now you have to create show($id) function in NewsController.php which parameter is id.

You can append the index URL with ?id=1 parameter (eg. domain.com?id=1) and get it in your index controller action by using Request::get('id');
For example:
Url in template file:
<a href="domain.com?id=1" />
In your NewsController:
public function index(Request $request){
$id = $request->get('id');
}
You should be able to have access to the parameter even though you didn't specify wildcards in the route file.
Edit:
you will have to call a different #action for a different route. You can pass in an id wildcard.
For example, in Route file:
Route::get('tennis-news/{id}', 'NewsController#tennisIndex');
Route::get('football-news/{id}', 'NewsController#footballIndex');
Then in the NewsControlleryou must have public methods tennisIndex($id) and footballIindex($id), these methods will have access to the wildcard you set in the route.
For example, in NewsController
public function tennisIndex($id){
$tennnis_news = News::where('sport'='tennis)->where('id', $id)->get();
return view('tennis_news', compact('tennnis_news'));
}

Related

How to pass several $_GET parameters in blade from different anchor tags in Laravel?

so far I've passed one get parameter from an anchor tag like this:
<a class="zone" href="{{route('home', ['zone' => 'europe'])}}">Europe</a>
How to pass another one if I want to combine them both? If I do: <a class="time" href="{{route('home', ['time' => 'today'])}}">Today</a> than the zone parameter will be removed. How to pass both parameters to the same route from the anchor tags in order to have a url like this https://example.com/?zone=europe&time=today ?
You can add as many parameters as you want in the array, so if you have to add the zone, just update your code as follows:
route('home', ['time' => 'today', 'zone' => 'europe'])
Remeber that you can have these parameters both in the route definition
Route::get('home/{time}/{zone}', 'YourController#yourMethod');
And define your controller as follows:
class YourController extends Controller {
public function yourMethod(Request $request, $time, $zone) {
dd($time) // 'today';
dd($zone) // 'europe';
}
}
Or you can simply retrieve them from the request as follows:
// Route:
Route::get('home', 'YourController#yourMethod');
// Controller:
class YourController extends Controller {
public function yourMethod(Request $request) {
dd($request->time) // 'today';
dd($request->zone) // 'europe';
}
}
Inside your route definition, pass two parameters:
Route::get('/home/{zone}/{time}', 'Controller')
After that, pass the both parameters in your view, where you call the route:
<a class="time" href="{{route('home', ['time' => 'today', 'zone'=>'europe'])}}">Today</a>

why I get error on current route name with id

in my app I use link as language switcher, it works ok in all web routing and show the correct button for language switch but, in my product page with id I get this error:
Missing required parameters for [Route: products] [URI: {lang}/products/{id}]
this is the app web route:
Route::group(['prefix' => '{lang}'], function () {
Route::get('products/{id}', 'AppController#products')->name('products');
});
this is the controller:
public function products($lang, $id){
$products = Category::with('products')->where('id', $id)->get();
return view('products', compact('products', 'lang'));}
and this is the buttons I use for language switch:
#if(app()->isLocale('fa'))
<div id="change">English</div>
#elseif(app()->isLocale('en'))
<div id="change">Farsi</div>
#endif
AS I said the language switch work ok in all routes except in product with :id
The products route you've defined requires an ID and you are not putting one in the route generator.
Your code is a bit confusing, so what I think you are doing is this:
You are displaying a list of products in a category of $id, with one single link to switch languages. You will need to update your route to include a the single common product id:
public function products($lang, $id){
$products = Category::with('products')->where('id', $id)->get();
$product_id = $id;
return view('products', compact('products', 'product_id', 'lang'));
}
Then the output:
#if(app()->isLocale('fa'))
<div id="change">English</div>
#elseif(app()->isLocale('en'))
<div id="change">Farsi</div>
#endif
Should work for you.
You're missing a parameter in your products route. Only parameter you defined is id, but your controller expects lang as well, which you don't pass. Change your route definition to:
Route::get('products/{lang}/{id}', 'AppController#products')->name('products');
Also, remove curly brackets from your route prefix, since this is only the name of the route, and shouldn't be defined as a parameter:
Route::group(['prefix' => 'lang'], function ()

Dynamic url routing in Laravel

I am new in Laravel using version 5.8
I do not want to set route manually for every controller.
What i want is that if i give any url for example -
www.example.com/product/product/add/1/2/3
www.example.com/customer/customer/edit/1/2
www.example.com/category/category/view/1
for the above example url i want that url should be treated like
www.example.com/directoryname/controllername/methodname/can have any number of parameter
I have lots of controller in my project so i want this pattern should be automatically identified by route and i do not need to specify manually again and again Directory Name, Controller , method and number of arguments(parameter) in route.
try this:
Route::get('/product/edit/{id}',[
'uses' => 'productController#edit',
'as'=>'product.edit'
]);
Route::get('/products',[
'uses' => 'productController#index',
'as'=>'products'
]);
in the controller:
public function edit($id)
{
$product=Product::find($id);
return view('edit')->with('product',$product);
}
public function index()
{
$products=Product::all();
return view('index')->with('products',$products);
}
in the index view
#foreach($products as $product)
Edit
#endforeach
in the edit view
<p>$product->name</p>
<p>$product->price</p>

How to call multiple methods or controllers to a same route in laravel

Find below the controller code with two methods and suggest me how to call these two methods in the same route or whether I have to create two different controllers for the same page(route).
class TicketController extends Controller
{
public function show(){
$results=Whmcs::GetTickets([
]);
return view('clientlayout.main.index',compact('results'));
}
public function set(){
$test=Whmcs::GetInvoices([
]);
return view('clientlayout.main.index',compact('test'));
}
}
The route file:
Route::get('clientlayout.main.index','TicketController#show');
Route::get('clientlayout.main.index','TicketController#set');
Find the code in the blade file and after running this I'm getting an error
undefined index:Results.
#foreach($results['tickets']['ticket'] as $key)
{{$key['subject']}}
#endforeach
#foreach($test['invoices']['invoice'] as $value)
{{$value['firstname']}}
#endforeach
When I run these two foreach loops in a different blade file it executes correctly, but I need these two results to be viewed in the same file.
How to view both tickets and invoices in the same index page?
Combine the two controllers into one and perform both queries in a single method:
class InvoiceTicketController extends Controller
{
public function show(){
$tickets = Whmcs::GetTickets([]);
$invoices = Whmcs::GetInvoices([]);
return view('clientlayout.main.index',compact('tickets', 'invoices'));
}
}
Then update one of the those routes to use the combined controller:
Route::get('clientlayout.main.index','InvoiceTicketController#show');
You'll have access to both $tickets and $invoices collections in the blade file this way:
#foreach($tickets as $ticket)
{{ $ticket->subject }}
#endforeach
#foreach($invoices as $invoice)
{{ $invoice->firstname }}
#endforeach

NotFoundHttpException Laravel

I am very new in learning Laravel. I want to fetch data from a database and show it. I can do it. But I want to use the title (fetched from the database) as a link. but then I get a NotFoundHttpException.
Routes
Route::get('articles', 'ArticleController#index');
Route::get('articles/{id}', 'ArticleController#show');
Controller
class ArticleController extends Controller
{
public function index()
{
$articles = Article::all();
return view('articles.index', compact('articles'));
}
public function show($id){
$article = Article::find($id);
return view('articles.show', compact('article'));
}
}
View
#extends('new_welcome')
#section('content')
<h1>Articles</h1>
#foreach($articles as $article)
<article>
<h2>
{{$article->title}}
</h2>
<div class="body">{{ $article->body}}</div>
</article>
#endforeach
#stop
Can someone help me in this case?
Your problem is because of You've "eat" one curly brace (blade engine skips it):
was:
href="{url ('/articles',$article->id)}"
have to be:
href="{{url ('/articles',$article->id)}}"
as You said:
if I click on any single article title then it can not show me the
specific article. But, if I give the URL "homestead.app/articles/2";
so You can see that when You click on link Your browser's address bar becomes:
homestead.app/{url ('/articles',$article->id)}
Because You're beginner so I'll give You advice to not to set direct url in views using url() helper.
Named routes are better if You want to have app that will work properly if in future You decide to change url from: articles to artcls. In this named routes will save You from bulk changing urls in view files.
set name to Your route using 'as' directive that makes Your routing flexible for changes (when You need to change URL so You change only path and keep views unchanged):
Route::get('articles/{id}', ['as' => 'article', 'uses' => 'ArticleController#show']);
Route::get('articles', ['as' => 'articles', 'uses' => 'ArticleController#index']);
change Your view file (find route helper in href):
#extends('new_welcome')
#section('content')
<h1> Articles </h1>
#foreach($articles as $article)
<article>
<h2>
{{$article->title}}
</h2>
<div class="body">{{ $article->body}}</div>
</article>
#endforeach
#stop

Resources