Skip to content

Instantly share code, notes, and snippets.

@mfsiat
Last active June 25, 2019 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfsiat/cf02fca2e6e76af5a098f86ab2f634ae to your computer and use it in GitHub Desktop.
Save mfsiat/cf02fca2e6e76af5a098f86ab2f634ae to your computer and use it in GitHub Desktop.
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
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-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment