Laravel Has Undefined Constant 'App\App\projects - laravel

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');
}

Related

How do I retrieve course contents of the specific course in Laravel?

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

Not found for some routes

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'));
}

How to show the comments which belongs to the post?

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.

FatalErrorException in Articles.php line 22: Call to undefined method Carbon\Carbon::createFormFormat()

I am getting error on this code so I start it from blade, then controller then modle kindly give me solution why this problem happened.
blade:
#extends ('lay')
#section('content')
<h1>Write a New Article</h1>
<hr>
{!!Form::open(['url'=>'articles'])!!}
<div class="form-group">
{!!Form::label('title','Title:')!!}
{!!Form::text('title','',['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::label('body','Body:')!!}
{!!Form::textarea('body','',['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::label('published_at','Published on:')!!}
{!!Form::input('date','published_at',date('Y-m-d'),['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::submit('Add Article',['class'=>'btn btn-primary form-control','name'=>'submit'])!!}
</div>
{!!Form::close()!!}
#stop
controller: this is my controller of the program all this is made in laravel
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Articles;
use Request;
use Carbon\Carbon;
class ArticlesController extends Controller {
public function index()
{
/*$art=[
'title'=>'ashwani',
'body'=>'rathi',
'published_at'=>'Carbon\Carbon::now()'
];
Articles::create($art);*/
$articles=Articles::latest()->get();
return view('articles.index', compact('articles'));
}
public function show($id)
{
$article=Articles::findorFail($id);
return view('articles.show',compact('article'));
}
public function create(){
return view('articles.create');
}
public function store()
{
//$input=Request::all();
//$input['published_at']=Carbon::now();
//Articles::create($input);
Articles::create(Request::all());
return redirect('articles');
}
}
model: this is model where i using date and its not working
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Articles extends Model {
protected $fillable= [ 'title', 'body', 'published_at' ];
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFormFormat('Y-m-d|', $date);
}
}
It looks like this is stemming from a small typo.
You have put createFormFormat, where you have spelt Form instead of From.
You just need to correct this in your function:
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date);
}
You can use
public function getPublishedAtAttribute($date){
return Carbon::parse($date)->format('Y-m-d');
}
public function setPublishedAtAttribute($date){
$this->attributes['published_at'] = Carbon::parse($date);
}
in place of
public function setPublishedAtAttribute($date){
//$this->attributes['published_at'] = Carbon::createFormFormat('Y-m-d', $date);
return $this->attributes['published_at']->format('Y-m-d');
}

laravel many to may relationship

I have two tables passport and status and a pivot table passport_statuses.I have enter passport details and select status from dropdown but I am unable to save data in pivot table.please help.My codes are as below:
Passport model
class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
Statuses model
class Statuses extends Model
{
protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
PassportController
public function create()
{
$statuses=Statuses::lists('Status_Name','id');
return view('admin.passport.create')->with('statuses',$statuses);
}
public function store(Request $request)
{
$passport=Passport::create($request->all());
$passport->status()->attach($request->input('statuses'));
return redirect('admin/passport');
}
View
{!!Form::open(['url'=>'admin/passport'])!!}
<div class="form-goup">
{!!Form::label('Full_Name','Full Name')!!}
{!!Form::text('Full_Name',null,['class'=>'form-control'])!!}
</div>
<div class="form-goup">
{!!Form::label('Date_of_Birth','Date of Birth')!!}
{!! Form::input('date', 'Date_of_Birth', null, ['class' => 'form-control', 'placeholder' => 'Date']) !!}
</div>
{!!Form::label('Passport_Number','Passport Number')!!}
{!!Form::text('Passport_Number',null,['class'=>'form-control'])!!}
<div class="form-goup">
{!!Form::label('Status_Name','Status')!!}
{!!Form::select('Status_Name',$statuses,null,['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::submit('Add',['class'=>'btn btn-primary'])!!}
</div>
{!!Form::close()!!}
Your Passport model don't belongToMany statuses, but hasManyThrough statuses.
Maybe your problem is here.
I think the line in your model Passport.php should be like this :
public function status()
{
return $this->hasManyThrough('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
Check BelongToMany and HasMany documentation on laravel.com
class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
class Statuses extends Model
{
protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport',"passport_statuses","statuses_id", "passport_id")->withTimestamps();
}
}
belongsToMany relation takes third argument foreign key of current Model table and 4th parameter foreighn key of related model table
of course your table has to be like this passport_statuses with with at least two columns statuses_id and passport_id.And in your example with created_at and updated_at timestamp columns
I was able to solve this by changing input('statuses') to input('Status_Name') in PassportController
$passport->status()->attach($request->input('Status_Name'));

Resources