Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method std class error in laravel

Tags:

php

laravel-5

This code related to our group project.when i use below code it is give

Call to undefined method stdClass::subjects().

I tried many ways but can not solved.

following code part give the error

 <td>{{$user->subjects()->get()[0]->name}},{$user->subjects()->get()[1]->name}}    </td>
@foreach($users as  $user)

    <tr><td>{{$user->name }} </td>
    <td>{{$user->email}} </td>
    <td>{{$user->id}}    </td>

  <td>{{$user->subjects()->get()[0]->name}},{$user->subjects()->get()[1]->name}}    </td>
</tr>
@endforeach

codes of Subject.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subject extends Model
{
      protected $table='subject';

    protected  $fillable = ['id','name','created_at','updated_at','user_id'];

    protected $primaryKey='id';

    public function user(){
      return $this->belongsTo('App\User');

}

codes of User.php

 <?php

    namespace App;

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

    class User extends Authenticatable
    {
        use Notifiable;
    protected $table='users';

        protected $fillable = [
            'usertype','name','lname', 'email','dob','school','phone','gender','password','verifyToken'
        ];


        protected $hidden = [
            'password', 'remember_token',
        ];

    )    

        }

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




    }

codes of the controller shown as belows.I removed some codes parts to avoid this is very long.they are not caused to give errors

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use App\Subject;
use PDF;

class pdfGenerator extends Controller
{

public function reportPdf()
{
   $users = DB::table('users')->get();
   $pdf  = PDF::loadview('reports', ['users' => $users]); 


   return $pdf->download('report.pdf');
}

  public function report()
    {
        $users = DB::table('users')->get();

        return view('reports', ['users' => $users]);
    }
}
like image 780
Mihiran Chathuranga Avatar asked Jan 26 '26 12:01

Mihiran Chathuranga


1 Answers

Change this line

$users = DB::table('users')->get();

To

$users = User::all();

If you want only subject name with comma separated, then do this in your view,

<?php $subject_names = $user->subjects()->pluck('name');
     $subject_names_in_string = implode(',',$subject_names);
  ?>

<td>{{$subject_names_in_string}}    </td>
like image 100
Sohel0415 Avatar answered Jan 29 '26 01:01

Sohel0415



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!