sergey
5/9/2018 - 11:26 AM

Simple CRUD laravel

Simple CRUD laravel in controller

<?php

//Create
public function store (Request $request) {
  
  //here we use mass assignment and in model you need to define fillable variable
  // в моделе protected $fillable = ['name', 'email', 'password'];
  
  Post::create($request->all()); 
  
  //OR
  
  
  //здесь валидация сначало
  Post::create($request(['title', 'body'])); // если не ипортировали в функцию$request вот так Request $request, то может писать $request без знака $
  
  //OR
  
  $post = new Post;
  $post->title = request('postname'); 
  $post->body = request('postbody');  
  $post->save(); 
  
}

//Read
public function index()  {
  
  $tags = Tag::all();
         
         //OR
         
  $posts = DB::table('posts')->orderBy('created_at', 'desc')->paginate(3);
         
         //OR
         
  $category = Category::find($id);
         
         //OR
         
  $post = Post::where('slug', $id)->first();
         
         //OR
}


//Update

public function update($id) {
  
  $post = Post::find($id);
  if ($request->has('postname')) {
    $post->title = request('postname');
  }
  $post->body = request('postbody');  
  $post->save();
}

//Delete 
public function destroy($id) {
  
  $post = Post::find($id);
  $post->delete();
			    
    }
?>