欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Truncate a table in Laravel 5

DB:table('users')->truncate();

PUBLISHED 2 YEARS AGO BY ARCHSTANTON

I can seed fine but when I try to use this I get

 Call to undefined function table()  
hamzapurra

You would need a double colon for thisDB:table('users')->truncate();

DB::table('users')->truncate();

Hope that helps!

来自 https://laracasts.com/discuss/channels/laravel/dbtableusers-truncate

 

Sign In or create a forum account to participate in this discussion.

 

Description : I have a table full of tested data. Sometimes, I want to clear it out for new data. I can perform the truncate in the DBMS App like MySQL WorkBench, but I'm trying to achieve it within my application instead.


Goal : to make a button to truncate a table in a database when on click.


Here are my steps :

1 - Declare a route

Route::delete('visitor/truncate',array('as'=>'visitor.truncate', 'uses'=>'VisitorController@truncate'));

2 - Create a truncate function in my VisitorController

public function truncate()
{

    $visitors = Visitor::all();
    $visitors ->truncate();

    return View::make('visitors.index')
        ->with('success', 'Truncate Done');
}

3 - Create a button on my view

 {!! Form::model($visitors, array( 'route' => array('visitor.truncate'),'method' => 'DELETE')) !!}
          <button type="submit"  class="btn bgm-red btn-float waves-effect waves-effect waves-button waves-float"><i class="md md-remove"></i></button>
      {!! Form::close()!!}

4 - Test

When I click on it, it get into my truncate() function in my controller, but I keep getting this error

Call to undefined method Illuminate\Database\Eloquent\Collection::truncate()


Do I need include anything to use truncate() ?

Any hints on that will be much appreciated !

shareimprove this question
 

2 Answers 正确答案

The truncate method is part of the Query Builder. However Visitor::all() returns a Collection instance. You need to build the query using the following:

Visitor::query()->truncate();
shareimprove this answer
 

the following should work as well,

Visitor::truncate();

shareimprove this answer
 

来自 https://stackoverflow.com/questions/33054706/truncate-a-table-in-laravel-5

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

普通分类: