27
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[ メモ ] PHP laravel5.6 compact関数 配列省略

Last updated at Posted at 2018-05-24

#phpのcompact関数について(laravel)

compactが出てくる度に検索していたので、メモをしておきます:pencil2:

  1. 変数名とその値から配列を作成する
  2. controllerからviewへの変数の受け渡し

:thinking: phpでcompactを検索すると1番がよく出てきて、
laravelで検索すると2番が出てきます。
二つとも同じこと処理なのか、まだ理解できていないので
詳しい方が入れば教えて頂きたいです:pray:

  • compactとは
    配列(array)を短く書くことができる
index.php
$sports = array(
 'tennis' => $tennis,
 'basketball' => $basketball,
 'soccer' => $soccer,
);

//同じ意味になる

$sports = compact('tennis','basketball','soccer');

今回はlaravelで使用したので、2番の事を書いていきます。
##controllerからviewへの受け渡し

  • 変数を1つ受け渡す場合は、compact関数かwithメソッドを
  • compactの方使うことが多い
ListContoller.php
//compact

public function list()
{

  $list1 = 'tennis';

  return view('list.sport',compact('list1'));

}
ListContoller.php
//with

public function list()
{

  $list1 = 'tennis';

  return view('list.sport')->with('list1',$list1);

}

view側

<p>{{ $list1 }}</p>
27
29
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?