🎉 سال نو، مهارت نو، مشاوره رایگان نقشه راه برنامه نویسی (آفر ویژه ثبت نام قبل از افزایش قیمت 🔥)
۰ ثانیه
۰ دقیقه
۰ ساعت
۶ mohammad dadkhah
ایجاد topicObserver در API لاراول
جامعه لاراول ایجاد شده در ۲۴ آذر ۱۴۰۰

سلام

مشابه این جلسه را اومد در API با Authorization jwt انجام دادهم

در ایجاد سطر جدید برای userstate با ایجاد هر یوزر مشکلی پیش نمی‌آیید اما با ایجاد هر تاپیک فیلد count_topic جدول userstate اضافه نمی‌شود


namespace App\\Observers;
use App\\article;
class ArticleObserver
{
    /**
     * Handle the article "created" event.
     *
     * @param  \\App\\article  $article
     * @return void
     */
    public function created(article $article)
    {
        $article->users->incrementArticle();
    }
}
hasMany(User::class);
    }
    public function add($request)
    {
        try {
            $this::create([
                'user_id'=>auth('api')->user()->id,
                'title'=>$request->title,
                'description'=>$request->description,
                'image'=>$request->image
            ]);
        }catch (\\Exception $e){
            return response()->json(['message' => 'error']);
        }
    }

namespace App\\Providers;
use App\\Article;
use App\\Observers\\ArticleObserver;
use App\\Observers\\UserObserver;
use App\\User;
use Illuminate\\Support\\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Article::observe(ArticleObserver::class);
        User::observe(UserObserver::class);
    }
}
namespace App;
use App\\Http\\Resources\\userCollection;
use App\\Services\\Comment\\Traits\\Commentable;
use App\\Services\\User\\ValidateUser;
use http\\Env\\Request;
use Illuminate\\Contracts\\Auth\\MustVerifyEmail;
use Illuminate\\Foundation\\Auth\\User as Authenticatable;
use Illuminate\\Notifications\\Notifiable;
use Illuminate\\Support\\Facades\\DB;
use Illuminate\\Support\\Facades\\Hash;
use Tymon\\JWTAuth\\Contracts\\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
    use Notifiable ;
   /*  use Commentable;*/
    const NAME_MIN_LENGTH = 5;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'image'
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    /*  protected $hidden = [
          'password', 'remember_token',
      ];*/
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
    public function userState()
    {
       return $this->hasOne(UserState::class);
    }
    public function incrementArticle()
    {
        $this->userState->count_article++;
        $this->userState->save();
    }

سوال ام این است که فیلد count_article در پایگاه داده با ایجاد هر سوال به مقدار قبلی اش اضافه نمی‌شود.

mohammad dadkhah ۲۴ آذر ۱۴۰۰، ۱۱:۴۵
class CreateUserStatesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_states', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('user_id');
            $table->integer('count_article')->default(0);
            $table->integer('count_comment')->default(0);
            $table->integer('count_hashtag')->default(0);
            $table->integer('count_like_article')->default(0);
            $table->integer('count_like_comment')->default(0);
            $table->integer('count_follower')->default(0);
            $table->integer('count_following')->default(0);
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
mohammad dadkhah ۲۴ آذر ۱۴۰۰، ۱۱:۴۸

این هم مدل userstate


namespace App;
use Illuminate\\Database\\Eloquent\\Model;
class UserState extends Model
{
    protected $fillable=['user_id','count_article','count_comment','count_hashtag',
     'count_like_article','count_like_comment','count_follower','count_following'];
}
mohammad dadkhah ۲۴ آذر ۱۴۰۰، ۱۱:۴۹

با dd گرفتن متوجه شدم به این تابع نمی‌رسد یعنی dd را نشان نمی‌دهد ولی پست در پایگاه داده ثبت شده است. و طبع فیلد count_article هم تغییر نکرده

    
namespace App;
use App\\Http\\Resources\\userCollection;
use App\\Services\\Comment\\Traits\\Commentable;
use App\\Services\\User\\ValidateUser;
use http\\Env\\Request;
use Illuminate\\Contracts\\Auth\\MustVerifyEmail;
use Illuminate\\Foundation\\Auth\\User as Authenticatable;
use Illuminate\\Notifications\\Notifiable;
use Illuminate\\Support\\Facades\\DB;
use Illuminate\\Support\\Facades\\Hash;
use Tymon\\JWTAuth\\Contracts\\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
    use Notifiable ;
   /*  use Commentable;*/
    const NAME_MIN_LENGTH = 5;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'image'
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    /*  protected $hidden = [
          'password', 'remember_token',
      ];*/
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
    public function userState()
    {
       return $this->hasOne(UserState::class);
    }
    public function incrementArticle()
    {
dd('dd');
        $this->userState->count_article++;
        $this->userState->save();
    }
}


mohammad dadkhah ۲۴ آذر ۱۴۰۰، ۱۲:۰۵

سلام مشکل ام حل شد متاسفانه با کلی دقت بازهم اشتباه می‌کتم اشتباه بنده اون relation بین user و article است

mohammad dadkhah ۲۴ آذر ۱۴۰۰، ۱۷:۱۷

سلام و وقت بخیر، خوشحالم که تونستید مشکل رو حل کنید.

دقیقا مشکلی که خیلی از دانشجویان دارن همین مبحث دقت نکردن هستش، و البته این مشکل رو میشه با یادگیری دیباگ کردن بهتر برنامه تا حدود زیادی پوشش داد.

مهرداد سامی ۲۶ آذر ۱۴۰۰، ۱۴:۲۱