Laravel checkbox複数一括処理の書き方

view側でinput type=”checkbox” class=”checkBoxes” name=”checkBoxArray[]” value=”{{$photo->id}}” と書いて、配列でcontrollerに送り、Photo::findOrFail($request->checkBoxArray)で受け取る。

Route

Route::delete('/delete/media', 'AdminMediasController@deleteMedia');
@if($photos)

		<form action="/delete/media" method="post" class="form-inline">
{{csrf-field()}}
			{{method_field('delete')}}
			<div class="form-group">
				<select name="checkBoxArray" id="" class="form-control">
					<option value="delete">Delete</option>
				</select>
			</div>
			<div class="form-group">
				<input type="submit" class="btn btn-primary">
			</div>

		<table class="table table-striped">
			<thead>
			<tr>
			  <th><input type="checkbox" id="options"></th>
			  <th>Id</th>
			  <th>Name</th>
			  <th>Created date</th>
			</tr>
			</thead>
			<tbody>
				@foreach($photos as $photo)
				<tr>
				  <th><input type="checkbox" class="checkBoxes" name="checkBoxArray&#91;&#93;" value="{{$photo->id}}"></th>
				  <td>{{$photo->id}}</td>
				  <td><img height="50" src="/{{$photo->file}}"></td>
				  <td>{{$photo->created_at ? $photo->created_at : 'no date'}}</td>
				  <td>
				  	{!! Form::open(['method'=>'DELETE', 'action'=>['AdminMediasController@destroy', $photo->id]]) !!}
			        {{ csrf_field()}}
			        
			        <div class="form-group">
			            {!! Form::submit('Delete', ['class'=>'btn btn-danger']) !!}
			        </div>
			        {!! Form::close() !!}

				  </td>
				</tr>
				@endforeach			
			</tbody>
		</table>

		</form>
		@endif
public function deleteMedia(Request $request){

        if(isset($request->delete_single)){
            $this->destroy($request->photo);
            return redirect()->back();
        }

        if(isset($request->delete_all) && !empty($request->checkBoxArray)){
            $photos = Photo::findOrFail($request->checkBoxArray);
            foreach($photos as $photo){
                $photo->delete();
            }
            return redirect()->back();
        } else {
            return redirect()->back();
        }

        
    }
	$(document).ready(function(){

	$('#options').click(function(){
		if(this.checked){
			$('.checkBoxes').each(function(){
				this.checked = true;
			});
		} else {
			$('.checkBoxes').each(function(){
				this.checked = false;
			});
		}
	});
});

一括削除はUX上、あまり宜しくないと思ったが、よく考えたら複数一括処理はselectで一括ステータス変更などにも使えるので、書き方自体は覚えておきたい。

LaravelでtinyMCE & filemanagerの使い方

tinyMCEだと、textareaで文字の装飾はもちろん画像の挿入ができる

### viewの作成
views/includes/tinyeditor.blade.php

<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>tinymce.init({selector:'textarea'});</script>

posts/create.blade.php

@extends('layouts.admin')

@section('content')

    @include('includes.tinyeditor')
...

### filemanager install
https://unisharp.github.io/laravel-filemanager/installation

$ php composer.phar require unisharp/laravel-filemanager
$ php composer.phar require intervention/image

Unisharp\Laravelfilemanager\LaravelFilemanagerServiceProvider::class,
        Intervention\Image\ImageServiceProvider::class,

'Image' => Intervention\Image\Facades\Image::class,

$ php artisan vendor:publish –tag=lfm_config
$ php artisan vendor:publish –tag=lfm_public

### tinyeditor.blade.php

<script src="//cdn.tinymce.com/4/tinymce.min.js"></script>
<script>
  var editor_config = {
    path_absolute : "/",
    selector: "textarea",
    plugins: [
      "advlist autolink lists link image charmap print preview hr anchor pagebreak",
      "searchreplace wordcount visualblocks visualchars code fullscreen",
      "insertdatetime media nonbreaking save table contextmenu directionality",
      "emoticons template paste textcolor colorpicker textpattern"
    ],
    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
    relative_urls: false,
    file_browser_callback : function(field_name, url, type, win) {
      var x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
      var y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;

      var cmsURL = editor_config.path_absolute + 'laravel-filemanager?field_name=' + field_name;
      if (type == 'image') {
        cmsURL = cmsURL + "&type=Images";
      } else {
        cmsURL = cmsURL + "&type=Files";
      }

      tinyMCE.activeEditor.windowManager.open({
        file : cmsURL,
        title : 'Filemanager',
        width : x * 0.8,
        height : y * 0.8,
        resizable : "yes",
        close_previous : "no"
      });
    }
  };

  tinymce.init(editor_config);
