2014-10-16 2 views
3

Я довольно новичок в laravel, и я изо всех сил пытаюсь получить формат моего URL-адреса.Передача переменной через url в laravel

форматирует в

http://mysite/blog?category1 instead of http://mysite/blog/category1 

Это файлы, которые я использую, есть способ поместить маршрут в BlogController

Route.php

Route::get('blog/{category}', function($category = null) 
{ 
    // get all the blog stuff from database 
    // if a category was passed, use that 
    // if no category, get all posts 
    if ($category) 
     $posts = Post::where('category', '=', $category)->get(); 
    else 
     $posts = Post::all(); 

    // show the view with blog posts (app/views/blog.blade.php) 
    return View::make('blog.index') 
     ->with('posts', $posts); 
}); 

BlogController

class BlogController extends BaseController { 


    public function index() 
    { 
     // get the posts from the database by asking the Active Record for "all" 
     $posts = Post::all(); 

     // and create a view which we return - note dot syntax to go into folder 
     return View::make('blog.index', array('posts' => $posts)); 
    } 
} 

blog.index лезвие

@foreach ($posts as $post) 

    <h2>{{ $post->id }}</h2> 
    <p>{{ $post->name }}</p> 
    <p>{{ $post->category }}</p> 
    <h2>{{ HTML::link(
    action('[email protected]',array($post->category)), 
    $post->category)}} 


@endforeach 
+0

вы на апач или Nginx, я думаю, что это проблема переписывания URL. –

+0

Что вы подразумеваете под «It format as»? Когда вы вводите браузер? Или ссылки, созданные Laravel? –

+0

Ссылка, созданная laravel из db. теперь он отображается как http: // localhost/blog? category = category1, и он также не фильтрует результаты db, поэтому что-то не так где-то –

ответ

0

Вместо того, чтобы использовать функцию обратного вызова для вашего Route::get использовать контроллер и действие:

Route::get('blog/{category}', '[email protected]'); 

Теперь в вашем BlogController вы можете создать свою функцию.

class BlogController extends BaseController { 

    public function index() 
    { 
     // get the posts from the database by asking the Active Record for "all" 
     $posts = Post::all(); 

     // and create a view which we return - note dot syntax to go into folder 
     return View::make('blog.index', array('posts' => $posts)); 
    } 

    /** 
    * Your new function. 
    */ 
    public function getCategory($category = null) 
    { 
     // get all the blog stuff from database 
     // if a category was passed, use that 
     // if no category, get all posts 
     if ($category) 
      $posts = Post::where('category', '=', $category)->get(); 
     else 
      $posts = Post::all(); 

     // show the view with blog posts (app/views/blog.blade.php) 
     return View::make('blog.index') 
      ->with('posts', $posts); 
    } 
} 

Update:

Для отображения ссылок на ваш взгляд, вы должны использовать HTML::linkAction вместо HTML::link:

@foreach ($posts as $post) 

    <h2>{{ $post->id }}</h2> 
    <p>{{ $post->name }}</p> 
    <p>{{ $post->category }}</p> 
    {{ HTML::linkAction('[email protected]', "Linkname", array('category' => $post->category)) }} 

@endforeach 
+0

Спасибо, я обновил свой код, но он по-прежнему отображает ссылку с? вместо /. –

+0

Спасибо, я обновил свой код выше, и он по-прежнему отображает ссылку как http: // mysite/blog? Category1 вместо http: // mysite/blog/category1 –

+0

в моем приложении в моем url i place? Category = 1, а затем в моем контроллере я извлекаю переменную с категорией = Input :: get ('category'); – Peter

0

Вы пытались использовать альтернативный .htaccess, как показано в документация? Здесь вы идете:

Options +FollowSymLinks 
RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule^index.php [L] 

Вы должны поместить его в папку public приложения.

Вот оригинал .htaccess в случае, если вы не имеете его по какой-либо причине

<IfModule mod_rewrite.c> 
<IfModule mod_negotiation.c> 
    Options -MultiViews 
</IfModule> 

RewriteEngine On 

# Redirect Trailing Slashes... 
RewriteRule ^(.*)/$ /$1 [L,R=301] 

# Handle Front Controller... 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule^index.php [L] 
</IfModule> 
+0

Я только что попробовал это и не повезло, что он все равно отображается одинаково –

+0

Можете ли вы попытаться ввести какое-то нежелательное значение в свой '.htaccess', чтобы проверить, работает ли он? Если это сработает, вы должны получить '500 Internal Server Error' – Adrenaxus

+0

Да, он работает только что получил ошибку сервера –

0

Я добавил новый маршрут:

Route::get('blog/{category}', ['as' => 'post.path', 'uses' => '[email protected]']); 

и добавил новую ссылку в index.blade:

<a href="{{ URL::route('post.path', [$post->category]) }}">{{ $post->category }}</a> 
5

routes.php

Route::get('category', '[email protected]'); 

* .blade.php печать завершенной URL

<a href="{{url('category/'.$category->id.'/subcategory')}}" class="btn btn-primary" >Ver más</a> 
Смежные вопросы