-->

PHP资讯

您的当前位置:首页 > 资讯 > Laravel框架

laravel的基础mvc模式

2019-04-24 10:02:19  来源:admin 点击:912

1.创建控制器 app\Http\Controllers\NewsController.php

<?php

namespace App\Http\Controllers;

use App\News;

use App\Http\Requests;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class NewsController extends Controller {

public function index() {

$news = News::all();

//return $news;//直接返回json

return view('news.index', compact('news')); //返回视图

}

public function detail($id) {

//$row = News::findOrFail($id);

$row = News::getOne($id);

return view('news.detail', compact('row'));

}

}


2、创建模型 app\News.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

use DB;

class News extends Model {

//use SoftDeletes;

static function getOne($id) {

$row = DB::table('news')->where('id', $id)->first();

//$row = DB::select("SELECT * FROM news WHERE id='$id'");

return $row;

}

}<strong>

</strong>


3、创建视图,laravel使用的是Blade模板引擎,同时也支持php原生写法

resources\views\news\index.blade.php

<html>

    <head>

        <title>新闻列表</title>

    </head>

    <body>

<h2>新闻列表</h2>

        <div class="container">

  @foreach($news as $row)

<article>

  <a href="{{url('news/detail/'.$row->id)}}">{{$row->title}}</a>

</article>

  @endforeach

 

        </div>

    </body>

</html>

resources\views\news\detail.blade.php

<html>

    <head>

        <title>新闻详情</title>

    </head>

    <body>

<h2>新闻详情</h2>

        <div class="container">

<p>标题:{{$row->title}}</p>

<p>内容:{{$row->content}}</p>

<p>投稿人:{{$row->username}}</p>

        </div>

    </body>

</html>

创建model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Member extends Model

{   

    public static function getMember()

    {

        return 'member name is sean';

    }

}

3、在控制器当中使用

<?php

namespace App\Http\Controllers;

use App\Member;


class MemberController extends Controller

{

    public function info($id)

    {

        //调用模型

        return Member::getMember();

    }

}


相关文章更多 >

© 2024版权所有 水水网

电话:171780793