</script>

### config
lfm.php

'base_directory' => 'public',
'images_folder_name' => 'images',

### view
post.blade.php

<p>{!! $post->body !!}</p>

{{$post->body}}だと画像が表示されないので注意が必要
殆ど公式に書いてあるので、公式との闘いになりそう

Laravel upgradeの基本的な進め方

– まずlogin, authから確認
– upgrade後に基本動作から試していく
– packageもlaravelのヴァージョンに依存関係がある為、composer.jsonも必ず確認する(laravel collective)

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

$ php artisan route:list;

https://github.com/laravel-shift/laravel-5.3/blob/master/app/Http/Controllers/Auth/LoginController.php
Authフォルダの下にcontroller fileを追加
LoginController.php
ResetPasswordController.php
RegisterController.php
ForgotPasswordController.php

web.php

Route::auth();
Route::get('/logout', 'Auth\LoginController@logout');

LoginController.php

protected $redirectTo = '/';

web.php

Route::group(['middleware'=>'admin'], function(){

	Route::get('/admin', function(){
		return view('admin.index');
	});

	Route::resource('admin/users', 'AdminUsersController',['names'=>[
		'index'=>'admin.users.index',
		'create'=>'admin.users.create',
		'store'=>'admin.users.store',
		'edit'=>'admin.users.edit',
	]]);
	Route::resource('admin/posts', 'AdminPostsController', ['names'=>[
		'index'=>'admin.posts.index',
		'create'=>'admin.posts.create',
		'store'=>'admin.posts.store',
		'edit'=>'admin.posts.edit',
	]]);	
	Route::resource('admin/categories', 'AdminCategoriesController', ['names'=>[
		'index'=>'admin.categories.index',
		'create'=>'admin.categories.create',
		'store'=>'admin.categories.store',
		'edit'=>'admin.categories.edit',
	]]);	
	Route::resource('admin/media', 'AdminMediasController', ['names'=>[
		'index'=>'admin.media.index',
		'create'=>'admin.media.create',
		'store'=>'admin.media.store',
		'edit'=>'admin.media.edit',
	]]);

	Route::resource('admin/comments', 'PostCommentsController', ['names'=>[
		'index'=>'admin.comments.index',
		'create'=>'admin.comments.create',
		'store'=>'admin.comments.store',
		'edit'=>'admin.comments.edit',
	]]);
	Route::resource('admin/comments/replies', 'CommentRepliesController', ['names'=>[
		'index'=>'admin.replies.index',
		'create'=>'admin.replies.create',
		'store'=>'admin.replies.store',
		'edit'=>'admin.replies.edit',
	]]);
});

AdminUsersController
lists->pluckに変更

public function create()
    {
        //
        $roles = Role::pluck('name','id')->all();
        return view('admin.users.create', compact('roles'));
    }
$categories = Category::pluck('name', 'id')->all();

composer.json

"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.3.*",
        "laravelcollective/html": "5.3.*"
    },

Middleware: kernel.php

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\Admin::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ];

$ php composer.phar require cviebrock/eloquent-sluggable:^4.0

$ php artisan vendor:publish –provider=”Cviebrock\EloquentSluggable\ServiceProvider”

フレームワークのアップデートは、アップデートに伴う変更点を一つ一つ潰していくのかと思っていましたが、そうではなく、まずupgradeして、挙動を一つ一つ確認しながらエラーを潰していく。発想が真逆でした。道理で、凄い大変そうにみえたわけだ。。

ただし、マイクロアプリケーションなら比較的すぐ終わりそうですが、大規模アプリケーションだと、テスト工数が結構かかりそうです。

