Schema::create('media', function (Blueprint $table) {
$table->id();
$table->nullableMorphs('model');
$table->string('filename');
$table->string('mime_type');
$table->bigInteger('size');
$table->unsignedBigInteger('user_id');
$table->timestamps();
});
class Media extends Model
{
use HasFactory;
protected $guarded = [];
protected $appends = ['full_url'];
public function model():MorphTo {
return $this->morphTo();
}
public function getFullUrlAttribute() {
return url('media/'. $this->user_id . '/' . $this->created_at->format('Y-m-d') . '/' . $this->filename);
}
}
Tweet Modeli
public function media(): MorphMany {
return $this->morphMany(Media::class, 'model');
}
MediaController
public function store(Request $request) {
$file = $request->file('file');
$file->store('media/'. $request->user()->id . '/' . now()->format('Y-m-d'), 'public');
$media = Media::create([
'filename' => $file->hashName(),
'mime_type' => $file->getMimeType(),
'size' => $file->getSize(),
'user_id' => $request->user()->id
]);
return response()->json(['id' => $media->id]);
}
TweetsController
public function store(Request $request) {
$request->validate([
'content' => 'required|max:280',
'mediaIds.*' => [
Rule::exists('media', 'id')
->where(function($q) use ($request) {
$q->where('user_id', $request->user()->id);
})
]
]);
$tweet = Tweet::create([
'user_id' => $request->user()->id,
'content' => $request->input('content'),
]);
Media::find($request->mediaIds)->each->update([
'model_id' => $tweet->id,
'model_type' => Tweet::class,
]);
return redirect()->back();
}
TweetsController
public function index(Request $request) {
$tweets = Tweet::where(function($q) {
$q->where('user_id', auth()->id())
->orWhereIn('user_id', auth()->user()->followings->pluck('id'));
})
->withCount([
'likes',
'likes as liked' => function($q){
$q->where('user_id', auth()->id());
}
])
->withCasts([
'liked' => 'boolean'
])
->with(['user', 'media'])
->latest()
->paginate();
if($request->wantsJson()){
return $tweets;
};
return Inertia::render('index', [
'tweets' => $tweets
]);
}
->with(['user', 'media'])
getirmeme rağmen boş gösteriyor.
https://prnt.sc/UjHx0cLTuRdy
https://prnt.sc/uyfq8IFHVzZV
Fakat databasede var.
https://prnt.sc/zvQ6D8do5Jok
https://prnt.sc/18QgFz0ymBVh