嘿,伙计们,我想在laravel 8上添加一个类似和不喜欢的用户模型,而且只有当用户喜欢的是经过身份验证的用户,并且有人可以帮助我如何使它与所有用户一起成为可能时,它才能工作。
用户模型:
这是用户模型:
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'first_name',
'image',
'cover_image',
'country_id',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function likes()
{
return $this->hasOne(UserLike::class,);
}
}这是类似的模式:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
class UserLike extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'liked_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
}这是类似的迁移:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserLike extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_likes', function (Blueprint $table) {
$table->id();
$table->integer('user_id');
$table->integer('liked_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_like');
}
}
控制器:类UserLikeController扩展控制器{ //公共函数类似于不喜欢的用户($id){
$user = User::find($id);
if(!$user)
{
return response([
'message' => 'User not found.'
], 403);
}
$userlike = $user->likes()->where('user_id', auth()->user()->id)->first();
// if not liked then like
if(!$userlike)
{
UserLike::create([
'user_id' => auth()->user()->id,
'liked_id' => $id,
]);
return response([
'message' => 'Liked'
], 200);
}
// else dislike it
$userlike->delete();
return response([
'message' => 'Disliked'
], 200);
}
}发布于 2022-04-20 15:59:33
您不需要在控制器中使用Auth用户,只需要让所有用户访问该函数并检查您的路由,它不应该有Auth中间件,您的构造函数也不应该有中间件(Auth)。
https://stackoverflow.com/questions/71942671
复制相似问题