【问题标题】:how display the data of stock with the help of user table如何在用户表的帮助下显示库存数据
【发布时间】:2019-09-10 16:18:49
【问题描述】:

我将会话用户的用户 ID 与每一行数据一起存储在 Stock 表中。现在我尝试检索当时正在登录的特定用户的数据。只有哪些数据显示在表中的哪一行匹配 user_id 和 auth user_id。 这是我的索引页

    @extends('layouts.app')

@section('content')

  @if($message = Session::get('success'))
  <div class="alert alert-success">
   <p>{{$message}}</p>
  </div>
  @endif
  <div class="row">
          <div class="col-md-12">
            <div class="card">
              <div class="card-header">
                <h4 class="card-title"> Stock
                <div align="right">
   <a href="{{route('stock.create')}}" class="btn btn-primary">Add</a>

  </div></h4>

              </div>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table">
                    <thead class=" text-primary">
    <th>Product Name</th>
    <th>Product code</th>
    <th>deatils</th>
    <th>Price</th>
    <th>Cost</th>
    <th>Quantity</th>
    <th></th>
    </thead>
    <tbody>

    @foreach($stocks as $row Auth::user()->user_id == user_if)
    <tr>
    <td>{{$row['product_name']}}</td>
    <td>{{$row['product_code']}}</td>
     <td>{{$row['details']}}</td>
      <td>{{$row['price']}}</td>
       <td>{{$row['cost']}}</td>
        <td>{{$row['quntity']}}</td>
    <td ><a  href="{{action('StockController@edit', $row['id'])}}" ><i class="fa fa-edit"></i></a>
    </td>
    <td>
     <form id="my_form"  method="post" class="delete_form" action="{{action('StockController@destroy', $row['id'])}}">
      {{csrf_field()}}
      <input type="hidden" name="_method" value="DELETE" />
      <a href="javascript:{}" onclick="document.getElementById('my_form').submit();"><i class="fa fa-trash"></i></a>
     </form>
    </td>
   </tr>
   @endforeach

                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

</div>
</div>

@endsection

