belykia
166
4
Laravel

allow only the user to see his edit and delete ??

Posted 1 year ago by belykia

Hello everybody :

I m a beginner in Laravel , i made a form with 5 fields , that is related to a table posts , and i have a users table that's related to the login .the posts table is :

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('asnumber');
            $table->string('peeringrs')->nullable();
            $table->string('peeringdb')->nullable();
            $table->string('asset')->nullable();
            $table->string('contact');
            $table->integer('user_id');
            $table->timestamps();
        });

the users table is :

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

in order to leave only the user to see his edit i , i make the relation one to many , so in the Post.php model i wrote :

class Post extends Model
{
    protected $guarded = [];

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

then in the User.php model i wrote :

{
    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',
    ];
    public function Post(){
      return $this->hasMany('App\Post','id', 'user_id');
    }
}

eventually in the the controller PostController.php in order to give the id in the users table to the user_id in the posts table i added :

public function store(Request $request)
    {
          $request->validate([
    'ASNumber' => 'required|unique:posts|max:255',
    'choice' => 'nullable|max:255',
        'peeringDB' => 'nullable|max:255',
    'asset' => 'nullable|max:255',
'Contact' => 'required|email',
]);
$post_data = [
    'asnumber' => $request->input('ASNumber'),
    'peeringrs' => $request->input('choice'),
    'peeringdb' => $request->input('peeringDB'),
    'asset' => $request->input('asset'),
    'contact' => $request->input('Contact'),
    'user_id'=> Auth::id(),
];
Post::create($post_data);
    Session::flash('success', 'Form succesfully saved!');
   return redirect('save');
    }

so what s should i do to show for each user only his contents, i mean to update only for his own contents .

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.