skip to Main Content

I have set up a very simple project as I want to pass livewire an id and it to return some data from a table with that ID.

My basic page includes

@livewire('ShowData',['id' => 4])

I have a livewire component set up (ShowData) which is

public $id;
public function render()
{
    return view('livewire.show-data');
}

I can see the ID is passed OK

 <div class="text-center border-2 w-1/2 mx-auto bg-grey-200 my-4 px-4 py-4 rounded ">
    {{$id}}
</div>

4 comes up. So my next set was to add at the top of the show page

@php
    $fp =AppModelsFrontPanel::find($id);
@endphp

So far so good – I still get the number 4.

But when I replace showing the ID with

{{$fp->name}}

I get

Attempt to read property "name" on null

Any help appreciated! (There is a field name in the table BTW).

2

Answers


  1. Chosen as BEST ANSWER

    I have worked it out. The lookup must be before the render, unlike components which can be done on the blade file, so on the FrontPanel.php page I added in the render:

    $frontPanel = FrontPanel::find($id);
    return view('livewire.show-data', ['frontPanel' => $frontPanel]);
    

    It works OK now.


  2. You can do like this

    @livewire('show-data',['id' => 4])
    
    use AppModelsFrontPanel;
    
    class YourComponent extends Component
    {
        public $fp;
    
        public function mount($id)
        {
            $this->fp = FrontPanel::find($id);
        }
    }
    

    Or straight bind the eloquent data

    @livewire('show-data',['fp' => AppModelsFrontPanel::find(4)])
    
    use AppModelsFrontPanel;
    
    class YourComponent extends Component
    {
        public $fp;
    
        public function mount(FrontPanel $fp)
        {
            $this->fp = $fp;
        }
    }
    

    Now you can access $fp in your view as usual

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search