controllerから変数をviewに渡す

controller

public function contact(){

        $people = ['Edwin', 'Jose', 'James', 'Peter', 'maria'];
        return view('contact', compact('people'));
    }

contact.blade.php

<h1>Contact Page</h1>
	@if (count($people))
	 <ul>
	 @foreach($people as $person)
	 	<li>{{$person}}</li>
	 @endforeach
	 </ul>
	@endif

bladeの中での書き方が特殊なので、慣れるまで少し時間がかかるやもしれません。

Laravelでcontrollerからviewにデータを渡す

変数の$idとその名前’id’を一緒に渡す

public function show_post($id){
        return view('post')->with('id', $id);
    }

post.blade.php

<div class="container">
		<h1>Post {{ $id }}</h1>
	</div>	

databaseから値を持ってくる際は、変数をfunctionの中で定義するが、routingの場合も仕組みは同じ
with(‘id’, $id)は、compact(‘id’)とも書ける

return view('post', compact('id'));

表示は、->with(‘id’, $id) と同じ

複数渡す場合

Route::get('post/{id}/{name}/{password}', 'PostsController@show_post');
public function show_post($id, $name, $password){
        // return view('post')->with('id', $id);
        return view('post', compact('id','name','password'));
    }
<div class="container">
		<h1>Post {{ $id }} {{ $name }} {{ $password }}</h1>
	</div>	

It’s sweet, isn’t it!

routeからcontrollerへのデータパス

getでcontrollerを呼ぶとき

Route::get('/post', 'PostsController@index');
public function index()
    {
        return "its working";
    }

ここで、routeからデータを渡したい
ブランケットで囲むとデータを引き継げる

Route::get('/post/{id}/', 'PostsController@index');

indexがfunction

public function index($id)
    {
        return "its working with" . $id;
    }

Laravel Controller:–resource

filename:camelcase

namespace
-> namespace is wide scope does for variable basically allow

名前の集合を分割することで衝突の可能性を低減しつつ参照を容易にする概念
namespace App\Http\Controllers;

use
-> right to import that specific class or name space

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;

artisanコマンドでの作成
$ php artisan make:controller PostsController

–resouceとすると、index(), function create(), store(Request $request), show($id), edit($id), update(Request $request, $id), destory($id)ができる
$ php artisan make:controller –resource PostsController

なるほど、method名がdeleteではなくdestroyってのは若干違和感を感じるが、こんなもんかしらね。

Laravelでログインユーザーのみページを表示させる

# /resources/viewsの下にmenu.blade.phpをつくる。適当にhelloとしておく

# 続いて、/app/Http/Controllersに MenuController.phpをつくる

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MenuController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('menu');
    }
}

# /routes/web.phpにroutingを追加

Route::get('/home', 'MenuController@index')->name('menu');

# ログインしている時

# ログアウトしている時は自動的にloginにリダイレクトされる

おおおおおおおおおおおおおお、なるほど、ようは、controllerで$this->middleware(‘auth’);があればいいのね。なるほど。ログインサービス作りたくなってきた。

Display the uploaded image on Laravel 5.7

Create a file name and move it from the temporary folder to under item. Pass variable of file name from controller to view.
ImageIndexController.php

class ImageIndexController extends Controller
{
    public function index(){
    	return view('imageindex');
    }

    public function store(Request $request){

        $filename = date("YmdHis") . "." . $request->file('image')->guessExtension();
    	$request->file('image')->move(public_path('item'), $filename);
    	return view('imageindex',compact('filename'));
    }
}

If there is a variable in the “If statement”, display it.
imageindex.blade.php

@if(!empty($filename))
      <img src="/item/{{$filename}}">
      @else
      @endif

1. upload the image and put register button

2. Then image is displayed on view page.

Ok, first step is well done.
I think I need to insert a file pass to mysql.

Laravel5.7 upload file with extension

uploaded a file with a controller, but looked no file extension.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image;

class ImageIndexController extends Controller
{
    public function index(){
    	return view('imageindex');
    }

    public function store(Request $request){

    	$request->file('image')->move(public_path('item'));
    	return view('imageindex');
    }
}

How come to fix it?

specify the extension with guessExtension method.
ImageIndexController.php

public function store(Request $request){

        $filename = $request->file('image') . "." . $request->file('image')->guessExtension();
    	$request->file('image')->move(public_path('item'), $filename);
    	return view('imageindex');
    }

/image/index

I got it.

I want to display the uploaded image in view.
Before that, you want to make the file name arbitrary, such as date. It seems to be so easy.

