删除表中的记录

问题描述 投票:0回答:1

使用 Laravel 5.2.45

总的来说,我对 Laravel 和 PHP 相当陌生,所以我正在制作一个电话簿项目,在其中存储有关人员的联系信息。

我的数据库中有一个名为“联系人”的表,名为“电话簿”。

我有一个带有表单的视图,用于记录此表中的新条目。

这是视图:

电话簿.blade.php

....... CSS and stuff here .......
<body>
    
            <h1> Contact Form </h1><br/>
    
                        {{-- FORM --}}
    
            <form method = "POST" action = "contacts">
    
                {{ csrf_field() }}
    
                <div class = "form-group
                    @if($errors->has('name')) 
                        has-error
                    @endif"> 
                    <label for = "name"> Name </label><br/>
                    <input type = "text" id = "name" class = "form-control" name = "name" placeholder = "Name your Name" value = "{!! old('name') !!}">
                    @if($errors->has('name')) 
                        <p class = "help-block">{{ $errors->first('name') }}</p> 
                    @endif
                </div><br/>
    
                <div class = "form-group 
                    @if($errors->has('lastname')) 
                        has-error
                    @endif"> 
                    <label for = "lastname"> Lastname </label><br/>
                    <input type = "text" id = "lastname" class = "form-control" name = "lastname" placeholder = "Name your Lastname" value = "{!! old('lastname') !!}">
                    @if($errors->has('lastname')) 
                        <p class = "help-block">{{ $errors->first('lastname') }}</p> 
                    @endif                        
                </div><br/>
    
                <div class = "form-group 
                    @if($errors->has('email')) 
                        has-error
                    @endif">
                    <label for = "email"> E-mail </label><br/>
                    <input type = "text" id = "email" class = "form-control" name = "email" placeholder = "[email protected]" >
                    @if($errors->has('email')) 
                        <p class = "help-block">{{ $errors->first('email') }}</p> 
                    @endif
                </div><br/>
    
                <div class = "form-group 
                    @if($errors->has('phone'))
                        has-error
                    @endif">
                    <label for = "phone"> Phone Number </label><br/>
                    <input type = "text" id = "phone" class = "form-control" name = "phone" placeholder = "I'll call you">
                    @if($errors->has('phone')) 
                        <p class="help-block">{{ $errors->first('phone') }}</p> 
                    @endif
                </div><br/>
    
                <div class = "form-group"> 
                    <label for = "address"> Address </label><br/>
                    <input type = "text" id = "address" class = "form-control" name = "address" placeholder = "I'll even visit you" value = "{!! old('address') !!}">                        
                </div><br/>
    
                <div>
                    <button type = "submit" class = "submit"> Submit Information </button>
                    <a href="contacts"><button type = "button"> View Contacts </button></a>
                </div>
            </form>      
        </body>
    </html>

当我记录新条目时,我会被重定向到可以看到表格的视图。 以简单的方式构建,这就是视图:

contacts.blade.php

....... CSS and stuff here .......
<body>

        <h1> Contacts </h1>

        <br/>

        <div>
            <a href = "phonebook"><button class = "ret" type = "button"> Add New Entry </button></a>
        </div>

        <br/><br/>

        <table class = "contacts">

            <thead>
                <tr>
                    <th> ID       </th>
                    <th> Name     </th>
                    <th> Lastname </th>
                    <th> E-Mail   </th>
                    <th> Phone    </th>
                    <th> Address  </th>
                    <th> Edit     </th>
                    <th> Delete   </th>
                </tr>
            </thead>

            <tbody>
                @foreach($contact as $contact)                                                      
                    <tr class = "tableBody">
                        <td class = "id">       {{ $contact->id }}                                          </td>
                        <td class = "name">     {{ $contact->name }}                                        </td>
                        <td class = "lastname"> {{ $contact->lastname }}                                    </td>
                        <td class = "email">    {{ $contact->email }}                                       </td>
                        <td class = "phone">    {{ $contact->phone }}                                       </td>
                        <td class = "address">  {{ $contact->address }}                                     </td>
                        <td class = "edit">     <a href = "edit"> Edit </a>                                 </td>
                        <td class = "delete">   <a href = "delete"> Delete </a>                             </td>
                    </tr>                       
                @endforeach
            </tbody>
        </table>

        <br/>
        
        <div>
            <a href = "phonebook"><button class = "ret" type = "button"> Add New Entry </button></a>
        </div>
    </body>
</html>