Laravel Upgrade

– upgrade時には公式のドキュメントを読むと同時に、参考記事を探し、主な変更点を確認する
– 新しいversionをインストールして、folder構成の違いを確認する
– composer updateでエラーが出た場合は、コードを修正する

$ php artisan –version

### composer.jsonでupdate

"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.3.*",
        "laravelcollective/html": "^5.2.0"
    },

### composer update
$ php composer.phar update

app/Providers/EventServiceProvider.php

public function boot()
    {
        parent::boot();

        //
    }

app/Providers/RouteServiceProvider.php

use Illuminate\Support\Facades\Route;
public function boot()
    {
        //

        parent::boot();
    }
public function map()
    {
        $this->mapWebRoutes();

        //
    }
protected function mapWebRoutes()
    {
        Route::group([
            'namespace' => $this->namespace, 'middleware' => 'web',
        ], function ($router) {
            require base_path('routes/web.php');
        });
    }

routes/web.php

Route::get('/', function () {
    return view('welcome');
});

routes/console.php

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->describe('Display an inspiring quote');

routes/api.php

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

$ php composer.phar update
$ php artisan –version
$ php artisan route:list;

技術負債は後々問題になりやすいので、「じゃー新しいの作る?」となってしまわないよう、設計時によく考えておかないといけない。

Gravatarとは?

https://ja.gravatar.com/support/what-is-gravatar/

Model User.php

public function getGravatarAttribute(){
        $hash = md5(strtolower(trim($this->attribute['email'])));
        return "http://www.gravatar.com/avatar/$hash";
    }

Viewのimg srcでAuth::user()->gravatar()と書くと、gravatarに登録した画像が表示される

公式ドキュメント
https://ja.gravatar.com/site/implement/images/
https://www.gravatar.com/avatar/${hashedUrl}

あんまり使ってるの見たことないけど、アバターのマイナンバーみたいな発想は面白い

Laravel ページングの書き方

グローバルのrender()を使います。

AdminPostsController.php

public function index()
    {
        // $posts = Post::all();
        $posts = Post::paginate(4);
        return view('admin.posts.index', compact('posts'));
    }

posts/index.blade.php

<div class="row">
		<div class="col-sm-6 col-sm-offset-5">
			{{$posts->render()}}
		</div>
    </div>

URLに自動的に?page=${n} が付与されます。

super amazing! あれほどページングべた書きに苦労したのは一体何だったんだ

Laravel return redirect()->back();

Controllerでは、viewの指定なしにredirect()->back();と書ける。

PostCommentsController.php

 public function index(){
    	$comments = Comment::all();
    	return view('admin.comments.index', compact('comments'));
    }

admin/comments/index.blade.php

@if($comments)
	<h1>Comments</h1>
	<table class="table table-striped">
		<thead>
		<tr>
		  <th>Id</th>
		  <th>Author</th>
		  <th>Email</th>
		  <th>Body</th>
		  <th>Post</th>
		</tr>
		</thead>
		<tbody>
		
			@foreach($comments as $comment)
			<tr>
			  <td>{{$comment->id}}</td>
			  <td>{{$comment->author}}</td>
			  <td>{{$comment->email}}</td>
			  <td>{{$comment->body}}</td>
			  <td><a href="{{route('home.post',$comment->post_id)}}">View Post</td>
			  <td>
			  	@if($comment->is_active == 1)
			  			{!! Form::open(['method'=>'PATCH', 'action'=>['PostCommentsController@update', $comment->id]]) !!}
					        {{ csrf_field()}}
					        <input type="hidden" name="is_active" value="0">

					        <div class="form-group">
					            {!! Form::submit('Un-approve', ['class'=>'btn btn-info']) !!}
					        </div>
        				{!! Form::close() !!}
						
			  	@else
						{!! Form::open(['method'=>'PATCH', 'action'=>['PostCommentsController@update', $comment->id]]) !!}
					        {{ csrf_field()}}
					        <input type="hidden" name="is_active" value="1">

					        <div class="form-group">
					            {!! Form::submit('Approve', ['class'=>'btn btn-info']) !!}
					        </div>
        				{!! Form::close() !!}

			  	@endif
			  </td>
			  <td>
			  	{!! Form::open(['method'=>'DELETE', 'action'=>['PostCommentsController@destroy', $comment->id]]) !!}
			        {{ csrf_field()}}

			        <div class="form-group">
			            {!! Form::submit('Delete', ['class'=>'btn btn-danger']) !!}
			        </div>
				{!! Form::close() !!}

			  </td>
			</tr>
			@endforeach
		
		</tbody>
	</table>
	@else
	<h1 class="text-center">No Comments</h1>
		
	@endif

