SQLSTATE[42S22]: Column not found: - laravel

I am getting this error unknown column city = Faislabad but i have this column in my database. I want to fetch the data in which city is faislabad.
Code of my controller is
public function chart(Request $request)
{
$users = Disease::where("city=$request->city")
->get();
$chart = Charts::database($users, 'bar', 'highcharts')
->title("Monthly new Register Users")
->elementLabel("Total Users")
->dimensions(1000, 500)
->responsive(false)
->groupBy('name');
return view('test1',compact('chart'));
}
And the migration for my table is
public function up()
{
Schema::create('diseases', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('city');
$table->string('symptomps');
});
}
Please tell me what I am doing wrong in this.

Change:
$users = Disease::where("city=$request->city")->get();
to
$users = Disease::where('city', $request->city)->get();

Related

How to get just one user data in Laravel with eloquent?

I use Laravel 8. I want to get the user proccess course, but I get all users proccess.
In User.php
public function courses()
{
return $this->belongsToMany(Course::class);
}
Course.php
public function progresses()
{
return $this->hasMany(Progress::class);
}
Progress.php is empty.
Course table
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->string('title');
...
$table->timestamps();
});
Progress table
Schema::create('progress', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('course_id')->constrained()->onDelete('cascade');
$table->integer('percent');
$table->timestamps();
});
CourseController
public function index()
{
$userCourses = User::where('id', 1)->with('courses.progresses')->first();
return $userCourses;
}
And this return:
But I only wanted proccess where user_id = 1.
With() method can constrain eager loads with a specific array annotation. This is also described in the documentation.
$userId = 1;
$userCourses = User::where('id', $userId)
->with(
[
'courses.progresses' => function ($query) use ($userId) {
$query->where('user_id', $userId)
},
]
)->first();

morphToMany column not found