注意,您会看到我的表中有一个删除链接,我想用它来删除该给定行中的记录。

为此,我有一个删除视图,该视图在

destroy()
函数中的一段代码之后加载,在我使用 artisan 控制台所做的控制器中提供

这是我的routes.php 文件,带有注释

routes.php

<?php

use Illuminate\Support\Facades\Input;
use App\Contact;
use App\Http\Controllers;


// default welcome view from Laravel
Route::get('/', function ()
{
    return view('welcome');
});

// getting the routes from the controller
Route::resource('contacts', 'ContactsController');

// getting the form from the controller, which is in a .blade.php view
Route::get('phonebook', 'ContactsController@index');

// showing the table in a .blade.php view
Route::get('contacts', 'ContactsController@tab');

// the route to post the contact in the table, using the form in the phonebook.blade.php
Route::post('contacts', 'ContactsController@create');

// routing to the destroy function in my controller
Route::get('delete', [
    'as' => 'delete', 'uses' => 'ContactsController@destroy'
]);

// getting the edit.blade.php, not working
// permeate the inputs of name, lastname, email, phone and address
// with the same inputs we have in the row of our table
Route::get('edit', function()
{
    return view('edit');
});

也许错误在我的路线中,这就是为什么我也将其粘贴到这里。

总体而言,这是我的控制器

ContactsController.php 带注释

   <?php
    
    namespace App\Http\Controllers;
    
    use App\Contact;
    use DB;
    use Illuminate\Http\Request;
    
    use App\Http\Requests;
    
    use Illuminate\Support\Facades\Input;
    use Validator;
    
    
    class ContactsController extends Controller
    {
       // showing the form in the phonebook.blade.php
        // the form is structured using html and stuff
        public function index()
        {
            return view('phonebook');
        }
    
        // showing the table where I save my contacts
        // simple view stuff
        public function tab()
        {
            return view('contacts');
        }
        
        // the parameters to save my contact, with errors and stuff
        //working since day one
        public function create()
        {
            $rules = array(
                'name'      => 'alpha|min:3|max:15|required',
                'lastname'  => 'alpha|min:3|max:15',
                'email'     => 'required|unique:contacts,email|email',
                'phone'     => 'required|unique:contacts,phone|alpha_num|between:3,25',
                'address'   => 'max:255',
            );
    
            $messages = array(
                'alpha'     => 'The :attribute must contain only letters.',
                'max'       => 'The :attribute must have a maximum of 15 letters.',
                'min'       => 'The :attribute must have at least 3 characters.',
                'required'  => 'The :attribute is really important. We are storing your contact info after all...',
                'email'     => 'The :attribute must be a valid e-mail format address.',
                'numeric'   => 'The :attribute must contain only numbers.',
                'between'   => 'The :attribute content must have a lenght between 3 and 25 characters.',
            );
    
            $validator = Validator::make(Input::all(), $rules, $messages);
    
            if ($validator->fails())
            {
                $messages = $validator -> messages();
    
                return redirect('phonebook')
                    ->withInput()
                    ->withErrors($validator);
            }
            else 
            {
                $contact             = new Contact;
                $contact-> name      = Input::get('name');
                $contact-> lastname  = Input::get('lastname');
                $contact-> email     = Input::get('email');
                $contact-> phone     = Input::get('phone');
                $contact-> address   = Input::get('address');
    
                $contact->save();
    
                // $contact =  App\Contact::all();
    
                return view('contacts', compact('contact'));
            };
        }

我也有编辑功能,但不起作用,但我不关心它。

我用多种方式编辑了我的销毁函数。

我现在将它们列在这里,包括评论和它们返回的错误。

由于每个函数都应该返回

delete.blade.php
,所以我不会在下面的代码中编写这一行。

销毁功能1

//error: undefined variable in the findOrFail()
$contact = Contact::findOrFail($contact);
$contact->delete();

与我想在 findOrFail() 中传递的参数无关,无论是 $id、$name 还是唯一的 $phone 或 $email,错误与代码注释中提到的相同。

销毁功能2

//FatalErrorException in ContactsController.php line 93:
//Class 'App\Http\Controllers\Contacts' not found
Contacts::where('id','=',$id);
$id->delete();

在这一篇和下一篇中,我什至不知道如何摆脱这个错误。

销毁功能3

//Same error as above
//Class not found
$contact = Contacts::where('id', '=', $id);
$contact->delete();

接下来,我添加了一个

if
语句来检查事情是否进展顺利。

销毁功能4

//Class contacts not found
$id = contacts::where('id', $id)->first();
if ($id != null) {
    $id->delete();
return view('delete'); 
}else{
return view('delete')->with(['message'=> 'Contact not found']);
};

下一个返回一个我不明白的错误。

销毁功能5

//Call to a member function delete() on null
//I don't know what that is supposed to mean
$id = Contact::all();
Contact::find($id) -> delete();

现在,下一段代码感觉是最好的,因为它返回删除视图,但没有删除我表中的条目,甚至没有使用forceDelete()。

销毁功能6

//loading the view page, but not deleting the entry
// not even using forceDelete()
Contact::where('id', '=', '$id') 
    -> where('name', '=', '$name')
    -> delete();

最后,我想,只是为了好玩,我发布了下一行代码,当我单击表中的删除链接时,该代码会关闭我的服务器

//This line destroys my local server
//I have to up it again, using art serve command line
// $this -> destroy(Contact::get());

所以,我在使我的销毁功能正常工作时遇到了麻烦。

这就是我需要的

我需要对我的函数进行一些更正,只要对其中一个函数进行一次更正,我就会非常高兴。 重申一下,这些函数都不起作用,每个函数都会返回某种错误,正如您在代码本身提供的注释中看到的那样。

就像我之前说的,我认为 destroy 函数 6 是可行的,因为它返回我想要的视图,它只是不删除我在表中的条目。

另外,我发布了所有这些代码,因为也许错误是从后面一路传来的。

可以随意索取其他文件,例如模型、迁移等。

编辑

这是我的联系方式:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    // not using an id field
    // could this be the error?
    // isn't laravel making an automatic id field?
    // dunno
    public $fillable = array('name', 'lastname', 'email', 'phone', 'address');
    
    //added because of error at migration
    public $timestamps = false; 
}