PostCommentController.php

public function update(Request $request, $id){
    	Comment::findOrFail($id)->update($request->all());
    	return redirect('/admin/comments');
    }

    public function destroy($id){
    	Comment::findOrFail($id)->delete();
    	return redirect()->back();
    }

Post/index.blade.php

<td><a href="{{route('home.post', $post->id)}}">View Post</td>
			  <td><a href="{{route('admin.comments.show', $post->id)}}">View Comments</td>

Post.php

public function comments(){
        return $this->hasMany('App\Comment');
    }

Route

Route::group(['middleware'=>'auth'], function(){

		Route::post('comment/reply', 'CommentRepliesController@createReply');
});

post.blade.php

@if($comments)
                    @foreach($comments as $comment)
                <!-- Comment -->
                <div class="media">
                    <a class="pull-left" href="#">
                        <img class="media-object" src="http://placehold.it/64x64" alt="">
                    </a>
                    <div class="media-body">
                        <h4 class="media-heading">{{$comment->author}}
                            <small>{{$comment->created_at->diffForhumans()}}</small>
                        </h4>
                        {{$comment->body}}

                        @if($comment->replies)
                            @foreach($comment->replies as $reply)
                        <div class="nested-comment media">
                            <a class="pull-left" href="#">
                                <img class="media-object" src="http://placehold.it/64x64" alt="">
                            </a>
                            <div class="media-body">
                                <h4 class="media-heading">{{$reply->author}}
                                    <small>{{$reply->created_at->diffForhumans()}}</small>
                                </h4>
                                {{$reply->body}}
                            </div>

                            {!! Form::open(['method'=>'POST', 'action'=>'CommentRepliesController@store']) !!}
                                {{ csrf_field()}}

                                <input type="hidden" name="comment_id" value="{{$comment->id}}">
                         
                                <div class="form-group">
                                    {!! Form::label('body', 'Body') !!}
                                    {!! Form::textarea('body', null, ['class'=>'form-control', 'rows'=>1]) !!}
                                </div>                                
                                <div class="form-group">
                                    {!! Form::submit('Submit', ['class'=>'btn btn-primary']) !!}
                                </div>
                            {!! Form::close() !!}

                        </div>
                            @endforeach
                        @endif

post.blade.php

<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
    <script>
        $(".comment-reply-container .toggle-reply").click(function(){
            $(this).next().slideToggle("slow");
        });
    </script>

replies/show.blade.php

@section('content')
	
	@if($replies)
	<h1>replies</h1>
	<table class="table table-striped">
		<thead>
		<tr>
		  <th>Id</th>
		  <th>Author</th>
		  <th>Email</th>
		  <th>Body</th>
		  <th>Post</th>
		</tr>
		</thead>
		<tbody>
		
			@foreach($replies as $reply)
			<tr>
			  <td>{{$reply->id}}</td>
			  <td>{{$reply->author}}</td>
			  <td>{{$reply->email}}</td>
			  <td>{{$reply->body}}</td>
			  <td><a href="{{route('home.post',$reply->comment->post->id)}}">View Post</td>
			  <td>
			  	@if($reply->is_active == 1)
			  			{!! Form::open(['method'=>'PATCH', 'action'=>['CommentRepliesController@update', $reply->id]]) !!}
					        {{ csrf_field()}}
					        <input type="hidden" name="is_active" value="0">

					        <div class="form-group">
					            {!! Form::submit('Un-approve', ['class'=>'btn btn-success']) !!}
					        </div>
        				{!! Form::close() !!}
						
			  	@else
						{!! Form::open(['method'=>'PATCH', 'action'=>['CommentRepliesController@update', $reply->id]]) !!}
					        {{ csrf_field()}}
					        <input type="hidden" name="is_active" value="1">

					        <div class="form-group">
					            {!! Form::submit('Approve', ['class'=>'btn btn-info']) !!}
					        </div>
        				{!! Form::close() !!}

			  	@endif
			  </td>
			  <td>
			  	{!! Form::open(['method'=>'DELETE', 'action'=>['CommentRepliesController@destroy', $reply->id]]) !!}
			        {{ csrf_field()}}

			        <div class="form-group">
			            {!! Form::submit('Delete', ['class'=>'btn btn-danger']) !!}
			        </div>
				{!! Form::close() !!}

			  </td>
			</tr>
			@endforeach
		</tbody>
	</table>
	
	@else
	
		<h1 class="text-center">No replies</h1>
	@endif
	