I follow tutorial from laravel documentation but it seems the tutorial not complete to explain argument morphToMany to explicit determine what the function should point to.
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'tagables.tagables_id' in 'field list' (SQL: select tags.*,
tagables.tagables_id as pivot_tagables_id,
tagables.tag_tag_id as pivot_tag_tag_id,
tagables.tagables_type as pivot_tagables_type from tags inner
join tagables on tags.tag_id = tagables.tag_tag_id where
tagables.tagables_id = 1 and tagables.tagables_type =
App\Models\Comic)
media table
Schema::create('media', function (Blueprint $table) {
$table->mediumIncrements('media_id)->nullable(false);
$table->string('title', 255);
});
tags table // one row inside tag ( walking )
Schema::create('tags', function (Blueprint $table) {
$table->mediumIncrements('tag_id');
$table->string('tag_name', 255);
});
tagables table
Schema::create('tagables', function (Blueprint $table) {
$table->unsignedMediumInteger('tag_id')->nullable(false);
$table->unsignedMediumInteger('tagable_id')->nullable(false);
$table->string('tagable_type', 255)->nullable(false);
});
comic model
public function tags()
{
return $this->morphToMany(Tag::class, 'tagable');
}
comic controller
// insert new comic
$comic = Comic::create([
'title' => 'Doraemon',
]);
// Insert into tagables table with current comic id and bind to tag id 1
which is walking
$comic->tags->create([
'tag_id' => 1
]);
it succes to insert into media but failed to insert into tagables table.
I found some mistakes in your code. Please try to rewrite this code. There is a working example of your code. I have checked it for you
2021_04_10_073813_create_media_table.php
Schema::create('media', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
$table->timestamps();
});
2021_04_10_073837_create_tags_table.php
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name', 255);
$table->timestamps();
});
2021_04_10_073856_create_taggables_table.php
Schema::create('taggables', function (Blueprint $table) {
$table->id();
$table->unsignedMediumInteger('tag_id')->nullable(false);
$table->unsignedMediumInteger('taggable_id')->nullable(false);
$table->string('taggable_type');
$table->timestamps();
});
class Media extends Model
{
protected $guarded = [];
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
class Tag extends Model
{
protected $guarded = [];
public function medias()
{
return $this->morphedByMany(Media::class, 'taggable');
}
}
And finally in a some Controller
$media = Media::create([
'name' => 'media name1',
]);
$tag = $media->tags()->create([
'name' => 'tag name1',
]);

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'blogpost_post_id' in 'field list'

I'm stumped with the use of Pivot Table on Laravel. I've read several similar posts with no success.
I'm a complete beginner. Here's the message I have.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'blogpost_post_id' in 'field list' (SQL: insert into blogpost_blogtag (blogpost_post_id, blogtag_tag_id) values (1, 2))
The issue is pretty simple. Laravel is adding the name of the table before the name of the column, and I can't find out why.
Laravel calls blogpost_post_id whereas the name of the column is simply post_id
Laravel calls blogtag_tag_id whereas the name of the column is simply tag_id
The models
Blogpost.php
public function blogtags(){
return $this->belongsToMany('App\Blogtag');
}
Blogtag.php
public function blogposts(){
return $this->belongsToMany('App\Blogpost');
}
I've also declared in the **Postcategory.php** model the following
public function blogposts()
{
return $this->hasmany('App\Blogpost');
}
The tables:
blogpost table
public function up()
{
Schema::create('blogposts', function (Blueprint $table) {
$table->increments('post_id');
$table->integer('post_editorid')->default(0);
$table->string('post_title');
$table->string('post_slug');
$table->text('post_content');
$table->integer('post_categoryid');
$table->boolean('post_banned')->default(0);
$table->integer('post_moderatorid')->default(0);
$table->dateTime('post_bandate')->nullable($value = true);
$table->string('post_picture')->nullable($value = true);
$table->string('post_extlink')->nullable($value = true);
$table->softDeletes();
$table->timestamps();
});
}
Postcategories table
public function up()
{
Schema::create('postcategories', function (Blueprint $table) {
$table->increments('cat_id');
$table->string('cat_name')->unique();
$table->timestamps();
});
}
Blogtags table
public function up()
{
Schema::create('blogtags', function (Blueprint $table) {
$table->increments('tag_id');
$table->string('tag_kw')->unique();
$table->timestamps();
});
}
And the PIVOT table
public function up()
{
Schema::create('blogpost_blogtag', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id');
$table->integer('tag_id');
$table->timestamps();
});
}
And the controller (store)
public function store(Request $request)
{
//dd($request->all());
$this->validate($request, [
'posttitle' => 'required|min:4|max:255|string',
'postcontent' => 'required|min:30|max:3000|string',
'postpict' => 'nullable|image',
'post_categoryid' => 'required',
'postlink' => 'nullable|max:255|string',
'blogtags' => 'nullable',
]);
if ($request->hasFile('postpict')) {
$postpict = $request->postpict;
$postpict_new_name = time().$postpict->getClientOriginalName();
$postpict->move('uploads/postpicts/', $postpict_new_name);
$picturl = 'uploads/postpicts/' . $postpict_new_name;
}else{
$picturl = NULL;
}
$blogpost = Blogpost::create([
'post_title' => $request->posttitle,
'post_content' => $request->postcontent,
'post_categoryid' => $request->post_categoryid,
'post_picture' => $picturl,
'post_extlink' => $request->postlink,
'post_slug' => str_slug($request->posttitle)
]);
$blogpost->blogtags()->attach($request->blogtags);
$messageposttitle = $request->posttitle;
$message = $messageposttitle . ' is successfully stored';
$title = '';
Toastr::success($message, $title, ["positionClass" => "toast-top-center"]);
return redirect()->back();
}
$blogpost->blogtags()->attach($request->blogtags);
I'll be happy to learn about the mistake I've done.
Try to use custom foreign-key
Blogpost.php
public function blogtags(){
return $this->belongsToMany('App\Blogtag','blogpost_blogtag','post_id','tag_id');
}
Blogtag.php
public function blogposts(){
return $this->belongsToMany('App\Blogpost','blogpost_blogtag','tag_id','post_id');
}

Get Settings with id of 1? Laravel5.4*

