Ad

How To Save A User To A Post When It Is Created

- 1 answer

I am trying to display the name of the user that made a post in octobercms but haven't gotten it to work yet. This is what I have already done. I have extended the userModel in the boot method of my plugin.

  public function boot()
{ 
         User::extend(function($model){
        $model->hasMany['adverts'] = ['Corymillz\Adverts\Models\Advert'];
    }); 
}

and in my main plugin I have

public $belongsTo = [ 
'user' => [
'RainLab\User\Models\User', 'key' => 'user_id']
];

In my twig template i am trying something like {{ ads.user.name }} for the specific user. This works correctly but how to i attach a post to a logged in user. Don't know if i am asking the question right. When a logged in user makes a post. His name should appear with it using {{ ads.user.name}} instead of me manually adding a user to a post in the backend

With user_id in my advert table I have tried adding this to my form .php file but returns an error

$advert->user_id = Auth ::user()->id; $advert->save();

Ad

Answer

Solved it by adding use Auth;

at the top of the file and

$advert->user_id = Auth ::user()->id; $advert->save();

Ad
source: stackoverflow.com
Ad