@stop

comments/index.blade.php

<td><a href="{{route('admin.comments.replies.show', $comment->id)}}">View Replies</a></td>

CommentRepliesController.php

use App\Comment;
public function show($id)
    {
        //
        $comment = Comment::findOrFail($id);
        $replies = $comment->replies;
        return view('admin.comments.replies.show', compact('replies'));
    }

public function update(Request $request, $id)
    {
        //
        CommentReply::findOrFail($id)->update($request->all());

        return redirect()->back();
    }
public function destroy($id)
    {
        //
        CommentReply::findOrFail($id)->delete();

        return redirect()->back();
    }

Laravel Collectiveでのhiddenの扱い

hiddenはinput type=”hidden”で普通に書く

/resources/views/comments/index.blade.php
/resources/views/comments/replies/index.blade.php

Route

Route::group(['middleware'=>'admin'], function(){
	...//
	Route::resource('admin/comments', 'PostCommentsController');
	Route::resource('admin/comments/replies', 'CommentRepliesController');
});

$ php artisan make:model Comment -m
$ php artisan make:model CommentReply -m

comment migration file

Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned()->index();;
            $table->integer('is_active')->default(0);
            $table->string('author');
            $table->string('email');
            $table->text('body');
            $table->timestamps();

            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        });

comment replies migration file

Schema::create('comment_replies', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('comment_id')->unsigned()->index();
            $table->integer('is_active')->default(0);
            $table->string('author');
            $table->string('email');
            $table->text('body');
            $table->timestamps();

            $table->foreign('comment_id')->references('id')->on('comments')->onDelete('cascade');
        });

Model: Post.php

public function comments(){
        return $this->hasMany('App\Post');
    }

Comment.php

protected $fillable = [
		'post_id',
		'author',
		'email',
		'body',
		'is_active'
	];

    public function replies(){
    	return $this->hasMany('App\CommentReply');
    }

CommentReply.php

protected $fillable = [
		'comment_id',
		'author',
		'email',
		'body',
		'is_active'
	];

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

$ php artisan make:controller –resource PostCommentController
$ php artisan make:controller –resource CommentRepliesController

admin.blade.php

<li>
                        <a href="#"><i class="fa fa-wrench fa-fw"></i> Posts<span class="fa arrow"></span></a>
                        <ul class="nav nav-second-level">
                            <li>
                                <a href="{{route('admin.posts.index')}}">All Posts</a>
                            </li>

                            <li>
                                <a href="{{route('admin.posts.create')}}">Create Post</a>
                            </li>

                            <li>
                                <a href="{{route('admin.comments')}}">All Comments</a>
                            </li>

                        </ul>
                        <!-- /.nav-second-level -->
                    </li>

PostCommentsController.php

public function index(){
    	return view('admin.comments.index');
    }

route

Route::get('/post/{id}', ['as'=>'home.post','uses'=>'AdminPostsController@post']);

post.blade.php

