본문 바로가기

Back-end/PHP

Laravel 기초2 - Controller, Route, Template

Laravel 기초2 - Controller, Route, Template

라라벨이 설치된 폴더에서 App/Http/routes.php로 이동

라우트

//route.php
Route::get('/', function () {
return "hello world"
});

루트 디렉토리로 이동하면 hello world가 출력됩니다.

전체 디렉토리에 대한 정보들을 보고싶다면

php artisan route:list

위와같이 현재 사용중인 route 리스트를 시각적으로 한눈에 볼 수 있습니다.

// View welcome.php .
//View header nav
// view('header/nav')
Route::get('/', function () {
return view('welcome');
});
/* http://localhost/about */
Route::get('/about', function () {
return "HI About page";
});
/* http://localhost/post/11/112 id 11 named 112 */
Route::get('/post/{id}/{name}',function($id, $name){
return "this is post number".$id." and name is".$name;
});
//as url admin.home
Route::get('admin/posts/example', array('as'=>'admin.home', function(){
//route('admin.home') url admin/posts/example .
$url = route('admin.home');
return "this url is".$url;
}));

컨트롤러

컨트롤러의 경우 직접 만드는 방법도 있지만 php artissan을 통해 만들 수 있다.

php artisan make:controller PostsController
#
php artisan make:controller PostsController --resouce

이제 라우트단에서 직접 기술해줄 필요 없이 아래의 내용으로 컨트롤러로 보내줄 수 있다.

// post PostsController
Route::get('/post', 'PostsController');
// post postController index function
Route::get('/post', 'PostsController@index');
Route::resource('posts','PostsController');

위처럼하면 get뿐만 아니라 delete post등 모든 url을 연동시켜주며 자세한건 상단의 artisan의 route를 통해 볼 수 있다.

public function show_post($id, $name, $password){
//$id id .
// compact
//return view('pages/post')->with('id',$id);
return view('pages/post', compact('id','name','password'));
}

blade

layouts.app.php

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="container">
@yield('content')
</div>
@yield('footer')
</body>
</html>

위처럼 contents로 지정된 부분이 어디에 들어갈 것인지 footer로 지정된 부분이 어디에 들어갈 것인지만 명명해준다.

tempalte.balde.php

@extends('layouts.app')
{{--section start--}}
@section('content')
{{--@include('header')--}}
<h1>hellow world</h1>
@if(count($people))
<ul>
@foreach($people as $person)
<li>{{$person}}</li>
@endforeach
</ul>
@endif
@stop

위처럼 어떤 레이아웃을 사용할지 잡아준 후 그 내용부터 @section 끝날부분을 @stop으로 잡아준다.
이후 view를 template.balide.php로 설정해줄경우 알아서 layouts.app의 내용을 로드 한 후 그곳의 네이밍에 맡는 section부분을
맵핑해준다