laravel - 尝试为特定用户 ID 存储和编辑产品
问题描述
在这里,我尝试存储和编辑特定 ID 的产品。用户可以在哪里拥有某些产品,并且可以为该特定用户编辑这些产品。我试图这样做,但不知道发生了什么问题。有人能帮我吗。在此先感谢这是我的 ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::latest()->paginate(20);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 5) - 1) * 5);
}
function authapi(Request $request)
{
$user = User:: where('email', $request->email)->first();
if(!$user || !Hash::check($request->password, $user->password)){
return response([
'message' => ['These credentials do not match our records.']
],404);
}
$token = $user -> createToken('my-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response,201);
}
function all_app_jsons(){
return Product::all();
}
function search_by_name($name){
return Product::where('name','like','%'.$name.'%')->get();
}
function search_by_id($id){
return Product::where('id',$id)->get();
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//$tag = Product::create($request->all());
//return redirect()->route('admin.tags.index');
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:1024',
]);
$input = $request->all();
// $request->validated();
$input['user_id'] = auth()->user()->id;
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}
Product::create($input);
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
// public function update(Request $request, Product $product)
public function update(Request $request, $productId)
{
$product = auth()->user()->products()->findOrFail($productId);
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}else{
unset($input['logo']);
}
$product->update($input);
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
// function indextwo(){
// //return DB::select("select * from products");
// //DB::table('products')->orderBy('id','desc')->first();
// return Product::orderBy('id', 'DESC')->first();
// }
}
在 ProductController.php $product = auth()->user()->products()->findOrFail($productId);
这一行中说products()
id undefined 这是我的模型 Product.php
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function user(){
return $this->belongsTo(User::class);
}
}
这是我的 User.php 模型
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
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',
];
public function products(){
return $this->hasMany(Product::class);
}
}
这是产品表
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
});
Schema::table('products', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users');
});
}
注意:我可以存储许多产品,但不能存储特定用户。我可以存储和编辑每个用户都可以访问的产品。但我希望特定用户将拥有一些其他用户无法访问的产品
解决方案
$table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade'); 我在项目表上使用了这个
推荐阅读
- dji-sdk - 如何从无人机获取原始视频
- reactjs - 反应原生 - 不变违规:不支持动态更改 onViewableItemsChanged
- android - 如何为android中的图像赋予不同的帧或大小?
- c# - 无法将内容从 restsharp 放到 db
- javascript - 如何使用 uber h3-js 在具有多个数据点的多边形内和具有质心纬度/经度、半径的圆内查找位置?
- c++ - 结构中的 OMP 数据依赖数组
- javascript - 如何从javascript中的绝对路径点找到svg viewbox?
- rest - 如果我使用 POST 进行幂等操作,我会有什么风险?
- reactjs - react.js 无法通过参数读取图片
- ios - 底部安全区域颜色通过半透明键盘 iOS