Trung Vu
Trung Vu

Reputation: 531

How to fix ? on the link instead of /

I want to link my 'name' to other page by '/nameID'.

For example: <a href='./2'>number 2</a>

I have tried:

@foreach($adverts as $advert) 
  {{link_to_route('adverts', $advert->name, array($advert->id))}} 
@endforeah

It returns me: <a href="http://localhost:8000/?2">, but I need <a href="http://localhost:8000/2">.

Where am I wrong?

More details:

models/advert.php

class advert extends Eloquent {
    protected $table = 'adverts';
}

routes.php

Route::get('/', array('as'=>'adverts', 'uses'=>'advertsController@index'));
Route::get('/{id}', array('as'=>'advert', 'uses'=>'advertsController@info'));

controllers/advertsController.php

public function index() {
    return View::make('adverts.index')
               ->with('adverts', advert::All());
}
public function info($id) {
    return View::make('adverts.info')
               ->with('advert', advert::find($id));
}

When I change the second route to 'as'=>'adverts' then it works fine. But I have no idea why it works. If I understand clearly, 'as'=>'advert' is only a specific name of the route, isn’t it?

Upvotes: 0

Views: 47

Answers (2)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

You need to change your route definition and add a path parameter:

 Route::get('/', array('as'=>'adverts', 'uses'=>'advertsController@index'));
 Route::get('/{id}', array('as'=>'advert', 'uses'=>'advertsController@info'));

 {{link_to_route('advert', array('id' => $advert->id))}}

Upvotes: 1

Martin Bean
Martin Bean

Reputation: 39389

You’re using the wrong route. You should be using advert (singular), as that’s the route that takes a parameter. If you try and use the index route (adverts), it’ll tack any additional parameters on as a query string.

So given you have these routes:

Route::get('/', array('as'=>'adverts', 'uses'=>'advertsController@index'));
Route::get('/{id}', array('as'=>'advert', 'uses'=>'advertsController@info'));

If you want to link to an individual advert, you need to use this:

{{ link_to_route('advert', $advert->name, array($advert->id)) }}

Also, you may want to take a look at resource controllers. They’re perfect for situations like these, where you want one route/view to list a resource, and another route/view to view details of a particular resource.

Upvotes: 1

Related Questions