<h1>{{$post->title}}</h1>

                <!-- Author -->
                <p class="lead">
                    by <a href="#">{{$post->user->name}}</a>
                </p>
                <hr>
               <!-- Date/Time -->
                <p><span class="glyphicon glyphicon-time"></span> Posted {{$post->created_at->diffForhumans()}}</p>
                <hr>
                <!-- Preview Image -->
                <img class="img-responsive" src="{{$post->photo ? '/' . $post->photo->file : ''}}" alt="">
                <hr>
                <!-- Post Content -->
                <p>{{$post->body}}</p>
                <hr>

 <h4>Leave a Comment:</h4>
                    
                    {!! Form::open(['method'=>'POST', 'action'=>'PostCommentsController@store']) !!}
				        {{ csrf_field()}}
				 
				        <div class="form-group">
				            {!! Form::label('body', 'Body') !!}
				            {!! Form::textarea('body', null, ['class'=>'form-control', 'rows'=>3]) !!}
				        </div>				        
				        <div class="form-group">
				            {!! Form::submit('Submit Comment', ['class'=>'btn btn-primary']) !!}
				        </div>
				    {!! Form::close() !!}                   
                </div>

post.blade.php

 {!! Form::open(['method'=>'POST', 'action'=>'PostCommentsController@store']) !!}
				        {{ csrf_field()}}

				        <input type="hidden" name="post_id" value="{{$post->id}}">
				 
				        <div class="form-group">
				            {!! Form::label('body', 'Body') !!}
				            {!! Form::textarea('body', null, ['class'=>'form-control', 'rows'=>3]) !!}
				        </div>				        
				        <div class="form-group">
				            {!! Form::submit('Submit Comment', ['class'=>'btn btn-primary']) !!}
				        </div>
				    {!! Form::close() !!} 

@if(Sessin::has('comment_message'))
						{{session('comment_message')}}
                @endif

PostCommentsController.php

use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use App\User;
use App\Photo;
use App\Comment;

public function store(Request $request){

    	$user = Auth::user();

    	$data = [
    		'post_id' => $request->post_id,
    		'author' => $user->name,
    		'email' => $user->email,
    		'body' => $request->body
    	];
    	Comment::create($data);
    	$request->session()->flash('comment_message','Your message has been submitted and is waiting moderation' );

    	return redirect()->back();
    }

hiddenはinput type=”hidden”で書くという事は、フォームの確認ページがある場合、そこは全てcollectiveは使わずに書く、ということになりますね。

Laravelでdropzoneの使い方

– htmlべだ書と同様、ヘッダにdropzoneのcss、フッタにjsを読み込ませればいい。
– dropzoneはfileのnameがglobalで’file’なので、controllerで受け取るときは、$request->file(‘file’);と書く。

/resources/views/media/index.blade.php

@if($photos)
		<table class="table table-striped">
			<thead>
			<tr>
			  <th>Id</th>
			  <th>Name</th>
			  <th>Created date</th>
			</tr>
			</thead>
			<tbody>
				@foreach($photos as $photo)
				<tr>
				  <td>{{$photo->id}}</td>
				  <td><img height="50" src="/{{$photo->file}}"></td>
				  <td>{{$photo->created_at ? $photo->created_at : 'no date'}}</td>
				</tr>
				@endforeach			
			</tbody>
		</table>
		@endif

$ php artisan make:controller AdminMediasController

route.php

Route::group(['middleware'=>'admin'], function(){
	Route::resource('admin/users', 'AdminUsersController');
	Route::resource('admin/posts', 'AdminPostsController');	
	Route::resource('admin/categories', 'AdminCategoriesController');	
	Route::resource('admin/media', 'AdminMediasController');
});

layouts/admin.blade.php

<li>
                                <a href="{{route('admin.medias.index')}}">All Media</a>
                            </li>
s
                            <li>
                                <a href="{{route('admin.medias.create')}}">Upload Media</a>
                            </li>

AdminMediasController.php

 public function index(){
    	$photos = Photo::all();
    	return view('admin.media.index', compact('photos'));
    }
 public function create(){
    	return view('admin.media.create');
    }

https://www.dropzonejs.com/

create.blade.php

@extends('layouts.admin')

@section('styles')
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css">
@stop

@section('content')

		<h1>Upload Media</h1>

		{!! Form::open(['method'=>'POST', 'action'=>'AdminMediasController@store','class'=>'dropzone', 'files'=>true]) !!}
        {{ csrf_field()}}
      
        <div class="form-group">
            {!! Form::submit('Create Post', ['class'=>'btn btn-primary']) !!}
        </div>
    {!! Form::close() !!}
