I stored the User id in Stock table from session user with each row of data. Now i try to retrive the data for particlar user that's loggin at the time. Only which data show in table which row match the user_id with auth user_id.
THis is my index page
#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">
Add
</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 ></i>
</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" />
<i class="fa fa-trash"></i>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
THis is my controller file which i try to display data of particular user which is loggin at the time
<?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');
}
}
there are 2 ways. first is like #Keepon said: create a relationship between the user and the stock table
2:
$user = Auth::user();
$stocks = Stock::where('user_id','=',$user->id)->get();
Please change you index function
/**
* 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'));
}
And than in your blade
#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 ></i>
</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" />
<i class="fa fa-trash"></i>
</form>
</td>
</tr>
#endforeach
The best practice is to make a MODEL RELATIONSHIP.
To make a user and stocks relationship you need to determine what relationship would you build.
In this case I will build a relationship base on what I under stand a One To Many relationship
DATABASE
Stocks Migration
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');
});
It should be look like the above code.
Then in your model you can connect the relationship of user and stocks
MODEL
User Model
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);
}
}
Stock Model
class Stock extends Model
{
protected $guarded = [];
public function user() {
return $this->belongsTo(User::class);
}
}
Then you can query on your controller the user stocks.
CONTROLLER
Stocks Controller
public function index() {
$stocks = auth()->user()->stocks;
return view('index', compact('stocks'));
}
If you want more example of eloquent relationship you can check this tutorial by Victor
add this function in User Model
public function stocks() {
return $this->hasMany(Stock::class);
}
in Stocks Controller
public function index()
{
$stocks = auth()->user()->stocks;
return view('stock.index', compact('stocks'));
}
in 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 ></i>
</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" />
<i class="fa fa-trash"></i>
</form>
</td>
#endforeach
Related
When I click the search button, this shows.
error image
It shows Error Exception for (Cannot use object of type Illuminate\Database\MySqlConnection as array )
<div class='container'>
<div class="row" >
<div class="col-md-12">
<br />
<h3 align="center">Data Pesakit</h3>
<br />
#if($message = Session::get('success'))
<div class="alert alert-success">
<p>{{$message}}</p>
</div>
#endif
<div align="right">
Add
<br />
<br />
</div>
<div class="col-md-12">
<form action="/search" method="get" class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0">
<div class="form-group">
<input class="form-control" type="search" name="search" />
<span class="form-group-btn">
<button class="btn btn-primary" type="submit">Search</button>
</span>
</div>
</form>
</div>
<table class="table table-bordered">
<tr>
<th>Nama Pertama</th>
<th>Nama Akhir</th>
<th>Kad Pengenalan</th>
<th>No Telefon</th>
<th>Alamat Rumah</th>
<th>Alamat Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach($pesakit as $row)
<tr>
<td>{{$row['namaPertama']}}</td>
<td>{{$row['namaAkhir']}}</td>
<td>{{$row['kadPengenalan']}}</td>
<td>{{$row['noTelefon']}}</td>
<td>{{$row['alamatRumah']}}</td>
<td>{{$row['email']}}</td>
<td>Edit</td>
<td><form method="post" class="delete_form" action="{{action('PesakitController#destroy',$row['id'])}}">
{{csrf_field()}}
<input type="hidden" name="_method" value="DELETE" />
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('.delete_form').on('submit', function(){
if(confirm("Are you sure you want to delete it?"))
{
return true;
}
else
{
return false;
}
});
});
</script>
#endsection
This is code for views
class PesakitController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$pesakit = Pesakit::all()->toArray();
return view('pesakit.index', compact('pesakit'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('pesakit.create');
}
public function search(Request $request)
{
$search = $request->get('search');
$pesakit = DB::table('pesakit')
->where('namaPertama', 'like', '%'.$search. '%');
return view('pesakit.index', ['pesakit'=>$pesakit]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'namaPertama' => 'required',
'namaAkhir' => 'required',
'kadPengenalan' => 'required',
'noTelefon' => 'required',
'alamatRumah' => 'required',
'email' => 'required'
]);
$pesakit = new Pesakit([
'namaPertama' => $request->get('namaPertama'),
'namaAkhir' => $request->get('namaAkhir'),
'kadPengenalan' => $request->get('kadPengenalan'),
'noTelefon' => $request->get('noTelefon'),
'alamatRumah' => $request->get('alamatRumah'),
'email' => $request->get('email')
]);
$pesakit->save();
return redirect()->route('pesakit.create')->with('success',
'Data Berjaya Disimpan');
}
/**
* 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)
{
$pesakit = Pesakit::find($id);
return view('pesakit.edit', compact('pesakit', '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, [
'noTelefon' => 'required',
'alamatRumah' => 'required'
]);
$pesakit = Pesakit::find($id);
$pesakit->noTelefon = $request->get('noTelefon');
$pesakit->alamatRumah = $request->get('alamatRumah');
$pesakit->save();
return redirect()->route('pesakit.index')->with('success', 'Data Dikemas kini');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$pesakit = Pesakit::find($id);
$pesakit->delete();
return redirect()->route('pesakit.index')->with('success', 'Data Deleted');
}
}
This is the controller
Route::get('/', function () {
return view('utama');
});
Route::resource('pesakit', 'PesakitController');
Route::resource('petugas', 'PetugasController');
Route::resource('pendaftaran', 'PendaftaranController');
Route::get('/search','PesakitController#search');
This is the Route
I try to look for simple error such as ; or misspell or something but i cannot find it. It says some array problem but does not all crud is array??
add get()
public function search(Request $request)
{
$search = $request->get('search');
$pesakit = DB::table('pesakit')
->where('namaPertama', 'like', '%'.$search. '%')->get();
return view('pesakit.index', ['pesakit'=>$pesakit]);
}
Thank you guys for helping me last time. the problem I am having right now is regarding with my view blade. This index.blade is completely working before I create the, edit and create blade. After I completed the the other two blade, I noticed the index.blade are now having Trying to get property of non-object
what I'm trying to do is to display category in products table.
Product Table
id , name, categories_id
Categories Table
id, name
Products Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Products extends Model
{
use SoftDeletes;
protected $fillable = [
'product_code',
'name',
'categories_id',
'wh1_limit_warning',
'wh2_limit_warning',
'price',
'selling_price',
'user_id'
];
protected $dates = ['deleted_at'];
public function category() {
// return $this->belongsTo(Categories::class);
return $this->belongsTo('App\Categories', 'categories_id', 'id');
}
}
Categories Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categories extends Model
{
protected $fillable = ['name'];
public function Products()
{
// return $this->hasMany(Products::class);
return $this->hasMany('App\Products', 'categories_id');
}
}
Index Blade
<div class="panel-body">
<div class="result-set">
<table class="table table-bordered table-striped table-hover text-center" id="data-table">
<thead>
<tr>
<th class="col-md-1 text-center">Code</th>
<th class="col-md-2 text-center">Name</th>
<th class="col-md-2 text-center">Category</th>
<th class="col-md-1 text-center"><small>Warehouse 1<br/>Limit Warning</small></th>
<th class="col-md-1 text-center"><small>Warehouse 2<br/>Limit Warning<small></th>
<th class="col-md-1 text-center">Price</th>
<th class="col-md-1 text-center">Selling Price</th>
#can('update_product', 'delete_product')
<th class="text-center col-md-1 text-center">Actions</th>
#endcan
</tr>
</thead>
<tbody>
#foreach($products as $product)
<tr>
<td>{{ $product->product_code }}</td>
<td>{{ $product->name }}</td>
<td><b>{{ $product->category->name }}</b></td>
<td>{{ $product->wh1_limit_warning }}</td>
<td>{{ $product->wh2_limit_warning }}</td>
<td>{{ $product->price }}</td>
<td>{{ $product->selling_price }}</td>
#can('update_product')
<td>
<button data-toggle="tooltip" title="Update product" onclick="window.location='{{ route('products.edit', $product) }}'" name="edit" class="action-button edit">
<i class="fas fa-edit"></i>
</button>
<form action="{{ route('products.delete', $product )}}" method="post">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button data-toggle="tooltip" title="Delete product" type="submit" class="action-button delete" onclick="return confirm('Are you sure you want to delete this?');"><i class="fas fa-trash-alt"></i></button>
</form>
</td>
#endcan
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
Products Controller
<?php
namespace App\Http\Controllers;
use App\Products;
use App\Categories;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Products::with('category')->get();
return view('products.index')->with('products',$products);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$products = Products::with('category')->get();
$categories = Categories::get()->pluck('name','id');
return view('products.create',compact('categories'))->with('products', $products);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$products = Products::create($request->only(
'product_code',
'name',
'categories_id',
'wh1_limit_warning',
'wh2_limit_warning',
'price',
'selling_price',
'user_id'
));
$this->validate($request, [
'product_code' => '',
'name' => '',
'categories_id' => 'required|integer',
'wh1_limit_warning' => 'required|integer',
'wh2_limit_warning' => 'required|integer',
'price' => 'required|integer',
'selling_price' => 'required|integer',
'user_id' => 'required|integer',
]);
flash('New product added!');
return redirect(route('products.index'));
}
/**
* Display the specified resource.
*
* #param \App\Products $products
* #return \Illuminate\Http\Response
*/
public function show(Products $products)
{
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Products $products
* #return \Illuminate\Http\Response
*/
public function edit(Products $product)
{
$products = Products::all();
$categories = Categories::all('name','id');
return view('products.edit',compact('product','categories'));
//return view('products.edit',compact('product','categories'))->with('products', $products);
// return view('products.edit', compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Products $products
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Products $product)
{
$product->update($request->only(
'product_code',
'name',
'categories_id',
'wh1_limit_warning',
'wh2_limit_warning',
'price',
'selling_price',
'user_id'
));
return redirect()->route('products.index');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Products $products
* #return \Illuminate\Http\Response
*/
public function destroy(Products $product)
{
$product->delete();
return redirect(route('products.index'));
}
}
I can't see where did I go wrong because I did not change anything in public function index() of my controller. Again, EDIT and Create is workingI was able to display the categories in dropdown with no any issue only this index.blade.
Please see this screenshot of the issue
Thank you so much in advance!
My guess is that your query returns an array instead of an object. Try dumping your return to make sure.
If it is an array, you can try using [] instead of -> in your index.blade.php:
<td><b>{{ $product->category['name'] }}</b></td>
Seems there will be some product which don't have any category. So that product wont be linked with any category and it won't have any category object that's why it is giving this error.
You can add a check before displaying the category name that product contains category or not.
<td><b>{{ $product->category ? $product->category->name : "" }}</b></td>
I am working on laravel mini project, I have couple small issues, but this one is pretty tricky, I checked all possible solution, nothing worked.
When I click on download, downloading process starts, but then I got message in Failed - Server Problem.
I would like download file named in format name-last_name.txt, incase there are two people with the same name name-last_name/2.txt
If you can share with me any knowledge is the correct process of it, I will appreciate a lot
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Storage;
use App\Client;
class FormsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$clients = Client::all();
return view('/index')->with('clients', $clients);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view ('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, [
'name' => 'required',
'last_name' => 'required',
'phone'=> 'required',
'agree'=> 'required'
]);
$client = new Client;
$client->name = $request->input('name');
$client->last_name = $request->input('last_name');
$client->phone = $request->input('phone');
$client->call_time = $request->input('call_time');
$client->agree = $request->input('agree');
$client->save();
return redirect('/')->with('success', 'Klient vytvořen');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
$client = Client::find($id);
return view ('show')->with('client', $client);
}
public function download(){
$client = Client::find($id);
return response()->download($pathToFile);
}
}
Blade File is
#extends('layout')
#section('content')
<div class="row">
<div class="col-9 mt-5">
<h1>Seznam klientů</h1>
</div>
<div class="col-3 mt-5">
<h6>Nový klient</h6>
</div>
</div>
<div class="container">
#if(count($clients)>0)
<ul class="list-group">
<table class="table">
#foreach($clients as $client)
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Jméno</th>
<th scope="col">Příjmení</th>
<th scope="col">Telefonní číslo</th>
<th scope="col">Provolaný čas</th>
<th scope="col">Souhlas</th>
<th scope="col">Stahnout data</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"> </th>
<td>{{$client->name}}</td>
<td>{{$client->last_name}}</td>
<td>{{$client->phone}}</td>
<td>{{$client->call_time}}</td>
<td>{{$client->agree}}</td>
<td><a href="download/{{$client->name}}"
download="{{$client->name}}">
<button type="button" class="btn btn-
primary">
Download
</button>
</a></td>
</tr>
</tbody>
</table>
#endforeach
</ul>
#else
<p>Seznam je prázdny</p>
#endif
</div>
#endsection
Route
Route::resource('/', 'FormsController');
Route::get('/{$id}', 'FormsController#download');
Hello guys i have 3 eloquent tables members, pledge and campaign and they are have a relationship amongst each other namely:
for member model
protected $table = "members";
public function loans()
{
return $this->hasMany(Loan::class, 'borrower_id', 'id');
}
public function user()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function pledges()
{
return $this->hasMany(Pledge::class, 'member_id', 'id');
}
for campaign
protected $table = "campaigns";
public function pledges()
{
return $this->hasMany(Pledge::class, 'campaign_id', 'id')->orderBy('created_at', 'desc');
}
}
then for pledge model
protected $table = "pledges";
public function campaign()
{
return $this->hasOne(Campaign::class, 'id', 'campaign_id');
}
public function member()
{
return $this->hasOne(Member::class, 'id', 'member_id');
}
}
IN the plegde.create.blade
<div class="control-group">
<label class="control-label">Member</label>
<div class="controls">
<select>
#foreach ($member as $members)
<option>{{ $members->first_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Campaign</label>
<div class="controls">
<select>
#foreach ($campaign as $campaigns)
<option>{{ $campaigns->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Amount</label>
<div class="controls">
<input type="number" name="amount" id="required" value="{{ old('amount') }}">
#if ($errors->has('amount'))
<p class="alert alert-danger">{{ $errors->first('amount') }}
#endif
</div>
</div>
<div class="control-group">
<label class="control-label">Date (mm-dd)</label>
<div class="controls">
<div data-date="2012-11-02" class="input-append date datepicker">
<input type="text" name="date" value="2012-11-02" data-date-format="yyyy-mm-dd" class="span11" value="{{ old('date') }}">
#if ($errors->has('date'))
<p class="alert alert-danger">{{ $errors->first('date') }}
#endif
<span class="add-on"><i class="icon-th"></i></span> </div>
</div>
</div>
<div class="control-group">
<label class="control-label">Description</label>
<div class="controls">
<input type="text" name="notes" id="required" value="{{ old('notes') }}">
#if ($errors->has('notes'))
<p class="alert alert-danger">{{ $errors->first('notes') }}
#endif
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-success">
</div>
</form>
then in my pledge.index.blade.php i have this but it is not showing proerly this is the code
<div class="widget-content nopadding">
<table class="table table-bordered data-table">
<thead>
<tr>
<th>#ID</th>
<th>Campaign</th>
<th>Member</th>
<th>Amount</th>
<th>Date</th>
<th>Notes</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="gradeX">
#foreach ($member as $members)
<td>{{ $members->first_name }}</td>
#endforeach
#foreach ($campaign as $campaigns)
<td>{{ $campaigns->name }}</td>
#endforeach
#foreach ($pledge as $pledges)
<td>{{ $pledges->amount }}</td>
#endforeach
#foreach ($pledge as $pledges)
<td>{{ $pledges->date }}</td>
#endforeach
</tr>
</tbody>
</table>
</div>
Any help would be appreciated.
These are the controllers
Campaign Controller
use App\Campaign;
use Illuminate\Http\Request;
class CampaignController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$campaign = Campaign::all();
return view('campaign.index', compact('campaign'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('campaign.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, [
'name'=>'required',
'goal'=> 'required',
]);
// return $request->all();
$campaign = new Campaign;
$campaign->name = $request->name;
$campaign->goal = $request->goal;
$campaign->notes= $request->notes;
$campaign->save();
return redirect (route('campaign.index'));
}
PLedge Controller
use App\Campaign;
use App\Member;
use App\Pledge;
use Illuminate\Http\Request;
class Pledgecontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$member= Member::all();
$campaign= Campaign::all();
$pledge= Pledge::all();
return view ('pledges.index', compact ('member', 'campaign', 'pledge'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$member= Member::all();
$campaign= Campaign::all();
$pledge= Pledge::all();
return view ('pledges.create', compact ('member', 'campaign', 'pledge'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$pledge= new Pledge;
$pledge->member_id = $request->member_id;
$pledge->campaign_id = $request->campaign_id;
$pledge->amount = $request->amount;
$pledge->date = $request->date;
$pledge->notes = $request->notes;
$pledge->save();
return redirect (route('pledge.index'));
// return $request->all();
}
Member Controller
use App\Member;
use Illuminate\Http\Request;
class MemberController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$member = Member::all();
return view('member.index', compact('member'));
// return view ('member.data');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view ('member.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, [
'first_name'=> 'required',
'middle_name'=>'required',
'last_name'=>'required',
'gender'=> 'required',
'marital_status'=> 'required',
'status'=> 'required',
'mobile_phone'=> 'required',
'address'=> 'required',
'email'=> 'required',
'dob'=> 'required',
'photo'=> 'required | image|mimes:jpeg,png,jpg,gif,svg|max:700',
]);
if ($request->hasFile('photo')) {
// $request->photo->store('public');
$imageName= $request->photo->store('public');
}
$member = new Member;
$member->first_name = $request->first_name;
$member->middle_name = $request->middle_name;
// $member->photo = $request->photo;
$member->photo = $imageName;
$member->last_name = $request->last_name;
$member->gender = $request->gender;
$member->marital_status = $request->marital_status;
$member->status = $request->status;
$member->mobile_phone = $request->mobile_phone;
$member->address = $request->address;
$member->email = $request->email;
$member->dob = $request->dob;
$member->save();
return redirect (route('member.index'));
}
/**
* 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)
{
$member = Member::where('id', $id)->get();
return view ('member.edit', compact('member'));
}
/**
* 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, [
'first_name'=> 'required',
'middle_name'=>'required',
'last_name'=>'required',
'gender'=> 'required',
'marital_status'=> 'required',
'status'=> 'required',
'mobile_phone'=> 'required',
'address'=> 'required',
'email'=> 'required',
'dob'=> 'required',
'photo'=> 'required | image|mimes:jpeg,png,jpg,gif,svg|max:700',
]);
if ($request->hasFile('photo')) {
// $request->photo->store('public');
$imageName= $request->photo->store('public');
}
$member = Member::find($id);
$member->first_name = $request->first_name;
$member->middle_name = $request->middle_name;
// $member->photo = $request->photo;
$member->photo = $imageName;
$member->last_name = $request->last_name;
$member->gender = $request->gender;
$member->marital_status = $request->marital_status;
$member->status = $request->status;
$member->mobile_phone = $request->mobile_phone;
$member->address = $request->address;
$member->email = $request->email;
$member->dob = $request->dob;
$member->save();
return redirect (route('member.index'));
// return $request->all();
}
This is not a good solution. Same table, different models, different foreachs.
You can make just one foreach and function. Like this:
public function memberFunction()
{
return $this->hasOne('App\Member');
}
//
public function campaignFunction()
{
return $this->hasOne('App\Campaign');
}
We made the connection as a function. Now inside the foreach use the function with [' '] tags.
#foreach ($example as $examples)
<td>{{ $examples->memberFunction['firstname'] }}</td>
<td> {{ $examples->campaignFunction['name'] }} </td>
#endforeach
you can continue like this.
i created a resource controller (CRUD) to manage products, about update,delete work good. But CREATE doesnt work. i need specific that each product have a author relation and category relation.
THE ERROR:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (2016.products,
CONSTRAINT products_user_id_foreign FOREIGN KEY (user_id)
REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into
products (updated_at, created_at) values (2016-05-10 18:34:38,
2016-05-10 18:34:38))
PRODUCTCONTROLLER.PHP
namespace dixard\Http\Controllers\Admin;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Product;
use dixard\Category;
use dixard\User;
// ci serve per validare
use Validator;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::orderBy('id', 'desc')->paginate(20);
return view('admin.product.index', compact('products'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//prendo informazioni sulla categorie, mi prendo is e name.
// quando l'Admin crea un prodotto POTRA scegliere la categoria
$categories = Category::orderBy('id', 'desc')->lists('name', 'id');
$users = User::orderBy('id', 'desc')->lists('username', 'id');
return view('admin.product.create', compact('categories', 'users'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rules = [
'name' => 'required',
'description' => 'required',
'price' => 'required',
'image' => 'required',
];
$messages = [
'name.required' => 'Campo titolo prodotto richiesto',
'description.required' => 'Campo descrizione richiesto',
'price.required' => 'Campo prezzo richiesto',
'image.required' => 'Campo Url immagine richiesto'
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect('admin/product/create')->withErrors($validator);
}else {
$visible = (isset($_POST['visible']) == '1' ? '1' : '0');
$data = [
'name' => $request->get('name'),
'slug' => $request->get('name'),
'description' => $request->get('description'),
'extract' => $request->get('description'),
'price' => $request->get('price'),
'image' => $request->get('image'),
'visibile' => $visible,
];
$product = Product::create($data);
return redirect('admin/product')->with('message', 'Prodotto creato con successo!');
//return $data;
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return $product;
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(Product $product, User $user)
{
$categories = Category::orderBy('id', 'desc')->lists('name', 'id');
$users = User::orderBy('id', 'desc')->lists('username', 'id');
return view('admin.product.edit', compact('categories', 'users','product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
$id= $request->get('id');
// i want ignora id of user edited
$rules = [
'name' => 'required|unique:products'.',name,' . $id,
'description' => 'required',
'price' => 'required',
'image' => 'required',
];
$messages = [
'name.required' => 'Campo titolo prodotto richiesto',
'name.unique' => 'Campo titolo già esistente',
'description.required' => 'Campo descrizione richiesto',
'price.required' => 'Campo prezzo richiesto',
'image.required' => 'Campo Url immagine richiesto'
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect()->route('admin.product.edit', $request->get('id'))->withErrors($validator)->withInput();
}
// if there is not any error go to update
else{
// if email id different by input, so if email input update also email
if( $product->name != $request->get('name') ){
$s = new Product;
$visible = (isset($_POST['visible']) == '1' ? '1' : '0');
$data = array(
'name' => $request->get('name'),
'slug' => $request->get('name'),
'description' => $request->get('description'),
'extract' => $request->get('description'),
'price' => $request->get('price'),
'image' => $request->get('image'),
'name' => $request->get('name'),
'user_id' => $request->get('user_id'),
'category_id' => $request->get('category_id'),
'visible' => $visible,
);
$s->where('id', '=', $request->get('id'))->update($data);
return redirect('admin/product')->with('message', 'Utente aggiornato con successo!');
}
// If email input doesnt change update all ( not email)
else{
$s = new Product;
$visible = (isset($_POST['visible']) == '1' ? '1' : '0');
$data = array(
'slug' => $request->get('name'),
'description' => $request->get('description'),
'extract' => $request->get('description'),
'price' => $request->get('price'),
'image' => $request->get('image'),
'name' => $request->get('name'),
'user_id' => $request->get('user_id'),
'category_id' => $request->get('category_id'),
'visible' => $visible,
);
$s->where('id', '=', $request->get('id'))->update($data);
return redirect('admin/product')->with('message', 'Utente aggiornato con successo!');
}
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$deleted=$product->delete();
if(isset($deleted))
{
return redirect('admin/product')->with('message', 'Prodotto eliminato con successo!');
} else {
return redirect('admin/product')->with('message-error', 'Prodotto non eliminato');
}
}
}
CREATE.PHP
{!! Form::open(['route'=>'admin.product.store', 'class'=>'form-horizontal form-label-left']
)!!}
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Titolo Prodotto<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="name" name="name" class="form-control col-md-7 col-xs-12" placeholder="titolo prodotto">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="lastname">Descrizione<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="textarea" id="description" name="description" class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">Prezzo €<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="price" name="price" class="form-control col-md-7 col-xs-12" placeholder="prezzo">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">Immagine<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="image" name="image" class="form-control col-md-7 col-xs-12" placeholder="Url immagine">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">Categoria<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{!! Form::select('category_id', $categories, null, ['class'=>'form-control col-md-7 col-xs-12'])!!}
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">Autore<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{!! Form::select('user_id', $users, null, ['class'=>'form-control col-md-7 col-xs-12'])!!}
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="active">Attivo
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="checkbox" name="visible" id="checkbox-create" class="form-control col-md-7 col-xs-12 js-switch" value="1" checked>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
Indietro
<button type="submit" class="btn btn-success">Crea Prodotto</button>
</div>
</div>
{!! Form::close()!!}
ROUTES.PHP (about CRUD products)
Route::bind('product', function($id) {
return dixard\Product::where('id', $id)->first();
});
Route::get('admin', function(){
return view('admin.index')
;
});
Route::resource('admin/category','Admin\CategoryController');
Route::bind('category', function($category){
return dixard\Category::find($category);
});
////////////////// ADMIN Users ///////////////////////////////////////////////
Route::resource('admin/user','Admin\UserController');
Route::bind('user', function($user){
return dixard\User::find($user);
});
////////////////// ADMIN PRODUCT ////////////////////////////////////////////////
Route::resource('admin/product','Admin\ProductController');
MODEL USER
namespace dixard;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use dixard\Product;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'username',
'lastname',
'birth',
'profile',
'country',
//'province',
//'address',
//'address2',
//'phone',
'usertype',
'email',
'password',
'social',
'confirm_token',
'active',
];
// Ogni utente HA tanti prodotti.
public function products()
{
return $this->hasMany('dixard\Product');
}
//--//
MODEL PRODUCT
namespace dixard;
use Illuminate\Database\Eloquent\Model;
use dixard\User;
use dixard\Category;
class Product extends Model
{
protected $table = 'products';
protected $fillabile = ['name','slug','description','extract','image','visible','price',
'category_id','user_id'];
public function user() {
return $this->belongsTo('dixard\User');
}
public function category() {
return $this->belongsTo('dixard\Category');
}
//----//
public function __construct()
{
if(!\Session::has('cart')) \Session::put('cart',array());
}
}
MODEL CATEGORY
<?php
namespace dixard;
use Illuminate\Database\Eloquent\Model;
use dixard\Product;
class Category extends Model
{
protected $table = 'categories';
// gli dico che voglio scrivere questo campi
protected $fillable = [
'name',
'slug',
'description',
'color',
];
public $timestamps = false;
public function products() {
return $this->hasMany('dixard\Product');
}
}.
MIGRATION USER
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('lastname');
$table->string('username')->default('Utente');
$table->string('birth');
$table->string('profile')->default('image-profile/profilo.png');
$table->string('country')->default('Paese');
//$table->string('province')->default('Città');
//$table->string('address');
//$table->string('address2');
//$table->string('phone');
$table->string('usertype');
$table->string('email')->unique();
$table->string('password', 60);
$table->boolean('social');
$table->boolean('active')->default(0);
$table->string('confirm_token', 100);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
MIGRATION PRODUCT
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
//Up creare table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->string('slug');
$table->text('description');
//mostrare una piccola descrizione del prodotto
$table->string('extract', 300);
$table->decimal('price', 5, 2);
$table->string('image', 300);
//vedere se pubblico o no
$table->boolean('visible');
// unsigned solo valori positivi
//e fa riferimento al id category,
//Se si cancella, cancellerà tutti i prodotti con quella categoria
//Ogni prodotto ha una categoria
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->integer('category_id')->unsigned();
// relazioni
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
//crea // Ogni prodotto ha un autore( artista)
// ----//
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
//eliminare table
public function down()
{
Schema::drop('products');
}
}
MIGRATION CATEGORY
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255)->unique();
//Slug Nome facile per URL
$table->string('slug');
$table->text('description');
//dargli un colore
$table->string('color', 30);
//$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('categories');
}
}
I have one user registered, so user ID 1 exist.
Thank you for your help!
Ok, your name conventions seems to be right, now you are forgetting to enter the user_id to your product, so it wont have the 1-N relationship.
According to Laravel's documentation, you have to use the method save on the user->product().
$userID = Auth::user()->id; // i dont know how are you setting the authentication, but i will assume its the default.
$userObject = User::find($userID);
... do all the things with product.
$userObject->products()->save($product);