$filename = date("YmdHis") . "." . $request->file('image')->guessExtension();

oh, OK.

Laravel5.7 mime type

Use mime type to specify the extension of the image in laravel.

A full listing of MIME types and their corresponding extensions may be found at the following location:
https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

I wonder if this match??

custom request
ImageRequest.php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ImageRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'image' => 'image|mimes:jpg,jpeg,gif,png',
        ];
    }
    public function messages()
    {
        return [
            'image.required' => '画像以外のファイルが指定されています。画像ファイル(png/jpg/jpeg/gif)を指定して下さい',
        ];
    }
}

Upload image with Laravel5.7

Upload images with Laravel5.7.
Configure routing to save images posted from view.

Route::get('/image/index', 'ImageIndexController@index');
Route::post('/image/index', 'ImageIndexController@store');

imageindex.blade.php

@extends('layouts.image')
@section('title', '画像管理')

@section('breadcrumb')
	@@parent
	<ul class="breadcrumb">
      <li itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb" >
        <a href="/top" itemprop="url">
          <span itemprop="title">ホーム</span>
        </a>
      </li>
      <li itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb" >
        <a href="/top" itemprop="url">
          <span itemprop="title">画像管理</span>
        </a>
      </li>
    </ul>
@endsection

@section('content')
<h2>画像管理</h2>
      <hr>
      <form action="/image/index" method="POST" enctype="multipart/form-data">
        <div id="drag-drop-area">
         <div class="drag-drop-inside">
          <p class="drag-drop-info">ここにファイルをアップロード</p>
          <p>または</p>
          <!-- <input type="file" value="ファイルを選択" name="image"> -->
          <p class="drag-drop-buttons"><input id="fileInput" type="file" value="ファイルを選択" name="image"></p>
              <!-- <input type="submit" value="送信"> -->
           </div>
          </div>
            

      <div class="button_wrapper remodal-bg">
         <button type="submit" value="送信" id="square_btn" onClick="location.href='#modal'">登録</button>
      </div>
       </form> 

      <!-- remodal -->
      <div class="remodal" data-remodal-id="modal">
        <button data-remodal-action="close" class="remodal-close"></button>
        <h1>保存しますか</h1>
        <p>
          入力した内容で宜しいでしょうか?
        </p>
        <br>
        <button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>
        <button data-remodal-action="confirm" class="remodal-confirm">OK</button>
      </div>
      <!-- /remodal -->

      <script>
      var fileArea = document.getElementById('drag-drop-area');
      var fileInput = document.getElementById('fileInput');

      fileArea.addEventListener('dragover', function(evt){
        evt.preventDefault();
        fileArea.classList.add('dragover');
      });

      fileArea.addEventListener('dragleave', function(evt){
        evt.preventDefault();
        fileArea.classList.remove('dragover');
      });

      fileArea.addEventListener('drop', function(evt){
        evt.preventDefault();
        fileArea.classList.remove('dragenter');
        var files = evt.dataTransfer.files;
        fileInput.files = files;
      });

      </script>
      
@endsection

Laravel フォーム・確認画面の「戻る」ボタンの処理実装

confirm.blad.php

<div class="button_wrapper remodal-bg">
         <button type="submit" value="送信" id="square_btn" onClick="location.href='#modal'">登録</button>
      </div>

「戻る」ボタンを追加する。

<div class="button_wrapper remodal-bg">
         <button id="square_btn" onClick="history.back()">戻る</button>
         <button type="submit" value="送信" id="square_btn" onClick="location.href='#modal'">登録</button>
      </div>

あれ!?onclickのhistory.back()だとエラーになるな。。何故??

やりなおします。
「戻る」ボタンのvalueを”back”として、一度、controllerにpostします。

<div class="button_wrapper remodal-bg">
         <button type="submit" name="action" id="square_btn" value="back">戻る</button>
         <button type="submit" name="action" value="送信" id="square_btn" onClick="location.href='#modal'">登録</button>
      </div>

controllerでbackを受けた場合は、AccountInputControllerにリダイレクトさせます。

public function store(Request $request){

        $action = $request->get('action', 'back');
        $input = $request->except('action');

        if($action == 'back'){
            return redirect()->action('AccountInputController@input')
->withInput($input);
        } else {

        $account = new Account([
        'login_id' => $request->get('login_id'),
        hogehoge // 省略
        ]);
        $account->save();
        return view('account');

        }

    	
    }

これだと値が保持されたまま、入力画面に戻ります^^
うむ、なかなか簡単には行かせてくれないな。