mfsiat
6/25/2019 - 11:15 AM

Data Store function under specific user_id

Suppose we have a blog and we want to create post under a specific id to do that we need to validate our id using login and on the function we create a new object and under that object we put our data and to specify the specific id we put an user id which is authenticated at the time of login. we just create our post under that id.

    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'body' => 'required'
        ]);

        // Create Post
        $post = new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->user_id = auth()->user()->id;
        $post->save();

        return redirect('/posts')->with('success', 'Post Created');
    }
class Post extends Model
{
    // Table Name 
    protected $table = 'posts';

    // primary key 
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;

    public function user(){
        return $this->belongsTo('App\User');
    }
}

<!--this is a model it shows that a post belongs to an user-->
class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * 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 posts(){
        return $this->hasMany('App\Post');
    }
}
<!--this is also a model -->
<!--this shows us that an user can have many posts -->
<!--by the function posts-->