laravel增刪改查

1.model層
2.控制層(含圖片處理,內(nèi)容驗(yàn)證)
3.插入信息的頁面
4.信息列表頁面
5.信息編輯頁面
6.在提交頁面?zhèn)鬟f提示信息

補(bǔ)充 ajax刪除

  <a href="{{url('admin/article/'.$v->art_id.'/edit')}}">修改</a>
  <a href="javascript:;" onclick="delArt({{$v->art_id}})">刪除</a>
    <script>
        //刪除分類
        function delArt(art_id) {
            layer.confirm('您確定要刪除這篇文章嗎?', {
                btn: ['確定','取消'] //按鈕
            }, function(){
                $.post("{{url('admin/article/')}}/"+art_id,{'_method':'delete','_token':"{{csrf_token()}}"},function (msg) {
                    if(msg == 0){
                        layer.msg('刪除失敗', {icon: 5});
                        setTimeout("location.reload()",1000);
                        //window.location.reload();
                    }else {
                        layer.msg('刪除成功', {icon: 1});
                        setTimeout("location.reload()",1000);
                        //window.location.reload();
                    }
                });
            }, function(){

            });
        }
    </script>

1.model層

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Carousel extends Model
{
    protected $table = 'anchong_carousel_figure';
    protected $primaryKey = 'figure_id';
    protected $guarded = [''];
    public $timestamps = false;
//    添加內(nèi)容
    public function add($data)
    {
        $this->fill($data);
        if ($this->save()){
            return true;
        }else{
            return false;
        }
    }

    /*
     * 編輯信息
     */
    public function carouselupdate($id,$data)
    {
        $num = $this->find($id);
        if ($num->update($data)){
            return true;
        }else{
            return false;
        }
    }

    /*
     * 刪除輪播圖
     */
    public function del($id)
    {
        return $this->where('figure_id',$id)->delete();
    }

}
?>

2.控制層

<?php
namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator,DB;
use Illuminate\Support\Facades\Input;

//輪播圖的處理類
class CarouselController extends ConmonController
{
    public $carousel;
    public function __construct()
    {
        $this->carousel = new \App\Carousel();
    }

//    展示輪播圖內(nèi)容
    public function index()
    {
        // 輪播圖
        $datas = DB::table('anchong_carousel_figure')->orderBy('figure_id','desc')->paginate(5);
        return view('admin.carousel.index',compact('datas'));
    }
//    創(chuàng)建輪播圖
    public function create()
    {
        return view('admin.carousel.create');
    }

//    編輯圖片內(nèi)容,跳轉(zhuǎn)到編輯頁面
    public function edit($id)
    {
        $datas = $this->carousel->find($id);
        return view('admin.carousel.edit',compact('datas'));
    }

    //    接受更新的數(shù)據(jù),更新數(shù)據(jù)
    public function update($id)
    {
        $data = Input::all();
        $res = $this->carousel->carouselupdate($id,$data);
        if($res){
            return redirect('carousel')->with('message', '更新成功'); //要在模板上用session('message')取值
        }else{
            return back()->with('errors','更新失敗');
        }
    }

    //刪除某條信息
    public function destroy($id)
    {
        $res = $this->carousel->del($id);
        if ($res){
            return response()->json(['status' => 0, 'msg' => '刪除成功']);
        }else{
            return response()->json(['status' => 1, 'msg' => '刪除失敗,請重試']);
        }
    }

//    保存輪播圖信息
//    保存內(nèi)容
    public function store(\Request $request )
    {

        $input = Input::except('_token','picfile');
        $res = $this->uploadpic('picfile','uploads/images');
        switch ($res){
            case 1: return back()->with('errors','圖片上傳失敗');
            case 2: return back()->with('errors','圖片不合法');
            case 3: return back()->with('errors','圖片儲存失敗');
            default :
                $input['figure_img'] = $res; //把得到的地址給picname存到數(shù)據(jù)庫
                if($this->carousel->add($input)){
                    return redirect('carousel')->with('message', '發(fā)布成功'); //這個message是存在session里面的,在模板中藥通過session取值
                }else{
                    return back()->with('errors','數(shù)據(jù)填充失敗')->withInput();;
                }
        }
    }
}