正如代码中注释的那样,我必须为

false
添加
timestamps
语句,因为它返回错误。

现在,这是一种有效的方法。

我采用了第一个销毁函数并将其应用到我的代码中。 错误还是一样,findOrFail()

未定义变量。

所以,我定义了这个变量,我不知道这是否是常见的做法。 这是它的样子。

$contact=Contact::first();
Contact::find($contact->id);
$contact->delete();

但是,这段代码删除了我表中的第一个条目,与我单击删除按钮的位置无关,这是有道理的,那里是一个first()

那么,既然这是一种工作,我应该使用什么语句来让它删除我想要的条目?

结束编辑

很抱歉问题中的代码过多。 提前谢谢大家。

php laravel-5
1个回答
1
投票

** 编辑 **

您需要更新“删除”按钮所在的刀片模板,以将联系人 ID 作为 url 的一部分传递

<tbody>
                @foreach($contact as $contact)                                                      
                    <tr class = "tableBody">
                        <td class = "id">       {{ $contact->id }}                                          </td>
                        <td class = "name">     {{ $contact->name }}                                        </td>
                        <td class = "lastname"> {{ $contact->lastname }}                                    </td>
                        <td class = "email">    {{ $contact->email }}                                       </td>
                        <td class = "phone">    {{ $contact->phone }}                                       </td>
                        <td class = "address">  {{ $contact->address }}                                     </td>
                        <td class = "edit">     <a href = "edit"> Edit </a>                                 </td>
                        <td class = "delete">   <a href = "delete/{{ $contact->id }}"> Delete </a>                             </td>
                    </tr>                       
                @endforeach
            </tbody>

然后更新您的删除路线以将 id 包含在 url 中

Route::get('delete/{id}', [
    'as' => 'delete', 'uses' => 'ContactsController@destroy'
]);

然后让你的控制器销毁方法接受id

public function destroy($id)
{
   $contact = Contact::findOrFail($id);
   $contact->delete();
}

原版

对此使用 $contact->id。 findOrFail 需要传递 id。

销毁功能1

//error: undefined variable in the findOrFail()
$contact = Contact::findOrFail($contact->id);
$contact->delete();

销毁功能2

似乎您没有 Contacts 类的导入语句。检查 Contacts 类的命名空间,并将其添加到控制器类的顶部,如下所示:

use App\Contact;

$contact = Contact::where('id','=',$id)->get();
$contact->delete();

Contact::destroy($id);

销毁功能3

同上。添加导入/使用语句。

//Same error as above
//Class not found
$contact = Contact::where('id', '=', $id)->get();
$contact->delete();
© www.soinside.com 2019 - 2024. All rights reserved.