这是我的控制器文件,我尝试显示当时正在登录的特定用户的数据

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Stock;
use Auth;
class StockController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $stocks = Stock::all()->toArray();
        return view('stock.index', compact('stocks'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('stock.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'user_id' =>'required',
            'product_name'    =>  'required',
            'product_code'     =>  'required',
             'details'    =>  'required',
            'price'     =>  'required',
            'cost'    =>  'required',
            'quntity'     =>  'required'
        ]);
        $stock = new Stock([
            'user_id' =>  $request->get('user_id'),  
           'product_name'    =>  $request->get('product_name'),
            'product_code'    =>  $request->get('product_code'),
            'details'    =>  $request->get('details'),
            'price'    =>  $request->get('price'),
            'cost'    =>  $request->get('cost'),
            'quntity'     =>  $request->get('quntity')
]);
        $stock->save();
        return redirect()->route('stock.index')->with('success', 'Data Added');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
       $stock = Stock::find($id);
        return view('stock.edit', compact('stock', 'id'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
         $this->validate($request, [
             'product_name'    =>  'required',
            'product_code'     =>  'required',
             'details'    =>  'required',
            'price'     =>  'required',
            'cost'    =>  'required',
            'quntity'     =>  'required'
        ]);
        $stock = Stock::find($id);
        $stock->product_name = $request->get('product_name');
        $stock->product_code = $request->get('product_code');
        $stock->details = $request->get('details');
        $stock->price = $request->get('price');
        $stock->cost = $request->get('cost');
        $stock->quntity = $request->get('quntity');
        $stock->save();
        return redirect()->route('stock.index')->with('success', 'Data Updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
         $stock = Stock::find($id);
        $stock->delete();
        return redirect()->route('stock.index')->with('success', 'Data Deleted');
    }
}

【问题讨论】:

  • @foreach($stocks as $row Auth::user()->user_id == user_if) user_if 中可能有错字
  • 您需要在 User 和 Stock 之间建立关系。关注documentation。然后只需调用Auth::user()-&gt;stocks 而不是Stock::all()。然后,您可以使用常规的 foreach 循环进行迭代,而无需过滤掉用户。

标签: laravel


【解决方案1】:

有两种方法。首先就像@Keepon说的:在用户和库存表之间建立关系

2:

$user = Auth::user();
$stocks =  Stock::where('user_id','=',$user->id)->get();

【讨论】:

    【解决方案2】:

    请更改您的索引功能

     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
    
        $stocks = Stock::where('user_id', Auth::id())->get();
        return view('stock.index', compact('stocks'));
    }
    

    比在你的刀片中

     @foreach($stocks as $stock)
    <tr>
    <td>{{$stock->product_name}}</td>
    <td>{{$stock->product_code}}</td>
     <td>{{$stock->details}}</td>
      <td>{{$stock->price}}</td>
       <td>{{$stock->cost}}</td>
        <td>{{$stock->quntity}}</td>
    <td ><a  href="{{action('StockController@edit', $stock->id)}}" ><i class="fa fa-edit"></i></a>
    </td>
    <td>
     <form id="my_form"  method="post" class="delete_form" action="{{action('StockController@destroy', $stock->id)}}">
      {{csrf_field()}}
      <input type="hidden" name="_method" value="DELETE" />
      <a href="javascript:{}" onclick="document.getElementById('my_form').submit();"><i class="fa fa-trash"></i></a>
     </form>
    </td>
    </tr>
     @endforeach
    

    【讨论】:

      【解决方案3】:

      最好的做法是创建一个MODEL RELATIONSHIP

      要建立用户和股票关系,您需要确定要建立什么样的关系

      在这种情况下,我将根据我理解的一对多关系建立关系

      数据库

      股票迁移

      Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        ...
        $table->timestamps();
      
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
      });
      

      它应该看起来像上面的代码。 然后在您的模型中,您可以连接 userstocks

      的关系

      型号

      用户模型

      class User extends Authenticatable
      {
          use Notifiable;
      
          /**
           * 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',
          ];
      
          /**
           * The attributes that should be cast to native types.
           *
           * @var array
           */
          protected $casts = [
              'email_verified_at' => 'datetime',
          ];
      
          public function stocks() {
            return $this->hasMany(Stock::class);
          }
      }
      

      库存模型

      class Stock extends Model
      {
          protected $guarded = [];
      
          public function user() {
              return $this->belongsTo(User::class);
          }
      }
      

      然后您可以在控制器上查询用户股票。

      控制器

      库存控制人

      public function index() {
        $stocks = auth()->user()->stocks;
      
        return view('index', compact('stocks'));
      }
      

      如果您想要更多雄辩的关系示例,您可以查看 Victor 的 tutorial

      【讨论】:

        【解决方案4】:

        在用户模型中添加此功能

        public function stocks() {
          return $this->hasMany(Stock::class);
        }
        

        在库存控制器中

        public function index()
        {
            $stocks = auth()->user()->stocks;
            return view('stock.index', compact('stocks'));
        }
        

        在 index.blade.php 中

        @foreach($stocks as $row)
        <tr>
        <td>{{$row['product_name']}}</td>
        <td>{{$row['product_code']}}</td>
         <td>{{$row['details']}}</td>
          <td>{{$row['price']}}</td>
           <td>{{$row['cost']}}</td>
            <td>{{$row['quntity']}}</td>
        <td ><a  href="{{action('StockController@edit', $row['id'])}}" ><i class="fa fa-edit"></i></a>
        </td>
        <td>
         <form id="my_form"  method="post" class="delete_form" action="{{action('StockController@destroy', $row['id'])}}">
          {{csrf_field()}}
          <input type="hidden" name="_method" value="DELETE" />
          <a href="javascript:{}" onclick="document.getElementById('my_form').submit();"><i class="fa fa-trash"></i></a>
         </form>
        </td>
        

        @endforeach

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-15
          • 1970-01-01
          • 2017-08-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多