upload excel file for specific user in laravel-8 General error: 1364 Field 'user_id' doesn't have a default value
upload excel file for specific user in laravel-8 General error: 1364 Field 'user_id' doesn't have a default value
想法是
- 一个用户有很多数据,但所有数据都属于一个用户
我正在处理 SQLSTATE[HY000]:一般错误:1364 字段 'user_id' 没有默认值(SQL:插入
projects
(name
, detail
, color
, image
, logo
, updated_at
, created_at
) 值 (shahed, kjfs, fsdkf, fdsfsd, fds, 2021 -05-30 08:45:35, 2021-05-30 08:45:35)) 错误。
如果您需要更多详细信息,可以询问
这是我的模特project.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function getUser(){
return $this->belongsTo(User::class);
}
}
这是模特user.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function getProducts(){
return $this->hasMany('App\Models\Product');
}
public function getProject(){
return $this->hasMany('App\Models\Project');
}
// public function products(){
// return $this->hasMany(Product::class);
// }
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'profile_photo_url',
];
}
这是项目 table projecttable.php
public function up()
{
Schema::create('projects', function (Blueprint $table) {
// $table->('id');
$table->bigIncrements('id');
$table->string('name', 255)->nullable();
$table->string('detail', 500)->nullable();
$table->string('color', 255)->nullable();
$table->decimal('image', 22)->nullable();
$table->decimal('logo', 22)->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
}
这是importProject.php
public function model(array $row)
{
return new Project([
'name' => $row['name'],
'detail' => $row['detail'],
'color' => $row['color'],
'image' => $row['image'],
'logo' => $row['logo'],
]);
}
这是projectController.php
<?php
namespace App\Http\Controllers;
use App\Exports\UsersExport;
use App\Models\Project;
use App\Imports\ProjectsImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
// $projects = Project::paginate(20);
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required',
'logo' => 'required',
]);
$input = $request->all();
$input['user_id'] = auth()->user()->id;
Project::create($input);
return redirect()->route('project.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function show(Project $project)
{
return view('projects.show', compact('project'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
$user_id = Auth::user()->id ;
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required',
'logo' => 'required'
]);
$input = $request->all();
$project->update($input);
return redirect()->route('project.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect()->route('projects.index')
->with('success', 'Project deleted successfully');
}
public function importProject()
{
Excel::import(new ProjectsImport, request()->file('file'));
return back()->with('success','Project created successfully.');
}
public function export()
{
return Excel::download(new UsersExport, 'projects.xlsx');
}
}
这是index.blade.php
@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD </h2>
</div>
<div class="d-flex flex-row-reverse flex-column">
<div class="d-flex">
<a class="btn btn-success text-light mr-5" data-toggle="medel" id="mediumButton" data-target="#mediumModel"
data-attr="{{ route ('projects.create')}}" title="upload project">
<i class="fas fa-cloud-upload-alt fa-2x"></i>
</a>
<form action="{{ route('importProject') }}" method="POST" enctype="multipart/form-data" class="d-flex">
@csrf
<input type='file' name="file">
<button class="btn btn-info" style="margin-left: -60px" title="Import Project">
<i class="fas fa-cloud-upload-alt fa-2x"></i></button>
<a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>
</form>
</div>
</div>
<div class="pull-right">
<a class="btn btn-success text-light" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
data-attr="{{ route('projects.create') }}" title="Create a project"> <i class="fas fa-plus-circle"></i>
</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<table class="table table-bordered table-responsive-lg table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">No</th>
<th scope="col">Name</th>
<th scope="col" width="30%">Details</th>
<th scope="col">color</th>
<th scope="col">image</th>
<th scope="col">logo</th>
<th scope="col">Date Created</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach ($projects as $project)
<tr>
<td scope="row">{{ ++$i }}</td>
<td>{{ $project->name }}</td>
<td>{{ $project->detail }}</td>
<td>{{ $project->color }}</td>
<td>{{ $project->image }}</td>
<td>{{ $project->logo }}</td>
<td>{{ date_format($project->created_at, 'jS M Y') }}</td>
<td>
<form action="{{ route('projects.destroy', $project->id) }}" method="POST">
<a data-toggle="modal" id="smallButton" data-target="#smallModal"
data-attr="{{ route('projects.show', $project->id) }}" title="show">
<i class="fas fa-eye text-success fa-lg"></i>
</a>
<a class="text-secondary" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
data-attr="{{ route('projects.edit', $project->id) }}">
<i class="fas fa-edit text-gray-300"></i>
</a>
@csrf
@method('DELETE')
<button type="submit" title="delete" style="border: none; background-color:transparent;">
<i class="fas fa-trash fa-lg text-danger"></i>
</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
{!! $projects->links() !!}
<!-- small modal -->
<div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="smallBody">
<div>
<!-- the result to be displayed apply here -->
</div>
</div>
</div>
</div>
</div>
<!-- medium modal -->
<div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="mediumBody">
<div>
<!-- the result to be displayed apply here -->
</div>
</div>
</div>
</div>
</div>
<script>
// display a modal (small modal)
$(document).on('click', '#smallButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
$('#smallModal').modal("show");
$('#smallBody').html(result).show();
},
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
})
});
// display a modal (medium modal)
$(document).on('click', '#mediumButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
$('#mediumModal').modal("show");
$('#mediumBody').html(result).show();
},
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
})
});
</script>
@endsection
像这样在导入项目中提供授权值:)
public function model(array $row)
{
return new Project([
'name' => $row['name'],
'detail' => $row['detail'],
'color' => $row['color'],
'image' => $row['image'],
'logo' => $row['logo'],
'user_id' => auth()->user()->id
]);
}
想法是
- 一个用户有很多数据,但所有数据都属于一个用户
我正在处理 SQLSTATE[HY000]:一般错误:1364 字段 'user_id' 没有默认值(SQL:插入
projects
(name
,detail
,color
,image
,logo
,updated_at
,created_at
) 值 (shahed, kjfs, fsdkf, fdsfsd, fds, 2021 -05-30 08:45:35, 2021-05-30 08:45:35)) 错误。 如果您需要更多详细信息,可以询问 这是我的模特project.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function getUser(){
return $this->belongsTo(User::class);
}
}
这是模特user.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function getProducts(){
return $this->hasMany('App\Models\Product');
}
public function getProject(){
return $this->hasMany('App\Models\Project');
}
// public function products(){
// return $this->hasMany(Product::class);
// }
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'profile_photo_url',
];
}
这是项目 table projecttable.php
public function up()
{
Schema::create('projects', function (Blueprint $table) {
// $table->('id');
$table->bigIncrements('id');
$table->string('name', 255)->nullable();
$table->string('detail', 500)->nullable();
$table->string('color', 255)->nullable();
$table->decimal('image', 22)->nullable();
$table->decimal('logo', 22)->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
}
这是importProject.php
public function model(array $row)
{
return new Project([
'name' => $row['name'],
'detail' => $row['detail'],
'color' => $row['color'],
'image' => $row['image'],
'logo' => $row['logo'],
]);
}
这是projectController.php
<?php
namespace App\Http\Controllers;
use App\Exports\UsersExport;
use App\Models\Project;
use App\Imports\ProjectsImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
// $projects = Project::paginate(20);
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required',
'logo' => 'required',
]);
$input = $request->all();
$input['user_id'] = auth()->user()->id;
Project::create($input);
return redirect()->route('project.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function show(Project $project)
{
return view('projects.show', compact('project'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
$user_id = Auth::user()->id ;
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required',
'logo' => 'required'
]);
$input = $request->all();
$project->update($input);
return redirect()->route('project.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect()->route('projects.index')
->with('success', 'Project deleted successfully');
}
public function importProject()
{
Excel::import(new ProjectsImport, request()->file('file'));
return back()->with('success','Project created successfully.');
}
public function export()
{
return Excel::download(new UsersExport, 'projects.xlsx');
}
}
这是index.blade.php
@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD </h2>
</div>
<div class="d-flex flex-row-reverse flex-column">
<div class="d-flex">
<a class="btn btn-success text-light mr-5" data-toggle="medel" id="mediumButton" data-target="#mediumModel"
data-attr="{{ route ('projects.create')}}" title="upload project">
<i class="fas fa-cloud-upload-alt fa-2x"></i>
</a>
<form action="{{ route('importProject') }}" method="POST" enctype="multipart/form-data" class="d-flex">
@csrf
<input type='file' name="file">
<button class="btn btn-info" style="margin-left: -60px" title="Import Project">
<i class="fas fa-cloud-upload-alt fa-2x"></i></button>
<a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>
</form>
</div>
</div>
<div class="pull-right">
<a class="btn btn-success text-light" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
data-attr="{{ route('projects.create') }}" title="Create a project"> <i class="fas fa-plus-circle"></i>
</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<table class="table table-bordered table-responsive-lg table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">No</th>
<th scope="col">Name</th>
<th scope="col" width="30%">Details</th>
<th scope="col">color</th>
<th scope="col">image</th>
<th scope="col">logo</th>
<th scope="col">Date Created</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach ($projects as $project)
<tr>
<td scope="row">{{ ++$i }}</td>
<td>{{ $project->name }}</td>
<td>{{ $project->detail }}</td>
<td>{{ $project->color }}</td>
<td>{{ $project->image }}</td>
<td>{{ $project->logo }}</td>
<td>{{ date_format($project->created_at, 'jS M Y') }}</td>
<td>
<form action="{{ route('projects.destroy', $project->id) }}" method="POST">
<a data-toggle="modal" id="smallButton" data-target="#smallModal"
data-attr="{{ route('projects.show', $project->id) }}" title="show">
<i class="fas fa-eye text-success fa-lg"></i>
</a>
<a class="text-secondary" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
data-attr="{{ route('projects.edit', $project->id) }}">
<i class="fas fa-edit text-gray-300"></i>
</a>
@csrf
@method('DELETE')
<button type="submit" title="delete" style="border: none; background-color:transparent;">
<i class="fas fa-trash fa-lg text-danger"></i>
</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
{!! $projects->links() !!}
<!-- small modal -->
<div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="smallBody">
<div>
<!-- the result to be displayed apply here -->
</div>
</div>
</div>
</div>
</div>
<!-- medium modal -->
<div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="mediumBody">
<div>
<!-- the result to be displayed apply here -->
</div>
</div>
</div>
</div>
</div>
<script>
// display a modal (small modal)
$(document).on('click', '#smallButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
$('#smallModal').modal("show");
$('#smallBody').html(result).show();
},
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
})
});
// display a modal (medium modal)
$(document).on('click', '#mediumButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
$('#mediumModal').modal("show");
$('#mediumBody').html(result).show();
},
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
})
});
</script>
@endsection
像这样在导入项目中提供授权值:)
public function model(array $row)
{
return new Project([
'name' => $row['name'],
'detail' => $row['detail'],
'color' => $row['color'],
'image' => $row['image'],
'logo' => $row['logo'],
'user_id' => auth()->user()->id
]);
}