Laravel 5.1 - Error create product - Resource controller - laravel

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);

Related

Trying to make select option to work in livewire

I am getting this error when I try to submit the selected option using Laravel Livewire.
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'team_id' cannot be null (SQL: insert into projects (user_id, name, description, team_id, updated_at, created_at) values (1, Sammy Mwangangi, qdqwfdweqfc wqdqwfdwqdqwdwq, ?, 2021-06-24 13:39:14, 2021-06-24 13:39:14))
App\Models\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',
'description',
'team_id',
];
// protected $guarded = [];
public function tasks(){
return $this->hasMany(Task::class);
}
public function user(){
return $this->belongsTo(User::class);
}
public function team(){
return $this->belongsTo(Team::class);
}
}
App\Http\Livewire\Project.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Project;
use App\Models\Team;
use Livewire\WithPagination;
use Illuminate\Support\Str;
use Auth;
class Projects extends Component
{
use WithPagination;
public $name;
public $description;
public $team_id;
public $projectId = null;
public $showModalForm = false;
public function showCreateProjectModal()
{
$this->showModalForm = true;
}
public function updatedShowModalForm()
{
$this->reset();
}
public function storeProject()
{
$this->validate([
'name' =>'required',
'description' => 'required',
]);
$project =new Project();
$project->user_id = auth()->user()->id;
$project->name = $this->name;
$project->description = $this->description;
$project->team_id = $this->team_id;
$project->save();
$this->reset();
session()->flash('flash.banner', 'Project created Successfully');
}
public function showEditProjectModal($id)
{
$this->reset();
$this->showModalForm = true;
$this->projectId = $id;
$this->loadEditForm();
}
public function loadEditForm()
{
$project = Project::findOrFail($this->projectId);
$this->name = $project->name;
$this->description = $project->description;
}
public function updateProject()
{
$this->validate([
'name' =>'required',
'description' => 'required',
]);
Project::find($this->projectId)->update([
'name' => $this->name,
'description' => $this->description
]);
$this->reset();
session()->flash('flash.banner', 'Project Updated Successfully');
}
public function deleteProject($id)
{
$project = Project::find($id);
$project->delete();
session()->flash('flash.banner', 'Project Deleted Successfully');
}
public function render()
{
return view('livewire.projects', [
'projects' => Project::orderBy('created_at', 'DESC')->paginate(5),
'teams' => Team::all()
]);
}
}
projects.blade.php
<div class="flex flex-wrap mb-6">
<label for="team" class="block text-gray-700 dark:text-white text-sm font-bold mb-2">
{{ __('Team') }}:
</label>
<select class="form-select px-4 py-3 w-full rounded" wire:model="team_id" name="team_id">
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->name}}</option>
#endforeach
</select>
<p class="mt-2 text-sm text-gray-500">
Select the team/department your project is associated with.
</p>
#error('team_id')
<p class="text-red-500 text-xs italic mt-4">
{{ $message }}
</p>
#enderror
</div>
What am I missing? I haven't done much with livewire regarding model relationships and how to bind data between the models.
you must do a default tag option for select, this way on change element this will bind the value to the property
<select class="form-select px-4 py-3 w-full rounded" wire:model="team_id">
<option>Select Team</option>
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->name}}</option>
#endforeach
</select>
also in the validation rules you can add another for the "team_id" value that can't be null on submit
wire:model should be on option tag not on select

How to implement a simple search function for laravel CRUD

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]);
}

how display the data of stock with the help of user table

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

use multiple for loops in a td element in laravel

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.

Form model binding doesn't work on Edit form (multiple select)

I am trying to reproduce the exact same thing as shown in Laravel 5 fundamentals by Jeffrey Way on this link https://laracasts.com/series/laravel-5-fundamentals/episodes/22
watch closely from 10:08
but my edit form is not showing the selected tags when the form was created...i probably missed something but i just can't see it.
This is my Article Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Article extends Model
{
protected $fillable = [
'title',
'body',
'published_at'
];
protected $dates = ['published_at'];
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function getTagListAttribute()
{
return $this->tags->pluck('id');
}
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFromFormat('d.m.Y H:i', $date)->format('Y-m-d H:i:s');
}
public function getPublishedAtAttribute($date)
{
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y H:i');
}
public function scopePublished($query)
{
$query->where('published_at', '<=', Carbon::now());
}
public function scopeUnpublished($query)
{
$query->where('published_at', '>', Carbon::now());
}
}
?>
Tag Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public function articles()
{
return $this->belongsToMany(Article::class);
}
}
ArticlesController
<?php
namespace App\Http\Controllers;
use App\Article;
use App\Http\Requests\ArticleRequest;
use Auth;
use App\Tag;
class ArticlesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$articles = Article::latest('published_at')->unpublished()->get();
return view('articles.index', compact('articles'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$tags = Tag::pluck('name', 'id');
return view('articles.create', compact('tags'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ArticleRequest $request)
{
//dd($request->all());
$article = Auth::user()->articles()->create($request->all());
$article->tags()->sync($request->input('tag_list'));
return redirect('articles')->with('success', "Successfully created a new Article!");
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Article $article)
{
return view('articles.show', compact('article'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(Article $article)
{
$tags = Tag::pluck('name', 'id');
return view('articles.edit', compact('article', 'tags'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(ArticleRequest $request, Article $article)
{
$article->update($request->all());
$article->tags()->sync($request->input('tag_list'));
return redirect('articles')->with('success', "Successfully updated the Article!");
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Article $article)
{
//
}
}
?>
edit.blade.php view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading"><h1>Edit {{ $article->title }}</h1></div>
<div class="panel-body">
{!! Form::model($article, ['method' => 'PATCH', 'action' => ['ArticlesController#update', $article->id]]) !!}
#include('articles._form', ['submitButtonText' => 'Update Article'])
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
_form.blade.php partial
<div class="form-group">
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('published_at', 'Published On:') !!}
{!! Form::text('published_at', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('tag_list', 'Published On:') !!}
{!! Form::select('tag_list[]', $tags, null, ['class' => 'form-control', 'multiple']) !!}
</div>
<div class="form-group">
{!! Form::submit($submitButtonText, ['class' => 'btn btn-primary form-control']) !!}
</div>
so when i go to edit an article the multiple select tags are not selected:
It simply doesn't work and i don't know what is wrong.... If you need any other source code i will provide it.
You can do 2 things
In your model change
public function getTagListAttribute()
{
return $this->tags->pluck('id');
}
To:
public function getTagListAttribute()
{
$tags = $this->tags->pluck('id');
return $tags->all()
}
Or
2. Change your model from
public function getTagListAttribute()
{
return $this->tags->pluck('id');
}
To
public function getTagListAttribute()
{
return array_pluck($this->tags,'id);
}
You can try as:
{!! Form::select('tag_list', $tags, $article->tags->pluck('id')->all(), ['class' => 'form-control', 'multiple']) !!}
Docs

Resources