Laravel 5.1 - Get data from 2 relations table - php

i'm doing a ecommerce, i created a resource controller for ORDERS. But i have some problem to get information about the products. i would like show all items orders with information about the products buyed, like name, price, category. Each order item have a "product_id" relation.
i have this tables migration:
Orders
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrdersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->decimal('subtotal', 5, 2);
$table->decimal('shipping', 5,2);
$table->text('method');
$table->text('status');
$table->text('order_code');
$table->text('fullname_ship');
$table->text('address_ship');
$table->text('app_ship');
$table->text('province_ship');
$table->text('country_ship');
$table->text('email_ship');
$table->text('phone_ship');
$table->text('fullname_bill');
$table->text('address_bill');
$table->text('app_bill');
$table->text('province_bill');
$table->text('country_bill');
$table->text('email_bill');
$table->text('phone_bill');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('orders');
}
}
Orders items
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrderItemsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('orders_items', function (Blueprint $table) {
$table->increments('id');
$table->decimal('price', 5, 2);
$table->integer('quantity')->unsigned();
$table->integer('product_id')->unsigned();
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
$table->integer('order_id')->unsigned();
$table->foreign('order_id')
->references('id')
->on('orders')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('order_items');
}
}
Products table
<?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');
$table->string('extract', 300);
$table->decimal('price', 5, 2);
$table->string('image', 300);
$table->boolean('visible');
$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');
}
}
My OrderController.php
<?php
namespace dixard\Http\Controllers\Admin;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Order;
use dixard\OrderItem;
use dixard\Product;
use dixard\Category;
use Validator;
class OrderController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$orders = Order::orderBy('id')->paginate(15);
return view('admin.order.index', compact('orders'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view ('admin.order.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rules = [
'status' => 'required',
'method' => 'required',
'order_code' => 'required',
'fullname_ship' => 'required',
'address_ship' => 'required',
'app_ship' => 'required',
'province_ship' => 'required',
'country_ship' => 'required',
'email_ship' => 'required',
'phone_ship' => 'required',
];
$messages = [
'status.required' => 'Status ordine richiesto',
'method.required' => 'Metodo di pagamento richiesto',
'order_code.required' => 'Codice ordine richiesto',
'fullname_ship.required' => 'Nome e cognome richiesto',
'address_ship.required' => 'Indirizzo spedizione richiesto',
'app_ship.required' => 'App/Interno richiesto',
'province_ship.required' => 'Città/Provincia di spedizione richiesto',
'country_ship.required' => 'Paese di spedizione richiesto',
'email_ship.required' => 'Email campo richiesto',
'phone_ship.required' => 'Cellulare/spedizione richiesto',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect('admin/order/create')->withErrors($validator);
}else {
$data = [
'status' => $request->get('status'),
'method' => $request->get('method'),
'order_code' => $request->get('order_code'),
'shipping' => $request->get('shipping'),
'subtotal' => $request->get('subtotal'),
'fullname_ship' => $request->get('fullname_ship'),
'address_ship' => $request->get('address_ship'),
'app_ship' => $request->get('app_ship'),
'province_ship' => $request->get('province_ship'),
'country_ship' => $request->get('country_ship'),
'email_ship' => $request->get('email_ship'),
'phone_ship' => $request->get('phone_ship'),
'fullname_bill' => $request->get('fullname_bill'),
'address_bill' => $request->get('address_bill'),
'app_bill' => $request->get('app_bill'),
'province_bill' => $request->get('province_bill'),
'country_bill' => $request->get('country_bill'),
'email_bill' => $request->get('email_bill'),
'phone_bill' => $request->get('phone_bill'),
];
$order = Order::create($data);
return redirect('admin/order')->with('message', 'Ordine creato!');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Order $order)
{
$items = OrderItem::orderBy('id', 'desc')->paginate(20);
$items_product_id = $items->product_id;
$items_products=Product::with('items_product_id')->get();
//$products = Product::where('id', $items->product_id)->orderBy('id', 'desc');
return view('admin.order.show', compact('items','items_products'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(Order $order)
{
return View('admin.order.edit', compact('order'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Order $order)
{
$id= $order->id;
$rules = [
'status' => 'required',
'order_code' => 'required',
'shipping' => 'required',
'subtotal' => 'required',
'fullname_ship' => 'required',
'address_ship' => 'required',
'app_ship' => 'required',
'province_ship' => 'required',
'country_ship' => 'required',
'email_ship' => 'required',
'phone_ship' => 'required',
];
$messages = [
'status.required' => 'Status ordine richiesto',
'order_code.required' => 'Codice ordine richiesto',
'shipping.required' => 'Costo spedizione richiesto',
'subtotal.required' => 'Totale costo prodotti - SUBTOTAL richiesto',
'fullname_ship.required' => 'Nome e cognome richiesto',
'address_ship.required' => 'Indirizzo spedizione richiesto',
'app_ship.required' => 'App/Interno richiesto',
'province_ship.required' => 'Città/Provincia di spedizione richiesto',
'country_ship.required' => 'Paese di spedizione richiesto',
'email_ship.required' => 'Email campo richiesto',
'phone_ship.required' => 'Cellulare/spedizione richiesto',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect()->route('admin.order.edit', $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
$s = new Order;
$data = array(
'status' => $request->get('status'),
'method' => $request->get('method'),
'order_code' => $request->get('order_code'),
'shipping' => $request->get('shipping'),
'subtotal' => $request->get('subtotal'),
'fullname_ship' => $request->get('fullname_ship'),
'address_ship' => $request->get('address_ship'),
'app_ship' => $request->get('app_ship'),
'province_ship' => $request->get('province_ship'),
'country_ship' => $request->get('country_ship'),
'email_ship' => $request->get('email_ship'),
'phone_ship' => $request->get('phone_ship'),
'fullname_bill' => $request->get('fullname_bill'),
'address_bill' => $request->get('address_bill'),
'app_bill' => $request->get('app_bill'),
'province_bill' => $request->get('province_bill'),
'country_bill' => $request->get('country_bill'),
'email_bill' => $request->get('email_bill'),
'phone_bill' => $request->get('phone_bill'),
);
$s->where('id', '=', $request->get('id'))->update($data);
return redirect('admin/order')->with('message', 'Ordine aggiornato con successo!');
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Order $order)
{
$deleted=$order->delete();
if(isset($deleted))
{
return redirect('admin/order')->with('message', 'Ordine eliminato con successo!');
} else {
return redirect('admin/order')->with('message-error', 'Ordine non eliminato');
}
}
}
I created the view show.blade.php to show all items ordered, i would like show all items with information about the products, like name, price, category. Each order item have a "product_id" relation.
i'm trying so in show.blade.php:
#foreach($items as $item)
<tr class="even pointer">
<td class=" ">{{ $item->id }}</td>
<td class=" ">{{ $item->product_id }}</td>
<td class=" ">{{ $item->quantity }}</td>
<td class=" ">€{{ $item->order_id }}</td>
</td>
</td>
</tr>
#endforeach
#foreach($items_products as $items_product)
<tr class="even pointer">
<td class=" ">{{ $items_product->id }}</td>
<td class=" ">{{ $items_product->name }}</td>
<td class=" ">{{ $items_product->price }}</td>
<td class=" ">€{{ $items_product->description }}</td>
</td>
</td>
</tr>
#endforeach
But it doesnt work. Thank you for your help! if you need models:
Product MODEL
namespace dixard;
use Illuminate\Database\Eloquent\Model;
use dixard\User;
use dixard\Category;
use dixard\OrderItem;
class Product extends Model
{
protected $table = 'products';
protected $fillable =
[
'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 OrderItem() {
return $this->belongsTo('dixard\OrderItem');
}
}
Order items MODEL
<?php
namespace dixard;
use Illuminate\Database\Eloquent\Model;
use dixard\Product;
class OrderItem extends Model
{
// DIrgli che ci lascia scrivere
protected $table = 'orders_items';
protected $fillable = [
'price',
'quantity',
'product_id',
'order_id'
];
public $timestamps = false;
public function product()
{
return $this->hasMany('dixard\Product');
}
}
Order MODEL
<?php
namespace dixard;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
// DIrgli che ci lascia scrivere
protected $table = 'orders';
// gli dico che voglio scrivere questo campi
protected $fillable = [
'subtotal',
'shipping',
'method',
'status',
'order_code',
'fullname_ship',
'address_ship',
'app_ship',
'province_ship',
'country_ship',
'email_ship',
'phone_ship',
'fullname_bill',
'address_bill',
'app_bill',
'province_bill',
'country_bill',
'email_bill',
'phone_bill',
];
}

Related

Trying to create project for specific product id laravel-8

A user have many products and product have own id
2)And A product have many projects
I have trouble to make ProjectController
Note: if you need more details you can ask.
This is my user model user.php
public function Products(){
return $this->hasMany('App\Models\Product');
}
public function Project(){
return $this->hasMany('App\Models\Project');
}
This is my Product model product.php
public function User(){
return $this->belongsTo(User::class);
}
public function Project(){
return $this->hasMany('App\Models\Project');
}
This is my project model project.php
public function User(){
return $this->belongsTo(User::class);
}
public function Product(){
return $this->belongsTo(Product::class);
}
Here product table have user_id as forignId and project table have user_id and product_id as forign key
This is project table project.php
$table->unsignedBigInteger ('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreignId('product_id')->nullable();
This is here I have troubles in ProjectController.php
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// $projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
$projects = Project::where('user_id',auth()->user()->id)->where('product_id')->latest()->paginate(20);
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request,$id)
{
$request->validate([
'chapter_name' => 'required',
'sub_section_name' => 'required',
'title_1' => 'required',
'description_1' => 'required',
'image_1' => 'required',
'image_2' => 'required',
'image_3' => 'required',
'title_2' => 'required',
'description_2' => 'required',
'title_3' => 'required',
'description_3' => 'required',
'video_1' => 'required',
'video_2' => 'required',
'video_3' => 'required',
]);
// $input = $request->all();
$input['user_id'] = auth()->user()->id;
$input['product_id'] = $id;
Project::create($input);
return redirect()->route('project.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
// $category = $project->category;
return view('projects.show', compact('project'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
// $user_id = Auth::user()->id ;
$request->validate([
'chapter_name' => 'required',
'sub_section_name' => 'required',
'title_1' => 'required',
'description_1' => 'required',
'image_1' => 'required',
'image_2' => 'required',
'image_3' => 'required',
'title_2' => 'required',
'description_2' => 'required',
'title_3' => 'required',
'description_3' => 'required',
'video_1' => 'required',
'video_2' => 'required',
'video_3' => 'required',
]);
$input = $request->all();
$project->update($input);
return redirect()->route('project.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect()->route('projects.index')
->with('success', 'Project deleted successfully');
}
public function importProject()
{
Excel::import(new ProjectsImport, request()->file('file'));
return back()->with('success','Project created successfully.');
}
public function export()
{
return Excel::download(new UsersExport, 'projects.xlsx');
}
}
This is user table user.php
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
This is products table products.php
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
This is project table project.php
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('chapter_name', 255)->nullable();
$table->string('sub_section_name', 500)->nullable();
$table->string('title_1', 255)->nullable();
$table->string('description_1', 5000)->nullable();
$table->string('image_1', 255)->nullable();
$table->string('image_2', 255)->nullable();
$table->string('image_3', 255)->nullable();
$table->string('title_2', 255)->nullable();
$table->string('description_2', 5000)->nullable();
$table->string('title_3', 255)->nullable();
$table->string('description_3', 255)->nullable();
$table->string('video_1', 255)->nullable();
$table->string('video_2', 255)->nullable();
$table->string('video_3', 255)->nullable();
$table->unsignedBigInteger ('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
// $table->foreignId('product_id')->nullable();
$table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
Thanks for help
Below are 2 possible causes of your error.
The uploaded file request()->file('file') lucks a column with header name id.
If this is the case you may wish to perform some sort of header validation during the import process. i.e:
<?php
namespace App\Imports;
use App\Models\Project;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProjectsImport implements ToCollection, WithHeadingRow
{
use Importable;
private const HEADING_NAMES = [
'chapter_name',
'sub_section_name',
'title_1',
'description_1',
'image_1',
'image_2',
'image_3',
'title_2',
'description_2',
'title_3',
'description_3',
'video_1',
'video_2',
'video_3',
'id'
];
private const HEADING_ROW = 0;
public function collection(Collection $rows)
{
if (
(count($columnHeadings = array_keys($rows[self::HEADING_ROW])) == count(self::HEADING_NAMES))
&& (array_diff($columnHeadings, self::HEADING_NAMES) === array_diff(self::HEADING_NAMES, $columnHeadings))
) {
redirect()
->back()
->withErrors([
"import" => "Incorrect excel sheet headers."
. " "
. "Expected:"
. " " . json_encode(self::HEADING_NAMES)
]);
}
// If validation fails, it won't reach the next statement.
foreach ($rows as $row) {
Project::create([
'chapter_name' => $row['chapter_name'],
// ...
]);
}
}
public function headingRow(): int
{
return self::HEADING_ROW;
}
}
You're using header names to access the data yet by default $row indexes are used instead. i.e: $row[0] instead of $row['chapter_name'].
If this is the case you may wish to implement the WithHeadingRow concern.
Laravel Excel | Heading Row
In case your file contains a heading row (a row in which each cells
indicates the purpose of that column) and you want to use those names
as array keys of each row, you can implement the WithHeadingRow
concern.
i.e:
<?php
use App\Models\Project;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProjectsImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return new Project([
'chapter_name' => $row['chapter_name'],
// ...
]);
}
}
Addendum
If the uploaded file doesn't have the actual 'product_id's but instead has the product names, you could perform some sort of preprocessing to replace product names with their respective 'product_id's.
In addition, you could use some row validation to ensure that the product names exist in the database.
A. Validate product names making sure that they exist.
Laravel Excel | Row Validation without ToModel
<?php
namespace App\Imports;
use App\Models\Project;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProjectsImport implements ToCollection, WithHeadingRow
{
use Importable;
public function collection(Collection $rows)
{
Validator::make($rows->toArray(), [
// Table Name: 'products'. Table Column Name: 'name'. Excel Sheet Header Name: 'product_name'.
'*.product_name' => ['required', 'exists:products,name'],
])->validate();
// If validation fails, it won't reach the next statement.
foreach ($rows as $row) {
Project::create([
'chapter_name' => $row['chapter_name'],
// ...
]);
}
}
}
B. Perform some sort of preprocessing to replace product names with their respective 'product_id's
Laravel Excel | Mapping rows
By adding WithMapping you map the data that needs to be added as
row. This way you have control over the actual source for each column.
i.e:
<?php
namespace App\Imports;
use App\Models\Project;
use App\Models\Product;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
class ProjectsImport implements ToCollection, WithHeadingRow, WithMapping
{
use Importable;
public function collection(Collection $rows)
{
Validator::make($rows->toArray(), [
'*.chapter_name' => 'required',
'*.sub_section_name' => 'required',
'*.title_1' => 'required',
'*.description_1' => 'required',
'*.image_1' => 'required',
'*.image_2' => 'required',
'*.image_3' => 'required',
'*.title_2' => 'required',
'*.description_2' => 'required',
'*.title_3' => 'required',
'*.description_3' => 'required',
'*.video_1' => 'required',
'*.video_2' => 'required',
'*.video_3' => 'required',
'*.product_name' => ['required', 'exists:products,name'],
'*.product_id' => ['required', 'numeric', 'exists:products,id'],
])->validate();
foreach ($rows as $row) {
Project::create([
'chapter_name' => $row['chapter_name'],
'product_id' => $row['product_id']
// ...
]);
}
}
public function map($row): array
{
$mappedRow = $row;
$mappedRow['product_id'] = (isset($row['product_name'])
&& ($product = Product::firstWhere('name', $row['product_name'])))
? $product->id
: null;
return $mappedRow;
// From this point, your rules() and model() functions can access the 'product_id'
}
}
Addendum 2
It appears that your second where clause in index method is lucking (ProjectController).
// ...
public function index()
{
// $projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
$projects = Project::where('user_id',auth()->user()->id)->where('product_id')->latest()->paginate(20); ❌
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
// ...
A where clause requires at least 2 parameters. One 'product_id' parameter is passed for your case.

Search Filtering users by FK in gridview

I have users table containing : PK - id, username, password.
i have three tables ( laptop, display, phone) - id - FK, series, model
I have userequipmentmapping table containing : id - PK , user_id - FK( id from users table), laptop_id - FK (id from laptop table), phone_id - FK (id from phone table), display_id(id from dislpay table), start_date, end_date.
I want to search by user in my gridview from UserEquipmentMapping, but don't know where should i implement the search model, considering the username is passed from the users table by foreign key.
If you have any suggestions are appreciated. Thank You in advance !
Controller :
<?php
namespace app\controllers;
use Yii;
use app\models\UserEquipmentMapping;
use app\models\UserequipmentmappingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\User;
use app\models\Laptop;
use app\models\Phone;
use app\models\Display;
/**
* UserequipmentmappingController implements the CRUD actions for UserEquipmentMapping model.
*/
class UserequipmentmappingController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all UserEquipmentMapping models.
* #return mixed
*/
public function actionIndex()
{
$usermodel = new UserEquipmentMapping();
$userquery = $usermodel->getUsers();
$displaymodel = new UserEquipmentMapping();
$displayquery = $displaymodel->getDisplays();
$phonemodel = new UserEquipmentMapping();
$phonequery = $phonemodel->getPhones();
$laptopmodel = new UserEquipmentMapping();
$laptopquery = $laptopmodel->getLaptops();
#foreach($query as $q)
# print_r($q);
#
# die;
$searchModel = new UserequipmentmappingSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'userquery' => $userquery,
'displayquery' => $displayquery,
'laptopquery'=> $laptopquery,
'phonequery'=> $phonequery,
]);
}
/**
* Displays a single UserEquipmentMapping model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new UserEquipmentMapping model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new UserEquipmentMapping();
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
#print_r(Yii::$app->request->post()); die;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Updates an existing UserEquipmentMapping model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Deletes an existing UserEquipmentMapping model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the UserEquipmentMapping model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return UserEquipmentMapping the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = UserEquipmentMapping::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
use app\models\User;
use app\models\UserQuery;
use yii\db\ActiveQuery;
/**
* This is the model class for table "user_equipment_mapping".
*
* #property int $id
* #property int $user_id
* #property int|null $laptop_id
* #property int|null $phone_id
* #property int|null $display_id
* #property string|null $start_date
* #property string|null $stop_date
*
* #property Display $display
* #property Laptop $laptop
* #property Phone $phone
* #property User $user
*/
class UserEquipmentMapping extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'user_equipment_mapping';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_id'], 'required'],
[['user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
[['display_id'], 'exist', 'skipOnError' => true, 'targetClass' => Display::className(), 'targetAttribute' => ['display_id' => 'id']],
[['laptop_id'], 'exist', 'skipOnError' => true, 'targetClass' => Laptop::className(), 'targetAttribute' => ['laptop_id' => 'id']],
[['phone_id'], 'exist', 'skipOnError' => true, 'targetClass' => Phone::className(), 'targetAttribute' => ['phone_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'laptop_id' => 'Laptop ID',
'phone_id' => 'Phone ID',
'display_id' => 'Display ID',
'start_date' => 'Start Date',
'stop_date' => 'Stop Date',
];
}
/**
* Gets query for [[Display]].
*
* #return \yii\db\ActiveQuery|DisplayQuery
*/
public function getDisplay()
{
return $this->hasOne(Display::className(), ['id' => 'display_id']);
}
/**
* Gets query for [[Laptop]].
*
* #return \yii\db\ActiveQuery|LaptopQuery
*/
public function getLaptop()
{
return $this->hasOne(Laptop::className(), ['id' => 'laptop_id']);
}
/**
* Gets query for [[Phone]].
*
* #return \yii\db\ActiveQuery|PhoneQuery
*/
public function getPhone()
{
return $this->hasOne(Phone::className(), ['id' => 'phone_id']);
}
/**
* Gets query for [[User]].
*
* #return \yii\db\ActiveQuery|UserQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getUsers()
{
return $this->hasMany(User::className(),['user_id', 'id']);
}
public function getLaptops()
{
return $this->hasMany(Laptop::className(),['laptop_id', 'id']);
}
public function getDisplays()
{
return $this->hasMany(Display::className(),['dislpay_id', 'id']);
}
public function getPhones()
{
return $this->hasMany(Phone::className(),['phone_id', 'id']);
}
/**
* {#inheritdoc}
* #return UserEquipmentMappingQuery the active query used by this AR class.
*/
public static function find()
{
return new UserEquipmentMappingQuery(get_called_class());
}
}
ModelSearch :
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\UserEquipmentMapping;
/**
* UserequipmentmappingSearch represents the model behind the search form of `app\models\UserEquipmentMapping`.
*/
class UserequipmentmappingSearch extends UserEquipmentMapping
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['id', 'user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = UserEquipmentMapping::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'laptop_id' => $this->laptop_id,
'phone_id' => $this->phone_id,
'display_id' => $this->display_id,
'start_date' => $this->start_date,
'stop_date' => $this->stop_date,
]);
return $dataProvider;
}
}
Index :
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\UserequipmentmappingSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'User Equipment Mappings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-equipment-mapping-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create User Equipment Mapping', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatter' => [
'class' => 'yii\i18n\Formatter',
'nullDisplay' => '-',],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
#'id',
'user.username',
#'laptop.laptop_model',
'laptop.laptop_series',
#'laptop_id',
#'phone.phone_model',
'phone.phone_series',
#'phone_id',
#'display.display_model',
'display.display_series',
#'display_id',
'start_date',
'stop_date',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Uncomment in your index view _search view. There are all fields from UserequipmentmappingSearch model. You can replace input fields with select fields for user, laptop and etc. Search model will do the other thing, all is in search function that fills your dataprovider

Laravel Soft Deletes dosent work in one table

I am trying to make soft deletes in my DB tables but it fails in one table. I made same things with other tables but only in one it dosen't work. When i click delete in view it deletes row in data base. I will show code of soft delete for this table and have hope that you will help me.
This is my migration for it:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Invoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->string('invoicenumber')->nullable();
$table->date('invoicedate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('form_id')->unsigned()->nullable();
$table->integer('currency_id')->unsigned()->nullable();
$table->integer('proform_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->string('city')->nullable();
$table->string('paid')->nullable();
$table->string('autonumber')->nullable();
$table->string('automonth')->nullable();
$table->string('autoyear')->nullable();
$table->string('name')->nullable();
$table->string('PKWIU')->nullable();
$table->string('quantity')->nullable();
$table->string('unit')->nullable();
$table->string('netunit')->nullable();
$table->string('nettotal')->nullable();
$table->string('VATrate')->nullable();
$table->string('grossunit')->nullable();
$table->string('grosstotal')->nullable();
$table->timestamps();
$table->time('deleted_at')->nullable();
});
Schema::table('invoices', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('form_id')
->references('id')
->on('forms')
->onDelete('cascade');
$table->foreign('currency_id')
->references('id')
->on('currencys')
->onDelete('cascade');
$table->foreign('proform_id')
->references('id')
->on('proforms')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('invoices');
}
}
This is model for invoice. Invoice.php
<?php
namespace App;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Invoice extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
use SoftDeletes;
use Sortable;
protected $table = 'invoices';
protected $fillable = [
'invoicenumber', 'invoicedate', 'id', 'selldate', 'user_id', 'paymentmethod',
'paymentdate', 'status', 'comments', 'city', 'paid', 'autonumber', 'automonth', 'autoyear', 'name',
'PKWIU', 'quantity', 'unit', 'netunit', 'nettotal',
'VATrate', 'grossunit', 'grosstotal', 'form_id', 'currency_id',
];
public $sortable = [ 'invoicenumber', 'invoicedate', 'id', 'selldate',
'user_id', 'paymentmethod', 'paymentdate', 'status', 'comments', 'grosstotal', 'nettotal', 'form_id', 'currency_id',];
protected $dates = ['deleted_at'];
public $primaryKey = 'id';
public function user()
{
return $this->belongsTo('App\User');
}
public function form()
{
return $this->hasOne('App\Form');
}
public function currency()
{
return $this->hasOne('App\Currency');
}
public function proform()
{
return $this->belongsTo('App\Proform');
}
}
InvoiceController.php
<?php
namespace App\Http\Controllers;
use Kyslik\ColumnSortable\Sortable;
use App\Invoice;
use Illuminate\Http\Request;
use App\User;
use App\Proform;
use App\Form;
use App\Currency;
use DB;
class InvoiceController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
function __construct()
{
$this->middleware('permission:product-list|product-create|product-edit|product-delete', ['only' => ['index','show']]);
$this->middleware('permission:product-create', ['only' => ['create','store']]);
$this->middleware('permission:product-edit', ['only' => ['edit','update']]);
$this->middleware('permission:product-delete', ['only' => ['destroy']]);
}
public function search4(Request $request)
{
$user = User::all('showname','id');
$invoices = Invoice::sortable()->paginate(5);
$query = DB::table('users')
->join('invoices', 'users.id', '=', 'invoices.user_id');
$search = $request->get('search');
$requestData = ['showname'];
/* $query = Proform::query(); */
foreach ($requestData as $field){
$query->orWhere($field, 'like', '%'.$search.'%');
}
$data2=$query->paginate(5);
return view('invoices.index', ['invoices' => $data2, 'user'=> $user])->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user = User::all('showname','id');
$invoices = Invoice::sortable()->paginate(5);
return view('invoices.index',compact('invoices', 'user'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{ $users = User::all('showname','id');
$forms = Form::all('id', 'form');
$currencys = Currency::all('id', 'currency', 'course');
return view('invoices.create')->with('users', $users, 'forms', 'currencys');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'invoicedate' => 'required',
'user_id' => 'required',
'selldate' => 'required',
'paymentdate' => 'required',
'paymentmethod' => 'required',
'status' => 'required',
'comments' => 'nullable',
'city' => 'nullable',
'paid' => 'nullable',
'name' => 'required',
'PKWIU' => 'nullable',
'quantity' => 'required',
'unit' => 'required',
'netunit' => 'required',
'nettotal' => 'required',
'VATrate' => 'required',
'grossunit' => 'required',
'grosstotal' => 'required',
]);
Invoice::create($request->all());
return redirect()->route('invoices.index')
->with('success','Invoice created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Invoice $invoice)
{
return view('invoices.show',compact('invoice'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Invoice $invoice)
{
$users = User::all('showname','id');
$forms = Form::all('id', 'form');
$currencys = Currency::all('id', 'currency', 'course');
return view('invoices.edit',compact('invoice', 'users', 'forms', 'currencys'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Invoice $invoice)
{
request()->validate([
'invoicedate' => 'required',
'user_id' => 'required',
'selldate' => 'required',
'paymentdate' => 'required',
'paymentmethod' => 'required',
'status' => 'required',
'comments' => 'nullable',
'city' => 'nullable',
'paid' => 'nullable',
'name' => 'required',
'PKWIU' => 'nullable',
'quantity' => 'required',
'unit' => 'required',
'netunit' => 'required',
'nettotal' => 'required',
'VATrate' => 'required',
'grossunit' => 'required',
'grosstotal' => 'required',
]);
$invoice->update($request->all());
return redirect()->route('invoices.index')
->with('success','Invoice updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Invoice $invoice)
{
$invoice->delete();
return redirect()->route('invoices.index')
->with('success','Invoice deleted successfully');
}
}
Routes:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function(){
return view('welcome');
});
Route::get('home');
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth']], function () {
Route::get('/search', 'UserController#search');
Route::get('/search2', 'ProductController#search2');
Route::get('/search3', 'ProformController#search3');
Route::get('/search4', 'InvoiceController#search4');
Route::post('/duplicate', 'ProformController#duplicate')->name('proforms.duplicate');
Route::get('data', 'UserController#index');
Route::get('posts', 'PostController#index');
Route::get('/prodview', 'TestController#prodfunct');
Route::resource('roles', 'RoleController');
Route::resource('users', 'UserController');
Route::resource('permissions', 'PermissionController');
Route::resource('products', 'ProductController');
Route::resource('invoices', 'InvoiceController');
Route::resource('category', 'CategoryController');
Route::resource('invoices', 'InvoiceController');
Route::resource('proforms', 'ProformController');
});
View:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Zarządzanie fakturami</h2>
</div>
<div class="col-md-4">
<form action="/search4" method="get">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-prepend">
<button type="submit" class="btn btn-primary">Wyszukaj</button>
</span>
</div>
</form>
</div>
<div class="pull-right">
#can('product-create')
<a class="btn btn-success" href="{{ route('invoices.create') }}"> Utwórz nową fakturę</a>
#endcan
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th scope="col">#sortablelink('id', 'Numer')</th>
<th scope="col">#sortablelink('invoicnumber', 'Numer faktury')</th>
<th scope="col">#sortablelink('invoicedate', 'Data wystawienia')</th>
<th scope="col">#sortablelink('user_id', 'Kontrachent')</th>
<th scope="col">#sortablelink('selldate', 'Data sprzedaży')</th>
<th scope="col">#sortablelink('paymentdate', 'Termin płatności')</th>
<th scope="col">#sortablelink('status', 'Status')</th>
<th scope="col">#sortablelink('nettotal', 'Netto razem')</th>
<th scope="col">#sortablelink('grosstotal', 'Brutto razem')</th>
<th width="280px">Akcja</th>
</tr>
#foreach ($invoices as $invoice)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $invoice->invoicenumber }}</td>
<td>{{ $invoice->invoicedate }}</td>
<td>{{ $invoice->user->showname ?? $invoice->showname }}</td>
<td>{{ $invoice->selldate }}</td>
<td>{{ $invoice->paymentdate }}</td>
<td>{{ $invoice->status }}</td>
<td>{{ $invoice->nettotal }}</td>
<td>{{ $invoice->grosstotal }}</td>
<td>
<form action="{{ route('invoices.destroy',$invoice->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('invoices.show',$invoice->id) }}">Więcej</a>
#can('product-edit')
<a class="btn btn-primary" href="{{ route('invoices.edit',$invoice->id) }}">Edytuj</a>
#endcan
#csrf
#method('DELETE')
#can('product-delete')
<button type="submit" class="btn btn-danger">Usuń</button>
#endcan
</form>
</td>
</tr>
#endforeach
</table>
{!! $invoices ?? ''->appends(request()->except('page'))->render() !!}
<p class="text-center text-primary"><small>ARTplus 2020</small></p>
#endsection
You must to use $table->softDeletes(); instead of $table->time('deleted_at')->nullable();.
softDeletes() method used timestamp instead of time format date. Maybe it will solve your problem;

Why duplication is occured?

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'admin#gmail.com' for key 'students_email_unique' (SQL: insert into students (name, address, phone, email, faculty, updated_at, created_at) values (Librarian, maitidevi, 9738233231, admin#gmail.com, food, 2019-06-18 09:38:58, 2019-06-18 09:38:58))
Previous exceptions
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'address' => 'required',
'phone' => 'required',
'email' => 'required|unique',
'faculty' => 'required'
]);
Student::create($request->all());
return redirect()->route('student.index')
->with('success', 'Student Updated Successfully');
}
When I validate with unique this also occurred:
Validation rule unique requires at least 1 parameters.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$students = Student::latest()->paginate(5);
return view('student.index', compact('students'))
->with('i', (request()->input('page', 1) -1)*5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('student.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'address' => 'required',
'phone' => 'required',
'email' => 'required',
'faculty' => 'required'
]);
Student::create($request->all());
return redirect()->route('student.index')
->with('success', 'Student Created Successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$student = Student::find($id);
return view('student.detail', compact('student'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$student = Student::find($id);
return view('student.edit', compact('student'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'address' => 'required',
'phone' => 'required',
'email' => 'required',
'faculty' => 'required'
]);
Student::create($request->all());
return redirect()->route('student.index')
->with('success', 'Student Updated Successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$student = Student::find($id);
$student->delete();
return redirect()->route('student.index')
->with('success', 'Student deleted successfully');
}
}
I am stuck in my above code? Please help what to do?
In the validation of store method put this instead
'email' => 'required|unique:students,email',
in the Update method, you will need to build the validation rules like this
use Illuminate\Validation\Rule;
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
\Validator::make($request->all(), [
'name' => 'required',
'address' => 'required',
'phone' => 'required',
'faculty' => 'required'
'email' => [
'required',
Rule::unique('students', 'email')->ignore($id),
],
]);
if ($validator->fails()) {
return redirect()
->route('student.create')
->withErrors($validator)
->withInput();
}
$student = Student::findOrFail($id);
foreach ($request->all() as $attribute => $value) {
$student->{$attribute} = $value;
}
$student->save();
return redirect()->route('student.index')
->with('success', 'Student Updated Successfully');
}

Show Related Data in View Yii 2

I'm new in Yii 2, and I'm creating an inventory system for the library of my school, but I had a problem.
First, I have a relation like this:
I want to show all the adqs (a unique number for each book - that way we don't need to capture the book again for every copy) of a book in his view, but only the adqs related to the book id obviously at the bottom.
My View:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $model app\models\Libros */
/* #var $searchModel app\models\LibrosSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = $model->lib_titulo;
$this->params['breadcrumbs'][] = ['label' => 'Libros', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="libros-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Modificar', ['update', 'id' => $model->lib_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Borrar', ['delete', 'id' => $model->lib_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<div class="row" align="center">
<?php
if ($model->lib_image_web_filename!='') {
echo '<br /><p><img width="500" src="'.Url::to('#web/', true). '/uploads/libros/'.$model->lib_image_web_filename.'"></p>';
}
?>
</div>
<div class="row" style="
text-align: center;
font: normal normal bold 15px/1 'lato';
color: rgba(7,7,7,1);
text-align: center;
">
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'lib_id',
'lib_titulo',
'lib_autor',
//'lib_edicion',
'editorialNombre',
'ubicacionNombre',
'lib_isbn',
'lib_clasificacion',
'lib_seccion',
//'lib_image_src_filename',
//'lib_image_web_filename',
],
]) ?>
</div>
</div>
My Controller (LibrosController):
<?php
namespace backend\controllers;
use Yii;
use app\models\Libros;
use app\models\LibrosSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
* LibrosController implements the CRUD actions for Libros model.
*/
class LibrosController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Libros models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new LibrosSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Libros model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionCreate()
{
$model = new Libros();
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Libros model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = explode(".", $image->name);
$ext_final = end($ext);
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext_final}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Deletes an existing Libros model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Libros model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Libros the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Libros::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
My Model (Libros.php):
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "libros".
*
* #property int $lib_id
* #property string $lib_titulo
* #property string $lib_autor
* #property string $lib_edicion
* #property int $lib_ubi
* #property int $lib_editorial_id
* #property string $lib_isbn
* #property string $lib_clasificacion
* #property string $lib_seccion
* #property string $lib_image_src_filename
* #property string $lib_image_web_filename
*
* #property Adq[] $adqs
* #property Editorial $libEditorial
* #property Ubicacion $libUbi
* #property LibrosCarreras[] $librosCarreras
* #property Carreras[] $licCarreras
*/
class Libros extends \yii\db\ActiveRecord
{
const PERMISSIONS_PRIVATE = 10;
const PERMISSIONS_PUBLIC = 20;
public $image;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'libros';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['lib_titulo', 'lib_autor', 'lib_ubi', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'required'],
[['lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo'], 'string', 'max' => 120],
[['lib_autor', 'lib_clasificacion'], 'string', 'max' => 64],
//[['lib_edicion'], 'string', 'max' => 3],
[['lib_isbn'], 'string', 'max' => 32],
[['lib_seccion'], 'string', 'max' => 2],
[['lib_editorial_id'], 'exist', 'skipOnError' => true, 'targetClass' => Editorial::className(), 'targetAttribute' => ['lib_editorial_id' => 'edi_id']],
[['lib_ubi'], 'exist', 'skipOnError' => true, 'targetClass' => Ubicacion::className(), 'targetAttribute' => ['lib_ubi' => 'ubil_id']],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 100],
[['image'], 'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png'],
[['image'], 'file', 'maxSize'=>'1000000'],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 255], ];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'lib_id' => 'ID',
'lib_titulo' => 'Titulo',
'lib_autor' => 'Autor',
//'lib_edicion' => 'Edicion',
'lib_editorial_id' => 'Editorial',
'lib_isbn' => 'ISBN',
'lib_clasificacion' => 'Clasificacion',
'lib_ubi' => 'Ubicacion',
'lib_seccion' => 'Seccion',
'image' => 'Captura',
'lib_image_src_filename' => Yii::t('app', 'Nombre de Archivo'),
'lib_image_web_filename' => Yii::t('app', 'Nombre del Directorio'),
'editorialNombre' => 'Editorial',
'ubicacionNombre' => 'Ubicacion',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
/**
* #return \yii\db\ActiveQuery
*/
public function getLibrosCarreras()
{
return $this->hasMany(LibrosCarreras::className(), ['lic_libros_id' => 'lib_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getEditorial0()
{
return $this->hasOne(Editorial::className(), ['edi_id' => 'lib_editorial_id']);
}
public function getEditorialNombre()
{
return $this->editorial0->edi_nombre;
}
public function getLibUbi()
{
return $this->hasOne(Ubicacion::className(), ['ubil_id' => 'lib_ubi']);
}
public function getUbicacionNombre()
{
return $this->libUbi->ubil_nombre; }
}
My Search Model (LibrosSearch.php):
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Libros;
/**
* LibrosSearch represents the model behind the search form of `app\models\Libros`.
*/
class LibrosSearch extends Libros
{
public $editorialNombre;
public $ubicacionNombre;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['lib_id', 'lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo', 'lib_autor', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'safe'],
[['editorialNombre'],'safe'],
[['ubicacionNombre'],'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Libros::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes'=>[
'editorialNombre'=>[
'asc'=>['editorial.edi_nombre'=>SORT_ASC],
'desc'=>['editorial.edi_nombre'=>SORT_DESC],
'label'=>'Editorial Nombre'
]
]
]);
$dataProvider->setSort([
'attributes'=>[
'ubicacionNombre'=>[
'asc'=>['ubicacion.ubil_nombre'=>SORT_ASC],
'desc'=>['ubicacion.ubil_nombre'=>SORT_DESC],
'label'=>'Ubicacion Nombre'
]
]
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'lib_id' => $this->lib_id,
'lib_ubi' => $this->lib_ubi,
'lib_editorial_id' => $this->lib_editorial_id,
]);
$query->andFilterWhere(['like', 'lib_titulo', $this->lib_titulo])
->andFilterWhere(['like', 'lib_autor', $this->lib_autor])
//->andFilterWhere(['like', 'lib_edicion', $this->lib_edicion])
->andFilterWhere(['like', 'lib_isbn', $this->lib_isbn])
->andFilterWhere(['like', 'lib_clasificacion', $this->lib_clasificacion])
->andFilterWhere(['like', 'lib_seccion', $this->lib_seccion])
->andFilterWhere(['like', 'lib_image_src_filename', $this->lib_image_src_filename])
->andFilterWhere(['like', 'lib_image_web_filename', $this->lib_image_web_filename]);
$query->joinWith(['editorial0'=>function($q)//creamos un nuevo filtro
{
$q->where('editorial.edi_nombre LIKE "%' . $this->editorialNombre . '%"');
}]);
$query->joinWith(['libUbi'=>function($q)//creamos un nuevo filtro
{
$q->where('ubicacion.ubil_nombre LIKE "%' . $this->ubicacionNombre . '%"');
}]);
return $dataProvider;
}
}
How can I accomplish this task?
[
'attribute' => 'adq_libro_id',
'value' => implode(', ', \yii\helpers\ArrayHelper::map($model->Adqs, 'id',
function ( $model )
{
return $model['adq'];
}
)),
'format' => 'raw'
],
try like this. Check the right name of attributes
In your model Libros.php you have this function.
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}
This means you can access the relations of Libros like:
// where $model is an instance of Libros
$model->adqs->property_name
Or as a function
$model->getAdqs();

Categories