I am trying to populate the image_tag intermediate table with the ids of the image and the tag, however, I keep getting this error which from what I understand, says the the table name is incorrect even though it is not. It has columns image_id and tag_id which take unsigned integers.
"SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name 'image_tag ' (SQL: insert into image_tag
(image_id
, tag_id
) values (17, 12))"
public function uploadImage(Request $request){
$this->validate($request, [
'name' => 'required|max:120',
'description' => 'max:120|nullable',
'image' => 'required|max:1999'
]);
$name = $request['name'];
$description = $request['description'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$file = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($file, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$path = $request->file('image')->storeAs('public/images/uploaded', $fileNameToStore);
$image = new Image();
$image->name = $name;
$image->description = $description;
$image->user_id = $userId;
$image->file_name = $fileNameToStore;
$image->save();
$image->tags()->attach($tag);
return redirect()->route('home');
}
Image model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->belongsToMany('App\Tag', 'image_tag ','image_id','tag_id');
}
}
Tag model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public function images(){
return $this->belongsToMany('App\Image', 'image_tag','tag_id','image_id');
}
}
There is a space in 'image_tag ' that you wrote :|
return $this->belongsToMany('App\Tag', 'image_tag ','image_id','tag_id');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With