skip to Main Content

I’m beginner in laravel, when I put stats table in blade I got this warning

Attempt to read property "nama" on array

This is Controller

public function show(Paslon $id)
    {
       //return "<h1> Saya siswa $id </h1>";
        $data ['data']= Paslon::where('id',$id);
        return view('/show')->with('data', $data);
    } 

This is view:

@extends('layouts.navbar')

@section('content1')

    <div>   
        
            <a href="/paslon" class="btn btn-secondry"><< Kembali</a>
            <h1></h1>
            <p>
                <b>Dapil</b>{{$data->nama}}
            </p>

            <p>
                <b>Fraksi</b>{{$data->fraksi}}
            </p>
            
    </div>

@endsection()

please help me in solving this problem

2

Answers


  1. This line doesn’t return Paslon model

    Paslon::where('id',$id);
    

    if you want to get a single model you should call first() and if you want to get a list you should call get()
    like these:

    $data = Paslon::where('id',$id)->first();
    //or
    $data = Paslon::where('id',$id)->get();
    

    and also if you want to use

    {{ $data->nama }}
    

    in your blade view, you have to return model like this

     return view('/show')->with('data', $data);
    
    Login or Signup to reply.
  2. The error you’re encountering is related to accessing properties on an array instead of an object. In your code, you’re passing an array $data to the view, but you’re trying to access its properties as if it were an object.

    You will need to add ->first() to run the query.
    You could also replace the where to find.

    You are also saving the Paslon object in the data array under the data key. You can skip this step. You can directly save the Paslon object in the $data array. Then you can access the object directly without the need of the [‘data’] key in the blade file.

    public function show(Paslon $id)
        {
           //return "<h1> Saya siswa $id </h1>";
            $data = Paslon::find($id);
            return view('/show')->with('data', $data);
        } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search