@stop

@section('scripts')
	<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>
@stop

AdminMediasController.php

public function store(Request $request){
    	$file = $request->file('file');
    	$name = time(). $file->getClientOriginalName();
    	$file->move('images',  $name);
    	Photo::create(['file'=>$name]);
    }
public function destroy($id){
    	$photo = Photo::findOrFail($id);
    	unlink(public_path(). '/'. $photo->file);

    	$photo->delete();
    	return redirect('/admin/media');
    }

index.blade.php

<tbody>
				@foreach($photos as $photo)
				<tr>
				  <td>{{$photo->id}}</td>
				  <td><img height="50" src="/{{$photo->file}}"></td>
				  <td>{{$photo->created_at ? $photo->created_at : 'no date'}}</td>
				  <td>
				  	{!! Form::open(['method'=>'DELETE', 'action'=>['AdminMediasController@destroy', $photo->id]]) !!}
			        {{ csrf_field()}}
			        
			        <div class="form-group">
			            {!! Form::submit('Delete', ['class'=>'btn btn-danger']) !!}
			        </div>
			        {!! Form::close() !!}

				  </td>
				</tr>
				@endforeach			
			</tbody>

対象ページのみcssやjsをインクルードさせたい時は、ヘッダとフッタのsectionに追加で書き込めば良い😺

Laravel index, create, update, delete

index, create, update, deleteの順番に作ります。
最初にindexで表示項目のデータをDBに入れておく。

$ php artisan make:controller –resource AdminCategoriesController

Route::group(['middleware'=>'admin'], function(){
	Route::resource('admin/users', 'AdminUsersController');
	Route::resource('admin/posts', 'AdminPostsController');	
	Route::resource('admin/categories', 'AdminCategoriesController');	
});

AdminCategoriesController.php

public function index()
    {
        $categories = Category::all();
        return view('admin.categories.index', compact('categories'));
    }

layouts/admin.blade.php

<li>
                                <a href="{{route('admin.categories.index')}}">All Categories</a>
                            </li>

                            <li>
                                <a href="{{route('admin.categories.create')}}">Create Category</a>
                            </li>

categories/index.blade.php

<h1>Categories</h1>	

	<div class="col-sm-6">
		{!! Form::open(['method'=>'POST', 'action'=>'AdminCategoriesController@store']) !!}
        {{ csrf_field()}}
	        <div class="form-group">
	            {!! Form::label('name', 'Name') !!}
	            {!! Form::text('name', null, ['class'=>'form-control']) !!}
	        </div>
	        <div class="form-group">
	            {!! Form::submit('Create Category', ['class'=>'btn btn-primary']) !!}
	        </div>
	    {!! Form::close() !!}

	</div>

	<div class="col-sm-6">
		
		@if($categories)
		<table class="table table-striped">
			<thead>
			<tr>
			  <th>Id</th>
			  <th>Category</th>
			  <th>Created date</th>
			</tr>
			</thead>
			<tbody>
				@foreach($categories as $category)
				<tr>
				  <td>{{$category->id}}</td>
				  <td>{{$category->name}}</td>
				  <td>{{$category->created_at ? $category->created_at->diffForhumans() : 'no date'}}</td>
				</tr>
				@endforeach			
			</tbody>
		</table>
		@endif
	</div>

AdminCategoriesController.php

public function store(Request $request)
    {
        //
            Category::create($request->all());

            return redirect('/admin/categories');
    }

public function edit($id)
    {
        //
        $category = Category::findOrFail($id);
        return view('admin.categories.edit', compact('category'));
    }

view: index.blade.php

<tr>
				  <td>{{$category->id}}</td>
				  <td><a href="{{route('admin.categories.edit', $category->id)}}">{{$category->name}}</a></td>
				  <td>{{$category->created_at ? $category->created_at->diffForhumans() : 'no date'}}</td>
				</tr>

AdminCategoriesController.php

public function destroy($id)
    {
        Category::findOrFail($id)->delete();
        return view('/admin/categories');
    }

Keep going!
気分転換に馬喰町のロボットコーヒーでも行くかな☕