dpi96151 2019-07-31 16:32
浏览 338

我想使用laravel中的模型来获取列

Hello I want to display the first_name, last_name, subject from the tables using models in laravel after the search but whenever I try to find subject_name using the models I get error below

Exception Property [subjects] does not exist on this collection instance.

My search functionality is working fine I am just having a problem with displaying the results i.e. first_name, last_name, subject.

I tried to fetch the results from the search keywords and it returned the array of the search matched now I want to display its specific columns that I mentioned above.

User Model

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

use App\UserType;
use App\Subject;
use App\SubjectKeyword;
use App\Review;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'type', 'username', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getAllUsers() {
        return User::all();
     }

    public function userTypes()
    {
            return $this->belongsTo('App\Users');
    }

    // public function subjects()
    // {
    //     return $this->belongsToMany('App\Subject');
    // }

    public function subjects(){
        return $this->belongsTo('App\Subject','subject_id','id');
    }

    public function reviews(){
        return $this->hasMany('App\Review');
    }

    public function subjectKeywords(){
        return $this->hasMany('App\SubjectKeyword');
    }
}

Subject Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;
use App\SubjectKeyword;

class Subject extends Model
{
    protected $fillable = [
        'subject_name', 
    ];

    public function users()
    {
        return $this->hasMany('App\User');
    }

    public function subjectKeywords()
    {
        return $this->hasMany('App\SUbjectKeyword');
    }
}

SubjectKeyword Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Subject;

class SubjectKeyword extends Model
{
    protected $fillable = [
        'keyword_title1', 'keyword_title2', 'keyword_title3', 'keyword_title4', 'keyword_title5', 
    ];

    public function subjects()
    {
        return $this->belongsTo('App\Subject','subject_id','id');
    }

    public function users() {
        return $this->belongsTo('App\User','user_id','id');
    }
}

subjectkeywords table

Schema::create('subject_keywords', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('subject_id')->unsigned()->index();
            $table->integer('user_id')->unsigned()->index();
            $table->string('keyword_title1')->nullable();
            $table->string('keyword_title2')->nullable();
            $table->string('keyword_title3')->nullable();
            $table->string('keyword_title4')->nullable();
            $table->string('keyword_title5')->nullable();
            $table->timestamps();
        });

subjects table

 Schema::create('subjects', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('subject_name');
            $table->timestamps();
        });

users table

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_type_id')->unsigned()->index();
            $table->integer('university_id')->unsigned()->index()->nullable();
            $table->integer('subject_id')->unsigned()->index()->nullable();
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email');
            $table->string('username')->unique();
            $table->string('password');
            $table->string('city')->nullable();
            $table->string('country')->nullable();
            $table->string('year_of_study')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

This is my Controller where I am performing the search

public function searchMentor(Request $request) {

        $search = Input::get('search');

        if($search != "") {

            $find = SubjectKeyword::where("keyword_title1",'LIKE', '%' . $search . '%')
                                    ->orWhere("keyword_title2",'LIKE', '%' . $search . '%')
                                    ->orWhere("keyword_title3",'LIKE', '%' . $search . '%')
                                    ->orWhere("keyword_title4",'LIKE', '%' . $search . '%')
                                    ->orWhere("keyword_title5",'LIKE', '%' . $search . '%')->get();

            if(count($find)>0) {

                echo $find;
                dd($find->subjects->subject_name);
                // echo $find->user->first_name;
                die();
                return view('review.showReviewPage', compact('find', 'search'));
            } else {
                Session::flash('message', 'No keyword matched');
                return redirect('/home');
            }
        } else {

        }
    }

View

@extends('layout.genericLayout')
@section('title', 'List of Mentors')

@section('content')

<p>if have any content that will go here<p>

@endsection

@section('details')

list of mentors <br/>

@section('content2')

<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>

@if(isset($find))
<p>The search result for your query {{ $search }} are: </p>

  <h1> Sample User Details </h1>

  <table>
<tr>
    <th>Name</th>
    <th>Expert Subject</th>
    <th>City</th>
    <th>Country</th>
    <th>Overall Ratings</th>
<tr>

  @foreach($find as $find)
<tr>
    <td> {{ $find->subject->first_name }} </td>
    <td> {{ $find['keyword_title2'] }}</td>
    <td> {{ $find['city'] }} </td>
    <td> {{ $find['country'] }} </td>
    <td> </td>

</tr>
@endforeach
</table>
@endif

@endsection
@endsection

Error when I try to iterate in view

ErrorException (E_ERROR) Trying to get property 'first_name' of non-object (View: C:\xampp\htdocs\myUniMentoresources\viewseview\showReviewPage.blade.php) Previous exceptions Trying to get property 'first_name' of non-object (0)

  • 写回答

1条回答 默认 最新

  • dongmo2324 2019-07-31 16:40
    关注

    Your $find is a collection which has more than just one instance. You need to iterate through it and get all of the subjects

    评论

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab