So, I've created a controller to add topic in my app, and it stores it in database. The only problem is when I show a view it's giving me ErrorException.
Here is the Topic Controller
public function store(Request $request)
{
$users = User::all();
$userid = Auth::user()->id;
$topic = new Topic([
'user_id' => $userid,
'title' => $request->get('title'),
'description' => $request->get('description'),
'tags' => $request->get('tags')
]);
$topic->save();
//Creating a loop for each user, send a notification.
$message_content = "The " . Auth::user()->first_name . " " . Auth::user()->last_name . " just added a new topic. \n " . $topic->title . " \n ";
foreach ( $users as $user ) {
mail( $user->email, 'New Topic!', $message_content);
}
return redirect('/topics')->with('topics', $topics);
}
Here is the view
@foreach($topics as $topic)
<div class="col-lg-4 col-md-6">
<div class="widget widget-shadow">
<div class="widget-content padding-20 bg-green-500 white height-full">
<a class="avatar pull-left margin-right-20" href="javascript:void(0)">
<img src=" {{URL::to('uploads')}}/{{ $topic->creator->image }} " alt=" ">
</a>
<div style="overflow:hidden;">
<small class="pull-right grey-200">{{$topic['created_at']}}</small>
<div class="font-size-18"> {{$topic->creator->first_name}} {{$topic->creator->last_name}}</div>
<div class="grey-200 font-size-14 margin-bottom-10">{{$topic->creator->role}}</div>
<blockquote class="cover-quote font-size-16 white">{{$topic['title']}}
</blockquote>
</div>
</div>
</div>
</div>
@endforeach
Here is the topic model
class Topic extends Model
public $fillable = ['title', 'user_id', 'description', 'tags'];
public function creator() {
return $this->belongsTo( User::class, 'user_id', 'id');
and here is the user model(only relation to topic model)
public function hasTopic() {
return $this->hasMany( Topic::class, 'id', 'user_id' );
}
lastly here is the controller that gets the topic data and shows a view
public function sdp()
{
$topics = Topic::all();
$users = User::with([ 'hasTopic' => function ($query) {
$query->where('id', 'user_id');
}]);
return view('topics.student', ['topics' => $topics, 'users' => $users] );
}