🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 第6节 Laravel-通过模型处理性别 # 6.1 模型中创建处理性别的方法 6.2 模型方法在前台视图的遍历、调用 ## 6.1 模型中创建处理性别的方法 ## 目前在列表页的性别,显示的还是数字。所以,我们有必要显示成中文。 首先,在模型中创建一个 sex() 的方法。 `\app\models\Student.php` ~~~ <?php namespace App\models; use Illuminate\Database\Eloquent\Model; class Student extends Model { const SEX_UN = 2; const SEX_BOY = 1; const SEX_GIRL = 0; /** * 与模型相关的数据表 */ protected $table = "student"; /** * 指定是否模型应该被戳记时间 */ public $timestamps = false; /** * 处理用户的性别,转换为中文 * * @param $ind 用户存储的性别数字编号 * @return string 对应的性别中文字符 * @author webjust [604854119@qq.com] */ public function sex($ind = null) { $arr = array( self::SEX_GIRL => '女', self::SEX_BOY => '男', self::SEX_UN => '未知', ); if($ind !== null) { return array_key_exists($ind, $arr) ? $arr[$ind] : $arr[self::SEX_UN]; } return $arr; } } ~~~ 别忘了,既然要在模板中使用Student类,那就需要引入它。 在 `\resources\views\student\create.blade.php` 文件顶部加入如下代码: <?php use App\Models\Student; $student = new Student(); ?> ## 6.2 模型方法在前台视图的遍历、调用 ## 修改视图 `\resources\views\student\create.blade.php` <div class="form-group"> <label class="col-sm-2 control-label">性别</label> <div class="col-sm-5"> @foreach($student->sex() as $ind => $sex) <label class="radio-inline"> <input type="radio" name="Student[sex]" {{ (isset(old('Student')['sex']) && old('Student')['sex'] == $ind) ? 'checked' : '' }} value="{{ $ind }}"> {{ $sex }} </label> @endforeach </div> <div class="col-sm-5"> <p class="form-control-static text-danger">{{ $errors->first('Student.sex') }}</p> </div> </div> 同理,我们在列表页首页也需要使用sex方法,因此也需要引入Student类。 在 `\resources\views\student\index.blade.php` 文件中,顶部写入: <?php use App\Models\Student; $student = new Student(); ?> 然后在视图文件中调用 sex() 方法,传递性别的值作为参数。 {{ $student->sex($student->sex) }} **显示效果:** ![](https://box.kancloud.cn/1a6405873acbe7c8dd010e6540746046_1046x728.png)