Laravel 5.2 QueryException in Connection.php line 669 - php

i'm developing an API but when I create the relations (Many to Many) and want to show in the index function I'm getting an error QueryException in Connection.php line 669 The error says:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'CTL_Tags.id' in 'on clause' (SQL: select `CTL_Tags`.*, `CTL_Resource_has_Tags`.`idResource` as `pivot_idResource`, `CTL_Resource_has_Tags`.`idTag` as `pivot_idTag` from `CTL_Tags` inner join `CTL_Resource_has_Tags` on `CTL_Tags`.`id` = `CTL_Resource_has_Tags`.`idTag` where `CTL_Resource_has_Tags`.`idResource` is null)
I believe my error is in my model because it's looking for id in CTL_Tags table when my id name in that table is idTag.
This is my CTL_Resource model
<?php
namespace Knotion;
use Illuminate\Database\Eloquent\Model;
class CTL_Resource extends Model {
public $timestamps = false;
protected $table = "CTL_Resource";
protected $hidden = [
'coachVisibility', 'thumbnail', 'tags', 'relatedTo',
'studentVisibility', 'isHTML','studentIndex', 'coachIndex',
'isURL', 'source', 'path', 'status', 'updateTime', 'isfolder',
'parentResource', 'idModifierUser'
];
protected $fillable = ['idResourceType','productionKey', 'tags', 'idCreatorUser', 'idModifierUser', 'idCreationCountry', 'title', 'description', 'URL', 'fileName', 'extension', 'quicktag', 'minimumAge', 'maximumAge', 'productionKey'];
public function creatorUser() {
return $this->belongsTo('Knotion\OPR_User', 'idCreatorUser');
}
public function creationCountry() {
return $this->belongsTo('Knotion\CTL_Country', 'idCreationCountry');
}
public function resourceType() {
return $this->belongsTo('Knotion\CTL_ResourceType', 'idResourceType');
}
public function quickTags() {
return $this->belongsToMany('Knotion\CTL_QuickTag', 'CTL_Resource_has_QuickTags', 'idResource', 'idQuickTag');
}
public function tags() {
return $this->belongsToMany('Knotion\CTL_Tag','CTL_Resource_has_Tags', 'idResource', 'idTag');
}
public function relatedTo() {
return $this->belongsToMany('Knotion\CTL_RelatedTo', 'CTL_Resource_has_RelatedTo', 'idResource', 'idRelatedTo');
}
}
and I just will show you the code of one of the relations
<?php
namespace Knotion;
use Illuminate\Database\Eloquent\Model;
class CTL_QuickTag extends Model {
protected $table = "CTL_QuickTags";
protected $fillable = ['name'];
protected $hidden = ['status', 'createTime', 'updateTime'];
public function resources() {
return $this->belongsToMany('Knotion\CTL_Resource', 'CTL_Resource_has_QuickTags', 'idResource', 'idQuickTag');
}
}
and this is my Controller
<?php
namespace Knotion\Http\Controllers;
use Illuminate\Http\Request;
use Knotion\Http\Requests;
use Knotion\Http\Requests\ResourcesRequest;
use Knotion\CTL_Resource;
use Knotion\CTL_Tag;
use Knotion\CTL_QuickTag;
use Knotion\CTL_RelatedTo;
use Knotion\CTL_ResourceType;
class ResourcesController extends Controller {
public function index(Request $request) {
$resources = CTL_Resource::paginate(10);
$resources->each(function($resources) {
$resources->tags;
$resources->quickTags;
$resources->relatedTo;
});
return response()->json(
$resources
);
I'll be so grateful who anyone can help me. Thank you so much.

Try to define
$primaryKey
in your model , with the correct column name
https://laravel.com/docs/5.2/eloquent#defining-models

Related

cannot retrieve Category model with related items

I have very strange error in my laravel website.
I try to retrieve Category model with related items, but looking at the error I see that laravel tries to retrieve items field from category model and of course it fails. But I am completely cannot understand why it happens, because I have the same code working well in other parts of my website.
routes/web.php
Route::name('gallery.')->prefix('gallery')->group(function () {
Route::get('/', 'GalleryController#index')->name('index');
Route::get('/{slug}', 'GalleryController#item')->name('item');
});
GalleryController
public function item($slug)
{
$category = $this->imageRepository->getCategoryWithPaginatedImages($slug, $perPage = 20);
return view('pages.gallery.item', compact('category'));
}
ImageRepository
namespace App\Repositories;
use Illuminate\Database\Eloquent\Collection;
use App\Models\ImageCategory as Model;
class ImageRepository extends CoreRepository
{
protected function getModelClass()
{
return Model::class;
}
public function getCategoryWithPaginatedImages($slug, $perPage = null)
{
$columns = ['id','title','slug','description','image','published','metatitle','metakey','metadesc'];
$result = $this
->startConditions()
->whereSlug($slug)
->select($columns)
->with('images:id,title,category_id,md,lg')
->firstOrFail()
->toArray();
$result = Arr::arrayToObject($result);
$result->items = collect($result->items)->mypaginate($perPage);
return $result;
}
}
Image
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $guarded = [];
public function category() { return $this->belongsTo(ImageCategory::class); }
}
ImageCategory
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ImageCategory extends Model
{
protected $guarded = [];
public $timestamps = false;
public function images() { return $this->hasMany(ImageCategory::class, 'category_id'); }
}
so when I hit gallery/slug then getCategoryWithPaginatedImages gives me following error
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category_id' in 'field list' (SQL: select `id`, `title`, `category_id`, `md`, `lg` from `image_categories` where `image_categories`.`category_id` in (2))
I guess the relationship images on ImageCategory definition has an issue, should be as under
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ImageCategory extends Model
{
protected $guarded = [];
public $timestamps = false;
public function images()
{
return $this->hasMany(Image::class, 'category_id');
}
}

How solve error Column not found: 1054 Unknown column '_token' in 'field list' (SQL: update?

public function edit($id){
$guests=Guest::with('programs', 'specialties')->find($id);
return view('editform',compact('guests'));
}
public function update(Request $request, $id)
{
$guestupdate = Guest::find($id);
$guestupdate->programs()->update($request->all());
$guestupdate->specialties()->update($request->all());
return redirect('/home/show'.$id)->with('alert', 'You have successfully updated');
}
class Guest extends Model
{
protected $primaryKey = 'guest_id';
protected $table = 'guests';
protected $fillable =
['guest_fname','guest_lname','profession','mobile','work_phone',
'current_job','previous_job','work_address','DOB','DD','program_name','specialty_name'];
public function programs()
{
return $this->belongsToMany(Program::class, 'guest_show', 'guest_id', 'program_id')
->withPivot('subject', 'show_date');
}
public function specialties()
{
return $this->belongsToMany(Specialization::class, 'guest_speciality', 'guest_id', 'speciality_id');
}
class Program extends Model
{
protected $table = 'programs';
protected $primaryKey = 'program_id';
protected $fillable = ['program_name','subject','show_date'];
public function guests()
{
return $this-
>belongsToMany(Guest::class,'guest_show','program_id','guest_id')
->withPivot('subject', 'show_date');
}
}
class Specialization extends Model
{
protected $table = 'specialties';
protected $primaryKey = 'specialty_id';
protected $fillable = ['specialty_name'];
public function guests()
{
return $this-
>belongsToMany(Guest::class,'guest_speciality','speciality_id','guest_id');
}
This is my code of controller and model to edit data(just show by guest_id) then I would to update request all field from many to many relationship.
The edit URL true but when I click button to update data appear this problem column not found:1054 Unknown column '_token' in 'field list' (SQL: update what's solve?
This is a known error and can be found here. I think your error comes from $request->all() which includes _token coming from csrf_field()
So try changing $request->all() to $request->except(['_token']); in your update function. Your new update function should look like below
public function update(Request $request, $id) {
$guestupdate = Guest::find($id);
$guestupdate->programs()->update($request->except(['_token']));
$guestupdate->specialties()->update($request->except(['_token']));
return redirect('/home/show'.$id)->with('alert', 'You have successfully updated');
}
For more study Laravel HTTP Requests
Another issue might be the syntax in ->withPivot, withPivot accepts array so change your code to below:
public function programs() {
return $this->belongsToMany(Program::class, 'guest_show', 'guest_id', 'program_id')
->withPivot(['subject', 'show_date']);
}

laravel Column not found: 1054 Unknown column 'created_at' in 'order clause'

I have defined to not use timestamps, but still laravel forces to use timestaps... Im using laravel 5.6.
When I visit page for example - http://mypage/api/videos/21/comments
I get an error - "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'created_at' in 'order clause' (SQL: select * from videos_comments where videos_comments.video_id = ▶"
app/Providers/VideoComment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class VideoComment extends Model
{
protected $table = 'videos_comments';
public $timestamps = false;
protected $fillable = [
'text', 'userid', 'date'
];
public function videos() {
return $this->belongsTo('App\Video', 'id', 'video_id');
}
public function member() {
return $this->belongsTo('App\Member', 'userid', 'member_id');
}
}
app/Providers/Video.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
class Video extends Model
{
protected $table = 'videos';
public $timestamps = false;
use Sluggable;
public function sluggable() {
return [
'slug' => [
'source' => 'title'
]
];
}
public function comments() {
return $this->hasMany('App\VideoComment', 'video_id', 'id');
}
public function member() {
return $this->belongsTo('App\Member', 'userid', 'member_id');
}
}
VideoCommentController.php function
public function index(Video $video) {
return response()->json($video->comments()->with('member')->latest()->get());
}
If you use latest() in your query then you have to add created_at in your db table, read more.
The latest and oldest methods allow you to easily order results by date. By default, the result will be ordered by the created_at column.
You can easily use orderBy and first() instead of latest() when you haven't created_at column.

Laravel retrieve values from foreign key

I have these models with their related db tables,at the moment I can retrieve all the requirement
Requirement::all()
but I just have a list of foreigns key (destination_id,applier_id,doc_id). How can i retrieve directly the row connected to that foreigns key?
class Requirement extends Model
{
protected $fillable = [
'required',
'destination_id',
'applier_id',
'doc_id'
];
public function destination()
{
return $this->belongsTo(Destination::class);
}
public function applier()
{
return $this->belongsTo(Applier::class);
}
public function doc()
{
return $this->belongsTo(Doc::class);
}
}
class Doc extends Model
{
protected $fillable = [
'type',
'description',
'note'
];
public function requirements()
{
return $this->hasMany(Requirement::class);
}
}
class Destination extends Model
{
protected $fillable = [
'country',
'passying_country',
'transfer_conditions',
'passing_conditions'
];
public function requirements()
{
return $this->hasMany(Requirement::class);
}
}
You can call with() function instead of all(). So if you try this following :
$requirements = Requirement::with('destination', 'applier', 'doc')->get();
Make it dd($requirements) and look the output.
Hope it will work.

Laravel model issue (non-object)

I am using Laravel 5.3 and this model:
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use SoftDeletes;
protected $table = 'categories';
protected $fillable = [
'name',
'slug',
'description',
'thumbnail',
'parent',
'created_by'
];
protected $hidden = [
'created_by'
];
protected $dates = ['deleted_at'];
public static function getSubcategories($category)
{
return Category::whereParent(Category::whereSlug($category)->first()->id)->get();
}
}
It works perfectly on my localhost server, but when I upload it on my production server, it outputs following error:
Trying to get property of non-object (on line ....)
It is on this line:
return Category::whereParent(Category::whereSlug($category)->first()->id)->get();
(Lines are hidden, because this model has much more functions and would be too long for this post)
Full trace:
its because the Category::whereSlug($category)->first() is returning null and that you are trying to get id of that null. so its as the error states that you are trying to get a property of non object.
I see that you are trying to get self reference category. you could so it this way as a relationships.
//children
public function categories()
{
return $this->hasMany(self::class, 'parent');
}
//parent
public function parent()
{
return $this->belongsTo(self::class, 'parent');
}
if you want to select recursively you could add this too.
public function parentRecursive()
{
return $this->parent()->with('parentRecursive');
}
public function categoriesRecursive()
{
return $this->categories()->with('categoriesRecursive');
}

Categories