// 被繼承的commonController控制器里面的圖片上傳處理
class ConmonController extends Controller
{
//    上傳圖片
    public function uploadpic( $filename, $filepath)
    {
        //        1.首先檢查文件是否存在
        if (\Request::hasFile($filename)){
            //          2.獲取文件
            $file = \Request::file($filename);
            //          3.其次檢查圖片手否合法
            if ($file->isValid()){
                //          4.將文件取一個新的名字
                $newName = 'partner'.time().rand(100000, 999999).$file->getClientOriginalName();
                //           5.移動文件,并修改名字
                if($file->move($filepath,$newName)){
                    return $filepath.'/'.$newName;   //返回一個地址
                }else{
                    return 3;
                }
            }else{
                return 2;
            }
        }else{
            return 1;
        }
    }
    // $realPath = $file->getRealPath(); //這個表示的是緩存在tmp文件夾下的文件的絕對路徑;
    // $tmpName = $file -> getFileName();   //緩存在tmp文件中的文件名
    // $clientName = $file -> getClientOriginalName(); //獲取文件名稱
    //$extension = $file->getClientOriginalExtension();   //上傳文件的后綴
}



// 如果需要做驗(yàn)證判斷
public function leaveStore()
{
    $input = Input::all();
    $rules = [
        'phone'=>'required',
        'content'=>'required',
    ];
    $message = [
        'phone.required'=>'電話號碼必須填寫!',
        'content.required'=>'反饋信息必須填寫!',
    ];
    $validator = Validator::make($input,$rules,$message);
    if ($validator->fails()){
        return back()->withErrors($validator)->withInput();
    }
    $result = $this->leave->add($input);
    if ($result){
        return back()->with('message','留言成功');//這個值是存在session中的
    }else{
        return back()->with('errors','留言失敗')->withInput(); //返回錯誤信息在模板中讀出,并將用戶填寫的信息用withInput();返回
    }

}

3.插入信息的頁面

@extends('admin.admin')
@section('content')
<ul class="breadcrumb">
    <li><a href="{{url('admin/console')}}">首頁</a></li>
    <li>輪播圖</li>
    <li>輪播圖添加</li>
</ul>
<div class="box">
    <div class="box-header with-border">
        <h3 class="box-title">輪播圖添加</h3>
    </div>
    <div class="box-body">
    // 1。如果插入信息失敗,就這樣處理,如果錯誤是一個變量。就遍歷,是一個單量,就直接輸出
        @if(count($errors)>0)
            <div class=""mark>
                @if(is_object($errors))
                    @foreach($errors->all() as $error)
                        <p>{{$error}}</p>
                    @endforeach
                @else
                    <p>{{$errors}}</p>
                @endif
                @endif
                <form class="form-horizontal" action="{{ url('carousel/')}}" method="POST" enctype="multipart/form-data">
                    {{ csrf_field() }}
                    <div class="form-group">
                        <label class="col-sm-2 control-label" >圖片標(biāo)題</label>
                        <div class="col-sm-10">
                            <input type="text" name="figure_title" class="form-control" value="{{ old('figure_title') }}"   placeholder="圖片標(biāo)題" >
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">圖片內(nèi)容</label>
                        <div class="col-sm-10">
                            <input type="text" name="content" class="form-control" value="{{ old('content') }}"  placeholder="圖片內(nèi)容">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">選擇文件</label>
                        <div class="col-sm-10">
                            <input type="file" name="picfile" >
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-md-4 col-md-offset-2">
                            <input class="btn btn-primary"  type="submit" value="提交">
                        </div>
                    </div>

                </form>
            </div>

    </div>
@endsection

4.信息列表頁面

@extends('admin.admin')
@section('content')
    <script src="layer/layer.js"></script>
//這個session是插入信息成功,重定向加with(message')里面的信息
@if (session('message'))
    <div class="alert alert-success">
        {{ session('message') }}
    </div>
