简体   繁体   中英

Laravel 5.2 Eloquent relationship return Multidimensional Array

this is may route code

Route::get('/dashboard',['middleware' => 'auth', function () {

    $links = App\Website_links::where('website_id',1)->get();
    return view('user.dashboard',['links_data'=>$links]);

}]);

and website_link model code is

class Website_links extends Model
{
   public $timestamps = false;
   protected $table = 'website_links';

    public function project()
    {
        return $this->belongsTo('App\Website','website_id')
                    ->select('project_name','project_status');
    }
 }

and view code

@foreach($links_data as $links)
         <tr>
         <td><a href="">{{$links['page_url']}}</a></td>
         <td>{{$links['project']}}</td>// here i want to display project_name from website table
         </tr>
    @endforeach

databse schema:

  website : id,project_name,project_status
  website_links: id, page_url, website_id   //here website_id is forign key.

now its shows page_url correctly but

{{$links['project']}} display {"project_name":"Project1","id":45}

and i want to show project_name value like project1 instead of whole array

  {"project_name":"Project1","id":45}

Change

$links['project'] to $link->project->project_name

@foreach($links_data as $links) 
     <tr>
         <td>
             <a href="">{{$links['page_url']}}</a>
         </td> 
        <td>
             {{$links->project->project_name}}
        </td>// here i want to display project_name from website table
     </tr> 
@endforeach

And change your query to the following to prevent the N+1 query problem

$links = App\Website_links::with('project')->where('website_id',1)->get();

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