سؤال

I have laravel project. When I click my view button, I want to see full description of my record. But I don't know how to pass the right id. My database table is called - csstable. I have model:

<?php 
class CssTable extends Eloquent
{
    protected $table = 'csstable';
}

View button on each post (I get all of my posts from database, so each of them have id):

<div class="view">
     <a href="{{ action('CssController@show') }}" ></a>
</div>

CssController with this show function:

public function show()
{
    $csstable = CssTable::all();
    return View::make('cssposts/right_post', compact('csstable'));
}

My Route:

Route::get('/css/id_of_right_post', 'CssController@show' );

Right_post, where I want information from description column from row, with id, that i clicked (In this field, I see just last record's description:

<h1 style="color:#fff">{{ $css->description }}</h1>

I have tried to put something like this

public function show($id)
{
    $csstable = CssTable::find($id);
    return View::make('cssposts/right_post', compact('csstable'));
}

But then there is an error - missing 1 argument in show function. So I want to know, how to pass correct id!

هل كانت مفيدة؟

المحلول

The way to do this involves three steps. First let's go for the route:

Route::get('css/{id}', 'CssController@show');

The {id} there means it's a matching parameter - it'll match a full URI segment (basically anything between slashes) and use that to pass into he method passed. So on to the controller:

class CssController
{
    public function show($id)
    {
        $csstable = CssTable::findOrFail($id);
        return View::make('cssposts/view', compact('csstable));
    }
}

That controller method accepts a (required) single parameter. You can call it whatever you want, but here I'm going for id as it's an ID for a model. Finally, the last part of the puzzle is how to link to such a route:

// view button for each csstable
<div class="view">
    {{ link_to_action('CssController@show', $item->title, array($item->getKey())) }}
</div>

As you can see, I'm using the link_to_action helper, but your method with <a href="{{{ action('CssController@show', array($item->getKey())) }}}"> will work too. After the controller action name, you pass an array that contains all of the parameters in the URI to fill in (in order). In our case we have one parameter, to it's an array with one item. I think in these cases you could also use a string and Laravel will turn it into an array with one element for you. I prefer to be explicit.

Hopefully that's helped you work out how to use the parameter-based routing system in Laravel.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top