简体   繁体   中英

How to display name instead of id

I have two tables: albums and categories .

I am displaying albums details with a foreach loop that includes category_id in my index page.

I want to display category_name instead of category id .

I am using Laravel

Controller code..

public function index() {
    $albums = Album::all();
    $categories = DB::table('albums')
        ->join('categories','albums.category_id','=','categories.id')
        ->select('*')->get();

    return view('admin.profile.index',compact('albums','categories'));
}

View code:

@foreach($albums as $album)
  <tr>
    <td>{{$album->album_name}}</td>
    <td>I want to diplay category_name here</td>
    <td>{{$album->created_at}}</td>
    <td>
      <input type="image" src="images/icn_edit.png" title="Edit">
      <input type="image" src="images/icn_trash.png" title="Trash">
    </td>
  </tr>
@endforeach

I want to display the category_name within the second <td> tag.

First in your model, create relationship, follow out this steps :-

Albums.php

public function category()
    {
        return $this->belongsTo('Category', 'id');
    }

Categories.php

public function categories()
    {
        return $this->hasMany('Album');
    }

controller

public function index()
    {
        $albums = Album::all();

        return View::make('admin.profile.index', compact('albums'));
    }

view

 @foreach($albums as $album)
      <tr>
        <td>{{ $album->album_name }}</td>
        <td>{{ $album->category->title }}</td>
        <td>{{ $album->created_at }}</td>
      </tr>
    @endforeach

Add you column selection in your controller like:

public function index()
    {
     $albums = Album::all();

$categories = DB::table('albums')
    ->join('categories','albums.category_id','=','categories.id')
    ->select('*,categories.category_name as cat_name')->get();
return view('admin.profile.index',compact('albums','categories'));

   }

View Code:

  @foreach($albums as $album)
            <tr>

                <td>{{$album->album_name}}</td>
                <td>{{$album->cat_name}}</td>
                <td>{{$album->created_at}}</td>
                <td><input type="image" src="images/icn_edit.png" title="Edit"><input type="image" src="images/icn_trash.png" title="Trash">           </td>
            </tr>
                @endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM