I am creating an online course site. I have issue with retrieving the course content of a specific course.
This function shows all the contents of different courses as well. I want to show the content of a specific course instead.
public function index()
{
$contents = Content::all();
return view('content.index', compact('contents'));
}
This is my content model.
class Content extends Model
{
protected $fillable = [
'topic', 'content',
];
public function course()
{
return $this->belongsTo('App\Course');
}
}
Thsi is course model.
class Course extends Model
{
protected $fillable = [
'title', 'about', 'image',
];
public function contents(){
return $this->hasMany('App\Content');
}
}
Content Migration
public function up()
{
Schema::create('contents', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('course_id');
$table->string('content');
$table->string('topic');
$table->timestamps();
});
}
Content index blade
#foreach ($contents as $content)
<div class="col-lg-12 content-list">
<a href="/content/{{$content->id}}">
<div class="cl-item mb-2" style="border-radius: 8px; padding: 18px; background-color: #c2c6ca;">
<h4 class="m-0">{{$content->topic}}</h4>
</div>
</a>
</div>
#endforeach
You need to create a route in web.php like following:
Route::get('/courses/{course_id}/contents', 'ContentController#get')->name('web.course_contents');
In the above code base, we pass "course_id" param for which we want to fetch the contents for.
In ContentController.php, do the following:
class ContentController extends Controller
{
get($course_id)
{
$contents = Content::where('course_id', $course_id)->get();
return view('content.index', compact('contents'));
}
}
Content::where('course_id', $course_id)->get() will run select * from contents where course_id = ? query to your database. You can check this by doing the following:
class ContentController extends Controller
{
get($course_id)
{
$contents = Content::where('course_id', $course_id)->get();
logger(Content::where('course_id', $course_id)->toSql());
return view('content.index', compact('contents'));
}
}
You can learn more about Laravel Query Builders here.
Happy Coding!
For this, all you need to do is use with to fetch both contents and their courses at the same time as:
public function index()
{
$contents = Content::with('course')->get();
return view('content.index', compact('contents'));
}
For more information, you can visit this link: https://laravel.com/docs/6.x/eloquent-relationships#eager-loading
Related
I keep getting the file on null error and can't seem to find why he can't locate the file?
#foreach($users as $user)
<tr>
<td>
<img height="62" src="{{asset($user->userdetail->file)}}" alt="">
</td>
</tr>
#endforeach
Userdetail Model
class UserDetail extends Model
{
use HasFactory;
protected $fillable = ['file'];
protected $uploads = '/img/avatar/';
public function getFileAttribute($userdetail){
return $this->uploads . $userdetail;
}
}
user model
protected $fillable = [
'name',
'is_active',
'email',
'photo_id',
'password',
];
public function userdetail(){
return $this->belongsTo(UserDetail::class);
}
Location of file
Migration userdetails
public function up()
{
Schema::create('user_details', function (Blueprint $table) {
$table->id();
$table->string('file');
$table->timestamps();
});
}
user
ddump of $user
You have to create the relationship for photo.
make this function in user model and place the name of the correct model
public function photo(){ return $this->hasOne(UserDetails::class, 'id', 'photo_id'); }
The problem was not the relation.
public function photo(){
return $this->belongsTo(UserDetail::class);
}
my problem was the name of the function i named it userdetail and then it will look for userdetail_id instead i needed it to name photo because then it will look for photo_id
Now it works!
I am trying to display reviews and ratings on a restaurant profile.
<div>
<h1>Reviews</h1>
#foreach($reviews as $review)
<hr>
<div class="row">
<div class="col-md-12">
#for ($i=1; $i <= 5 ; $i++)
<span class="glyphicon glyphicon-star{{ ($i <= $review->rating) ? '' : '-empty'}}"></span>
#endfor
{{ $review->user ? $review->user->name : 'Anonymous'}}
<p>{{{$review->value}}}</p>
</div>
</div>
#endforeach
</div>
Error
Undefined variable: reviews (View:
C:\xampp\htdocs\restaurantFinder\resources\views\restaurants\viewer.blade.php)
Reviews Controller
class ReviewsController extends Controller
{
public function index()
{
//
}
public function create()
{
//
}
public function store(Request $request)
{
if (!Auth::check()) {
return redirect('/index');
}
$review = new Review;
$review->user_id = auth()->user()->id;
$review->restaurant_id = $request->get('restaurant_id');
$review->value = $request->input('value');
$review->rating = $request->input('rating');
$review->save();
}
public function show($restaurant)
{
// $restaurant=Restaurant::find($id);
return view('restaurants.review', compact('restaurant'));
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
you are looking in the wrong place. to track the problem start with your route file. Search for the URL in the web.php file you will find the route there. ones you get the route, you will also get which controller and action are making this page render.
this issue is shown when you use a variable in a blade template but do not set it in the controller for use. In the controller, you can set this variable and you are good to go.
hope this help. incase of any issue feel free to ask.
update your ReviewsController.php
public function show($restaurantID)
{
$reviews = Reviews::find($restaurantID); // Find all reviews model by restaurantID
return view('viewer',compact('reviews ')); // This will do $reviews = reviews
// now you can foreach over reviews in your blade
}
this Link is useful
I have a problem with some of my routes in Laravel. this my code in web.php file:
Route::group(['namespace' => 'Admin', 'middleware' => ['auth:web']], function () {
Route::get('/admin/audio/create/{audio?}', 'AdminAudioController#create')->name('admin.audioCreate');
Route::get('/admin/article/create/{article?}', 'AdminArticleController#create')->name('admin.articleCreate');
}
and this my link in blade
<i class="fa fa-edit"></i>
<i class="fa fa-edit"></i>
and this are my Controllers:
AdminAudioController
<?php
namespace App\Http\Controllers\Admin;
use App\Article;
use App\Http\Requests\ArticleRequest;
class AdminArticleController extends AdminController
{
public function index()
{
$articleList = Article::where('removed', false)->latest()->paginate(10);
return view('admin.article.archive', compact('articleList'));
}
public function create(Article $article = null)
{
return view('admin.article.create', compact('article'));
}
}
AdminArticleController
<?php
namespace App\Http\Controllers\Admin;
use App\Article;
use App\Http\Requests\ArticleRequest;
class AdminArticleController extends AdminController
{
public function index()
{
$articleList = Article::where('removed', false)->latest()->paginate(10);
return view('admin.article.archive', compact('articleList'));
}
public function create(Article $article = null)
{
return view('admin.article.create', compact('article'));
}
}
but my second link with name "admin.articleCreate" doesn't work and get "404 not found" what should I do?
and this is my article model
class Article extends Model
{
protected $primaryKey = 'articleId';
use Sluggable;
protected $fillable = [
'title',
'subTitle1', 'subTitle2',
'image',
'description',
'body',
'enable',
];
protected $casts = [
'image' => 'array'
];
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
public function getRouteKeyName()
{
return 'slug';
}
}
When you call the method create(Article $article = null) on your controller, Laravel uses Model Binding to resolve your model and the model binding uses the method you have added to your model
public function getRouteKeyName()
{
return 'slug'; // by default it will be $primaryKey which is 'id'
}
In short, Laravel will try to use slug to find your model while your giving him articleId
So to fix it you have few options
Using the slug in the URL (the one I would recommend)
// blade.php
<i class="fa fa-edit"></i>
Using the primary articleId in the URL
// blade.php
<i class="fa fa-edit"></i>
// Article.php.php
public function getRouteKeyName()
{
return 'articleId';
}
Using a query
// blade.php
<i class="fa fa-edit"></i>
//Controller.php
public function create($article = null)
{
$article = Article::where('YOUR_FIELD', $article)->firstOrFail();
return view('admin.article.create', compact('article'));
}
you have code
return view('admin.article.create', compact('$article'));
but need
return view('admin.article.create', compact('article'));
I can see you have mentioned $article in side compact.
Can you please check once, I think the create method should look like this:
public function create(Article $article = null)
{
return view('admin.article.create', compact('article'));
}
I have created a model called company and projects, I need to show projects under a company. The company is showing fine, but when I added a project relation to the model, it displays an error. I am a newbie to Laravel.
Undefined constant 'App\App\projects' (View:
C:\xampp\htdocs\testdrive\resources\views\companies\show.blade.php)
C:\xampp\htdocs\testdrive\app\company.php
Model
use Illuminate\Database\Eloquent\Model;
class company extends Model
{
protected $fillable = [
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo(App\User);
}
public function projects()
{
return $this->hasMany(App\projects);
}
}
show.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<!-- Jumbotron -->
<div class="jumbotron">
<h1>{{$company->name}}</h1>
<p class="lead">{{$company->description}}</p>
</div>
<!-- Example row of columns -->
<div class="row">
#foreach($company->projects as $projects)
<div class="col-lg-4">
<h2>{{$projects->name}}</h2>
<p class="text-danger">{{$projects->description}} </p>
<p>
<a class="btn btn-primary" href="/projects/{{$projects->id}}" role="button">View Project</a>
</p>
</div>
#endforeach
</div>
</div>
#endsection
You've got a typo! namespaces should be strings:
public function user()
{
return $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany('App\projects');
}
You are missing class keyword in your model
class company extends Model
{
//
protected $fillable=[
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo(App\User::class);
}
public function projects()
{
return $this->hasMany(App\projects::class);
}
}
Hope this helps
Either pass class of the model or it's namespace within questions
public function user()
{
return $this->belongsTo(App\User::class); //or $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany(App\Project::class);
}
Aside from using quotes to reference the model as mentioned above.
It might also be necessary to define the namespace of your class.
Sidenote: it's also a Laravel naming convention to use PascalCase for classnames (ie. Company, WetCamel, FooBarClass)
namespace App\Company;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $fillable = [
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany('App\Projects');
}
}
Use '' this to call the model.
Correct your syntax as:
public function projects()
{
return $this->hasMany('App\projects');
}
I'm creating a news feed kind of thing where users can post anything and the post will have comments also. I'm able to create the newsfeed and the comment section, but my real problem is I'm not able to show the comments which belongs to the post. Right now all the comments are displayed under every news feed. Though I've declared the eloquent relationship between feed and comment but still I'm not able to save the feed_id in comment table.
This is my FeedsController:-
<?php namespace App\Http\Controllers;
use Request;
use Auth;
use Sentinel;
use App\Feed;
use App\Http\Requests;
use App\Blog;
use App\Http\Controllers\Controller;
use App\Comment;
class FeedsController extends Controller
{
public function index() {
$comments = Comment::latest()->get();
$feeds = Feed::where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index')->with('feeds', $feeds)->with('comments', $comments)->with('blogs', $blogs);
}
public function store(Requests\CreateFeedRequest $request){
$requet = $request->all();
$request['user_id'] = Sentinel::getuser()->id;
Feed::create($request->all());
return redirect('home');
}
public function storecomment(Requests\CommentRequest $request, Feed $feed)
{
$comment = new Comment;
$comment->user_id =Sentinel::getuser()->id;
$comment->feed_id = $request->feed_id;
$comment->comment = $request->comment;
$comment->save();
return redirect('home');
}
}
This is the models:
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Feed model:
use Illuminate\Database\Eloquent\Model;
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
User model:-
<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends EloquentUser {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes to be fillable from the model.
*
* A dirty hack to allow fields to be fillable by calling empty fillable array
*
* #var array
*/
protected $fillable = [];
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* To allow soft deletes
*/
use SoftDeletes;
protected $dates = ['deleted_at'];
public function feeds()
{
return $this->hasMany('App\Feed');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
This is my feed.blade.php where I'm displaying the feeds output and commnets
#foreach($feeds as $feed)
<article class="media">
<div class="well">
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'.$feed->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
<strong>{{ $feed->user->first_name }}
{{ $feed->user->last_name }}
<small> posted </small>
</strong>
{{ $feed->created_at->diffForHumans() }}<br><hr>
{{ $feed->feed_content }}
<hr>
{!! Form::open(['url' => 'home/{storecomment}']) !!}
<div class="form-group">
{!! Form::text('comment', null, ['class'=>'form-control', 'rows'=>3, 'placeholder'=>"Comment"]) !!}
</div>
<div class="form-group feed_post_submit">
{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}
</div>
{!! Form::close() !!}
#foreach($comments as $comment)
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'. $comment->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
{{ $comment->user->first_name }}
{{ $comment->created_at->diffForHumans() }}
{{ $comment->comment }}<hr>
#endforeach
</div>
</article>
#endforeach
Can anyone tell me how to store the feed_id into comment table and displaying the comments according to the feed. Thank You. I'm using Laravel 5.1
Based on our lengthy convo -
To save the feed_id (which is our foreign key for future relationships), you need to set/send the feed_id in your POST request. Laravel is not magic and won't know this automatically. You can do this by adding a hidden input, like so:
<input type="hidden" name="feed_id" value="{{ $feed->feed_id }}" />
In your FeedController, change your index to this:
public function index() {
// $comments = Comment::latest()->get(); remove this
// notice the "with" below. I'm eager loading in relations here
$feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index', compact('feeds', 'blogs'));
}
Feed Model should have the correct relationships, as below:
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User', 'id', 'user_id');
}
public function comments()
{
return $this->hasMany('App\Comment', 'feed_id', 'feed_id');
}
}
Comment Model should have the correct relationships, as below:
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
}
Now you should be able to run your foreach as you currently have it.