如何在表中填充数据库值

时间:2016-06-29 17:30:57

标签: php database laravel laravel-5.2

我正在尝试在 users 表中获取记录,如果使用Raw SQL Queries输入正确,则在表中填充它们。尝试从SQL转换为Laravel查询:

SELECT * FROM {用户{1}}

不幸的是它给了我一个错误。

  

未定义的变量:users(查看:C:\ Users \ JohnFrancis \ LaravelFrancis \ resources \ views \ account \ search.blade.php)

控制器:

用户是我的模型,其WHERE username = 'shadow'是我的数据库。

protected $table = 'users

查看:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Requests;
use DB;

class AccountController extends Controller
{
  public function getEmployee()
  {
    return view ('account.search');
  }

  public function postEmployee(Request $request)
  {
    $this->validate($request, [
        'username' => 'required|alpha|max:20',
    ]);

    $username = $request['username']; //Input will be passed to $request array. Accessing search field.

    $user = new User();
    $user = DB::select('select * from users where username = ?', [1]);

    return view ('account.search', ['user' => 'myuser']);

    }
}

Screens

路线:

@section ('content')
<div class = "col-md-10">
<form class = "form-vertical" role = "form" method = "post" action = "{{ route ('account.search') }}">

<div class = "form-group {{ $errors->has('username') ? ' has-error' : '' }}">

    <label for = "username" class = "control-label">Search</label>
    <input type = "text" name = "username" class = "form-control" placeholder = "Find people">

    @if ($errors->has('username'))
        <span class = "help-block">{{ $errors->first('username') }}</span>

    @endif

</div>

<div class = "form-group">

    <button type = "submit" class = "btn btn-default">Search</button>

</div>

<input type = "hidden" name = "_token" value = "{{ Session::token() }}">

</form>

<table class = "table">
    <br>
    <thead>
    <tr>
        <th>ID</th>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Middlename</th>
        <th>Email</th>
        <th>Username</th>
        <th>Actions</th>
    </tr>

    </thead>


    <tbody>
    @foreach ($user as $myuser)
        <tr class = "success">
            <td>{{ $myuser->id }}</td>
            <td>{{ $myuser->first_name }}</td>
            <td>{{ $myuser->last_name }}</td>
            <td>{{ $myuser->middle_name }}</td>
            <td>{{ $myuser->email }}</td>
            <td>{{ $myuser->username }}</td>
            <td></td>
            <td>
                <button type = "submit" class = "btn btn-warning">Update</button>
                <button type = "submit" class = "btn btn-danger">Archive</button>
            </td>
        </tr>
    @endforeach
    </tbody>
</table>
</div>
@endsection

2 个答案:

答案 0 :(得分:0)

这应该做你想要的:

$user = User::where('username', $username)->get();

if ($user->isEmpty()) {
    dd('Failed');
else {
    dd('Success');
}

答案 1 :(得分:-1)

如果您使用的是模型,则无需DB :: select。您可以通过用户名找到用户:

$user = User::where('username', '=', (the username))->get();