@endif
    <div class="box">
        <div class="box-header with-border">
            <h3 class="box-title">輪播圖列表</h3>
        </div><!-- /.box-header -->
        <div class="box-body">
            <table class="table table-hover">
                <tr>
                    <th>ID</th>
                    <th>圖片標(biāo)題    </th>
                    <th>圖片內(nèi)容    </th>
                    <th>圖片</th>
                    <th>編輯</th>
                </tr>
                @foreach($datas as $data)
                    <tr>
                        <td>{{$data->figure_id }}</td>
                        <td>{{ $data->figure_title }}</td>
                        <td>{{ $data->content }}</td>
                        // 1.讀圖片的時(shí)候,前面要加上"/",從根部開始讀取
                        <td><img src="/{{$data->figure_img}}" alt="" style="width: 100;height: 100px;"></td>
                        <td>
                            <a href="{{ url('carousel/'.$data->figure_id.'/edit')  }}" class="btn btn-info btn-primary btn-sm iframe cboxElement"><span class="glyphicon glyphicon-pencil"></span> 編輯</a>
                            <a  class="btn btn-info btn-danger btn-sm iframe cboxElement" href="javascript:;" onclick="delCate({{$data->figure_id}})"><span class="glyphicon glyphicon-trash"></span> 刪除</a>
                        </td>
                    </tr>
                @endforeach
            </table>
        </div><!-- /.box-body -->
        <div class="box-footer clearfix">
            <div class="pull-left">
            // 2.信息成分頁,注意變量是$datas,$links
                {{ $datas->links() }}
            </div>
        </div>
    </div><!-- /.box -->
    <script>
        //刪除分類
        function delCate(id) {
            layer.confirm('你確定刪除嗎?', {
                btn: ['確定','取消'] //按鈕
            }, function(){
                $.post("{{ url('carousel') }}/"+id,{'_method':'delete' ,'_token':'{{csrf_token()}}'},function (data) {
                    if(data.status==0){
                        location.href = location.href;
                        layer.msg(data.msg,{icon:6});
                    }else{
                        layer.msg(data.msg, {icon:6});
                    }
                } );

            }, function(){

            });
        }
    </script>
@endsection

5.信息編輯頁面

@extends('admin.admin')
@section('content')
    <ul class="breadcrumb">
        <li><a href="{{url('admin/admin')}}">首頁</a></li>
        <li>內(nèi)容管理</li>
        <li>圖片編輯</li>
    </ul>
    <div class="box">
        <div class="box-header with-border">
            <h3 class="box-title">圖片編輯</h3>
        </div>
        <div class="box-body">
            <form class="form-horizontal" action="{{ url('carousel/'.$datas->figure_id )}}" method="POST">
                <input type="hidden" name="_method" value="PUT">
                {{ csrf_field() }}
                <div class="form-group">
                    <label class="col-sm-2 control-label" >圖片標(biāo)題</label>
                    <div class="col-sm-10">
                        <input type="text" name="figure_title" class="form-control" value="{{ $datas->figure_title }}"  placeholder="圖片標(biāo)題">
                    </div>
                </div>
                <div class="form-group">
                    <label  class="col-sm-2 control-label">圖片內(nèi)容</label>
                    <div class="col-sm-10">
                        <input type="text" name="content" class="form-control" value="{{ $datas->content }}" placeholder="圖片內(nèi)容">
                    </div>
                </div>
                <div class="form-group row">
                    <div class="col-md-4 col-md-offset-2">
                        <input class="btn btn-primary"  type="submit" value="提交">
                    </div>
                </div>

            </form>
        </div>

    </div>
@endsection

6.在提交頁面?zhèn)鬟f成功與否的信息

    //這是在一個被繼承的主頁面里面寫的
    <section class="content">
  @if(is_object($errors))
      @if (count($errors) > 0)
          <div class="alert alert-danger alert-dismissable">
              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
              <p><i class="icon fa fa-ban"></i>  填寫表單出錯了哦!</p>
              <ul>
                  @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                  @endforeach
              </ul>
          </div>
      @endif
  @else
      <div class="alert alert-danger alert-dismissable">
          <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
          <p><i class="icon fa fa-ban"></i>  出錯了哦!</p>
          <ul>
              <li>{{ $errors }}</li>
          </ul>
      </div>
  @endif

  @if(Session::has('message'))
      <div class="alert alert-success alert-dismissable">
          <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
          <p><i class="icon fa fa-check"></i>  {{Session::get('message')}}</p>

      </div>
  @endif
  @yield('content')
  </section>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 用戶Model創(chuàng)建 Laravel-增刪改查 1、數(shù)據(jù)添加 路由/app/http/routes.php /app...
    曹淵說創(chuàng)業(yè)閱讀 2,330評論 0 1
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,039評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,555評論 19 139
  • 梳云鬟, 舊容妝, 娉娉婷婷秀色餐, 冰脂顏, 無濁念, 傾國傾城難比肩, 灼灼心, 金不換, 自由徜徉天地間, ...
    蘇沐晴閱讀 405評論 12 13
  • 中午剛上班,走進(jìn)樓道看見曉梅端著一碗紅糖水,邊走邊用勺子攪動著,時(shí)不時(shí)用嘴吹一下,我停了下來,曉梅放快腳步走了過來...
    方海敏閱讀 790評論 11 28

友情鏈接更多精彩內(nèi)容