I have the following tables:
Uses table:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('surename');
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('country')->nullable();
$table->string('postcode')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->string('facebook_id')->nullable();
$table->string('linkedin_id')->nullable();
$table->string('twitter_id')->nullable();
$table->timestamps();
});
Setting table:
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->string('value');
$table->timestamps();
});
Setting_user (Pivot table):
Schema::create('setting_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('setting_id')->unsigned();
$table->foreign('setting_id')->references('id')->on('settings');
$table->timestamps();
});
Categories table:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Setting_category (pivot table):
Schema::create('setting_category', function (Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->integer('setting_id')->unsigned();
$table->foreign('setting_id')->references('id')->on('settings');
$table->timestamps();
});
In my User model this I have a belongsToMany relationship:
public function settings()
{
return $this->belongsToMany(Setting::class, 'setting_user', 'user_id','setting_id')->with('category');
}
And in my setting model:
protected $table = 'settings';
public function category()
{
return $this->hasMany(Categories::class,'id');
}
When I access it like so:
public function settings()
{
$user = User::find(1);
return $user->settings()->with('category')->first();
}
This is the result I get:
{"id":1,"value":"87658675.jpg","created_at":"2017-07-04 00:00:00","updated_at":null,"pivot":{"user_id":1,"setting_id":1},"category":[{"id":1,"name":"avatar","created_at":"2017-07-06 00:00:00","updated_at":null}]}
How can I get only the settings with category->id == 1 ?
Many thanks
If you want to get only settings for specified user and specified category, use whereHas():
public function settings()
{
$categoryId = 1;
$userId = 1;
return Settings::whereHas('categories', function ($q) use ($categoryId) {
$q->where('id', $categoryId);
})
->whereHas('users', function ($q) use ($userId) {
$q->where('id', $userId);
})
->get();
}
To make this work, fix your relationships. Looks like all relations should be belongsToMany() and not hasMany()
I have changed the relationships in my Setting model to:
public function users()
{
return $this->belongsToMany(User::class, 'setting_user','setting_id', 'user_id');
}
public function categories()
{
return $this->belongsToMany(Categories::class,'setting_category','category_id','setting_id');
}
I still have the belongsToMany relationship in my User model :
public function settings()
{
return $this->belongsToMany(Setting::class, 'setting_user', 'user_id','setting_id');
}
And I have created another method to extract the Avatar which has id of "1" like so :
/**
* Get user's avatar.
*/
public function getAvatarAttribute() {
$categoryId = 1;
$userId = Auth::user()->id;
$avatar = $this->settings()->whereHas('categories', function ($q) use ($categoryId) {
$q->where('id', $categoryId);
})->whereHas('users', function ($q) use ($userId) {
$q->where('id', $userId);
})->first();
if(!$avatar)
{
return "default-avatar.jpg";
}
return $avatar->value;
}

Laravel 4 Pivot Table (many to many) not loading

I have 2 tables: 'users' and 'nests' and 1 pivot table: 'nest_user'. In my pivot table I have email addresses I want to filter against so I can grab all the nests which have the associated email addreses. Here is my scehma:
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username');
$table->text('bio');
$table->string('picture');
$table->string('email');
$table->string('password');
$table->integer('visits');
$table->integer('nest_id');
$table->timestamps();
});
}
public function up()
{
Schema::create('nests', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('info');
$table->integer('note_id');
$table->integer('website_id');
$table->integer('image_id');
$table->integer('video_id');
$table->integer('location_id');
$table->integer('user_id');
$table->integer('share_id');
$table->string('inviteAuth');
$table->string('tid');
$table->timestamps();
});
}
public function up()
{
Schema::create('nest_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id');
$table->integer('nest_id');
$table->string('inviteEmail');
$table->timestamps();
});
}
I can do this no problem based on the User ID like this:
Route::get('/t1', function () {
$nest = User::find(2)->nest()->where('inviteEmail', '=', 'martinelli#gmail.com')->get();
foreach( $nest as $nest)
echo $nest->name, ': ', $nest->pivot->inviteEmail, "</br>";
});
I can get the nest and name and the email in the pivot - awesome...However, I want to find ALL the 'nests' which have the associated email which is NOT tied to a user ID. This is getting me closer but it is still not working:
Route::get('/t4', function () {
$users = User::all();
foreach($users as $users)
{
$nests = $users->with(array('nest' => function($query) {
$query->where('inviteEmail', '=', 'martinelli#gmail.com');
}))->get();
foreach($nests->nest as $nest)
{
echo $nest->name,"<br />";
}
}
});
I am getting this error:
Undefined property: Illuminate\Database\Eloquent\Collection::$nest
I'm not sure I fully understand your question, but your last code block doesn't make sense. You'll want to do the with while fetching the users. Also, the error you're getting makes sense, because the $nests (Collection) doesn't have a $nest property.
Again, I'm not sure this is what you're after, but give this a try:
Route::get('/t4', function () {
// Get all users and their nests where nests are filtered by inviteEmail
$users = User::with(array('nest' => function($query) {
$query->where('inviteEmail', '=', 'martinelli#gmail.com');
}))->get();
// Loop through all users
foreach($users as $user)
{
// I'm asuming you defined the relation as nests() in your User model.
foreach($user->nests as $nest)
{
echo $nest->name . "<br />";
}
}
});

Resources