Home > database >  Include blade file from another file not working
Include blade file from another file not working

Time:04-20

I am trying to include this comments.index file:

@extends('posts.show')

@section('title', 'Comments')

@section('comments')
<a href="{{route('comments.create', ['id'=>$post->id])}}">Create Comment</a>
    @foreach ($comments as $comment)
        @if ($comment->post_id == $post->id)
        <div >
            <div >
                <p>{{$comment->text}}</p>
            </div>
            <a href="{{route('comments.edit', $comment->id)}}" >Edit</a>
        </div>
        @endif
    @endforeach
<a href="{{route('posts.show', ['id'=>$post->id])}}">Back</a>
@endsection

From this posts.show file:

@extends('layouts.myapp')
@section('content')

<head>
   <link href="{{ asset('css/posts.css') }}" rel="stylesheet">
</head>
<div >
   <div id="post_title">
     {{$post->title}}
   </div>
   <div id="post_text">
      {{$post->text ?? 'Empty'}}
   </div>
   <div>
      <img src="{{ asset('storage/images/'. $post->image) }}">
      <p>
        {{$post->image}}
      </p>
   </div>
</div>
<div>
   <h2>Comments</h2>
   <div>
     @include('comments')
   </div>
   <a href="{{route('comments.index', ['id' => $post->id])}}">Comments</a>
</div>
<a href="{{route('welcome')}}">Back</a>

@endsection

Now the issue is that when I include 'comments' it throws 'view comments not found' error and asks if I am sure there is a blade file with such a name. This made me think that I need to include 'comments.index', but when I do this I get 'undefined variable $comments' error.

CodePudding user response:

Doing an include of a partial is dot notation. So in this example...

@include( 'includes.modals.dude' )

This is really located in views -> includes -> modals -> dude.blade.php

The file name must be YourName.blade.php.

CodePudding user response:

I think you are providing a relative path, include directive needs absolute path. So, in your case following code should work.

@include('comments.index')
  • Related