Попытка получить свойство 'nom_matiere' необъектного laravel показывает мне эту ошибку - PullRequest
0 голосов
/ 21 мая 2019

Я хочу отобразить имя matiere на этой странице, но он показывает мне эту ошибку. Попытка получить свойство 'nom_matiere' не-объекта

Я делаю выбор на странице заметок, чтобы выбрать matiere, затем отмечаю, что он работает, но когда я отображаю имя matiere в моей таблице, это выдает мне ошибку

примечание модели

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Note extends Model
 {
 protected $fillable = ['note'];


 public function matieres() 
  {
   return $this->belongsToMany(Matiere::class);
    }

}

модель matiere

   <?php

    namespace App;

   use Illuminate\Database\Eloquent\Model;

    class Matiere extends Model
    {
    protected $fillable = ['nom_matiere','coef'];


     public function notes() {
    return $this->belongsToMany(Note::class);
   }


  }

мой контроллер

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Note;
use App\Matiere;


class NoteController extends Controller
{

public function index()
{

      $notes = Note::paginate(5);
      $matieres = Matiere::all();
    return view('admin.notes',compact('notes','matieres'));
}



public function store(Request $request)
{
    Note::create($request->all());




     session()->flash('success',' cette note  a été enregistré avec succés');


       return redirect()->back();
}



public function update(Request $request, $id)
{
    $note = Note::findOrFail($request->note_id);
     $note = Matiere::findOrFail($request->note_id);

    $note->update($request->all());
    session()->flash('success','cette note a été modifié avec succés');

   return redirect()->back();
}


public function destroy(Request $request)
{
    $note = Note::findOrFail($request->note_id);
    $note->delete();
    session()->flash('success','cette note a  été supprimé avec succés');
   return redirect()->back();
}

}

мой взгляд

          <section id="no-more-tables">
            <table class="table table-bordered table-striped table-condensed cf">
              <thead class="cf">
                <tr>
                <th>id-note</th>
                  <th>La note</th>
                  <th>nom matiere</th>
                 <th>les actions</th>
                </tr>
              </thead>
              <tbody>
                @foreach($notes as $note)
                  <tr>

                  <td class="numeric"  data-title="id-note" >{{$note->id}}</td>
                  <td class="numeric"  data-title="Nom">{{$note->note}}</td>

                   <td class="numeric"  data-title="Nom">{{$note->matiere->nom_matiere}}</td>

                   <td>
                        <button href="#editEmployeeModal" class="btn btn-theme"  data-target="#editEmployeeModal "data-mynote="{{$note->note}}"   "data-mymatiere="{{$note->nom_matiere}}" data-catid={{$note->id}}  class="edit" data-toggle="modal"  ><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i> </button>
                        <button href="#deleteEmployeeModal" class="btn btn-theme" data-target="#deleteEmployeeModal" data-catid={{$note->id}} class="delete" data-toggle="modal" > <i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i> </button>
                    </td>

                </tr>
              </tbody>
              @endforeach

            </table>
            <div class="text-center">
              {{ $notes->links() }}
        </div>
            <div class="clearfix">

            <div class="hint-text">Affichage de  <b>5</b> sur <b>25</b> entrées</div>

           <div id="addEmployeeModal"  href="create" class="modal fade">
<div class="modal-dialog">
  <div class="modal-content">
    <form   action="{{route('notes.store')}}" method="post">
      {{csrf_field()}}
      <div class="modal-header">            
        <h4 class="modal-title">Ajouter note</h4>
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      </div>
      <div class="modal-body">          
        <div class="form-group">
          <label>La note</label>
          <input type="text"  id="note" name="note" class="form-control" required>
        </div>



    </div>
    <div class="form-group select">
    <select name="matiere_id">
      <option value="">--selectionner la mtiére svp --</option>

    @foreach($matieres as $matiere)
        <option value="{{ $matiere->id }}">{{ $matiere->nom_matiere }}</option>
    @endforeach  
  </select> 
  </select>
</div>

      <div class="modal-footer">
        <input type="button" class="btn btn-default" data-dismiss="modal" value="Annuler">
        <input type="submit" class="btn btn-success" value="Ajouter">
      </div>
    </form>
  </div>
</div>

1 Ответ

0 голосов
/ 21 мая 2019

Вы называете $note->matiere по вашему мнению, но отношения называются matieres, что будет набором.

Вместо:

<td class="numeric" data-title="Nom">{{ $note->matiere->nom_matiere }}</td>

Вам нужно:

<td class="numeric" data-title="Nom">
    @foreach ($note->matieres as $matiere)
        {{ $matiere->nom_matiere }}
    @endforeach
</td>

Однако я подозреваю, что вы неправильно установили свои отношения.У вас есть отношение Note -> Matiere, установленное на belongsToMany, что означает, что вам нужна сводная таблица, содержащая отношения FK.Это будет использоваться, только если ваш Note является ребенком многих Matiere.

Звучит так, будто ваши отношения установлены неправильно, но без реального понимания того, что вы пытаетесь сделать, сложночтобы сказать вам, что именно нужно сделать.

Отдельная проблема, но в вашем классе update() метод у вас также есть:

$note = Note::findOrFail($request->note_id);
$note = Matiere::findOrFail($request->note_id);

$note->update($request->all());

Это означает, что вы фактически обновляете Matiere модель № Note модель.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...