How to fetch the id of relational database in symfony 4? - doctrine

I have displayed the relational database data's in drop down that's working properly
But when i try to insert the data's to another form containing relational database tables as drop down It throws error
<select>
<option value=""> Select Category</option>
{% for category in category %}
<option value="{{category.category}}"> {{category.category}} </option>
{% endfor %}
</select>
While inserting the data's the error is
An exception occurred while executing 'INSERT INTO new_product
(product_code, product_name, quantity, price, gst, hsn_code,
product_metric, product_dimension, supplier_name, category_id) VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["RE45", "Shirt", 4,
456.9, 70.8, 2345, 3, 4, "sakthi", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'category_id' cannot be null

Add these lines in Entity
public function __toString()
{
return (string) $this->getCategory();
}
In twig
TABLE HEADER
<th><h4> category </h4></th>
TABLE DATA
{% for newproduct in newproduct %}
<td> {{ newproduct.getCategory() }}</td> //newproduct is another entity contains category entity as relatinal database
{% endfor %}

Related

Foreign key is now null and when mapping through the data it say "Attempt to read property "$category_name" on null"

I deleted a category which is an f-key of the items table. Now the view has an error saying 'Attempt to read property "category_name" on null'. How do I render a null foreign key?
I tried if-else:
#if({{$item->category->category_name}} === 'null')
<h2>no category</h2>
#else
{{ $item->category->category_name}}
#endif
Try this:
#if ($item->category)
{{ $item->category->category_name }}
#else
<h2>no category</h2>
#endif
Or simply
<h2>{{ $item->category?->category_name ?? 'no category' }}</h2>
In PHP8 or Larvel 8
simple use this one
<h2>{{ $item->category->category_name ? 'no category' }}</h2>

Connection between Two Cruds

I want to send data from a Controller to an other one. From Client Crud to Reservation Crud. With this form i want send to booking method in ReservationController to associate a room with the client.
<form action="{{Route('reservation.booking', $room->id, $client->id)}}" method="POST">
#csrf
#method('get')
<select class="roomname" name="roomname">
<option selected>Elige habitacion</option>
<option value="{{$rooms[0]->id}}">ESTANÇA DEL PUIGRACIÓS</option>
<option value="{{$rooms[1]->id}}">ESTANÇA DE SANT CRISTÒFOL</option>
<option value="{{$rooms[2]->id}}">ESTANÇA (DÚPLEX) DEL ROCACENTELLA</option>
</select>
<input type="submit" value="Reservar habitación" class = "btn btn-primary">
</form>
public function booking(Room $room, Client $client)
{
//dd($client);
$room->client()->associate($client);
$room->save();
return redirect(route('reservation.create'));
}
The route definition:
Route::get('/reservation/{reservation}/booking','ReservationController#booking')
->name('reservation.booking');
And I got this message:
SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a
default value (SQL: insert into rooms (client_id, updated_at,
created_at) values (?, 2020-05-10 16:21:19, 2020-05-10 16:21:19))

laravel 5.6: How to display each product and the available brand s in a table given that each product has multiple brands

I'am a newbie in laravel and I'am trying to develop an application, which has a section with a table that lists each product, the available brands,the available quantities,the selling prices.Each product has multiple brands
I have three tables involved:
1ST TABLE Items_master: this table stores the product names, buying and selling price
2ND TABLE Stock_quantities: this table stores the product quantities according to the shop by product_id and shop_id.
3RD TABLE item_brands: this table stores the brands of each product based on product_id and shop_id.
Here is the code
MAIN QUERY TO GET PRODUCT NAME, CATEGORIES AND ITEM QUANTITY
$details=items_master::select('items_masters.id as
product_id','items_masters.name as item_name','items_masters.category','buying_price','selling_price','item_quantities.product_id','item_quantities.quantity','categories.id','categories.serial')
->join('item_quantities','items_masters.id','=','item_quantities.item_id')
->join('categories','categories.id','=','items_masters.category')
->where([['item_quantities.shop_id', '=',$shop]] )
->groupBY('product_id')
->get();
QUERY TO GET THE PRODUCT IDs
$product_ids = collect($details)->pluck('product_id');
QUERY TO GET THE PRODUCT BRANDS
$brands = item_brands::whereIn('pid', $product_ids)
->where('shop_id', $shop)
->where('status', 0)
->get();
CODE IN THE VIEW
<div class="table-responsive">
<table class="table table-bordered table-striped" >
<thead>
<tr>
<th>Item Name</th>
<th>Item Brands</th>
<th>Stock Qty</th>
<th>Category</th>
<th>Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach($details as $detail)
<tr>
<td>{{$detail->item_name}} </td>
<td><div class="form-group">
#foreach($brands as $brand )
<span>{{$brand->name}}</span>
#endforeach
</div>
</td>
<td>{{$detail->quantity.' '.$detail->units}} </td>
<td >
<td>{{$detail->category}} </td>
<td >
<b>Ksh. {{$detail->selling_price}}</b>
</td>
</tr>
#endforeach
</tbody>
</table>
Given the above code , I get all the brands for all products in the table listed against each product. I need each product to only display its brands on its row e.g
Product: Tablet | Brands: samsung, apple
Product: Desktop | Brands: HP,Lenovo
CURRRENLY THIS IS WHAT APPEARS
Product: Tablet | Brands: samsung, apple,HP,Lenovo
Product: Desktop | Brands: samsung, apple,HP,Lenovo
Have you tried using a collection method to constrain what brands are used in the foreach? IE:
#foreach($brands->where('pid', $detail->product_id) as $brand )
<span>{{$brand->name}}</span>
#endforeach
Since you get all brands for every product, this will let you just pick the brands for your current $detail.
Edit: but to be honest, I feel like all 3 queries could be written into 1 eloquent query, but I would have to see all 3 models with relationships.

How to show selected value from database in dropdown using Laravel?

I want to show selected value from database into dropdown list on page load.
My controller index function is :
public function index()
{
$country_data =DB::table('country')->select('country_id','country_name')->get();
$profile_data= DB::table('profiles')->select('*')->where('id',$user_id)->first();
return view('profile_update',compact('profile_data','country_data'));
}
Column name in database for height is :Height
My dropdown in profile_update.blade.php is
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
#foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$country_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
#endforeach</select>
This is a example of how I do this:
<select class="js-states browser-default select2" name="shopping_id" required id="shopping_id">
<option value="option_select" disabled selected>Shoppings</option>
#foreach($shoppings as $shopping)
<option value="{{ $shopping->id }}" {{$company->shopping_id == $shopping->id ? 'selected' : ''}}>{{ $shopping->fantasyname}}</option>
#endforeach
</select>
In order to understand it fully you will need basics of laravel (MVC),
Let suppose, you have controller. In my case I made a separate table for drop down values.
My Approach --- Separate table for values of drop down, you can try different approach but my explanation was mainly focused on concept.
Note: PersonInfo is model, sampleType is model of my drop down values and don't forget to make a route for the controller.
ExampleController{
public funtion getValues($id){
/*
I am fetching information of a single row from the database by id and
then passing it to the view. The $id to the function came from the
request by your view/form.
I also fetched the values of drop down from the separate table
of database and passed it to the exampleView.
*/
$selectedValue=PersonInfo::findOrFail($id);
$sampleType=SampletypePicker::all(); //model for fetching all values of drop down
return view('exampleView',compact('selectedValue','sampleType));
}
}
So, in the above controller I fetched all values and passed it to the ExampleView. Now in your View file you have to work likewise.
exampleView.blade.php add the below code
<?php $options=$selectedValue->sample_type ?> //note take the value from the database which stored for the individual record and match it with the selected one.
<select class="form-control" name="test">
<option>Select Test Type</option>
#foreach ($sampleType as $value)
<option value="{{ $value->sample_type }}" {{ ( $value->sample_type == $options) ? 'selected' : '' }}>
{{ $value->sample_type }}
</option>
#endforeach
</select>
It is one of the best approach when you want to add dynamic values to the drop down. I mean if you want to add more values to the select tag options then this is the best approach.
Another Approach - take the idea
<?php $months = array("Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); ?>
<?php $options=$patient_data->month ?>
#if($patient_data->month)
<select id="expiry_month" name="month" class="form-control-sm">
#foreach($months as $month)
<option value="{{$month}}" {{($month==$options)? 'selected':'' }}>{{$month}}</option>
#endforeach
</select>
#endif
<span class="select-icon"><i class="zmdi zmdi-chevron-down"></i></span>
</div>
OUTPUT of ABOVE CODE
#Sarita Sharma show the error(s). Maybe then anyone help you to resolve this problem. Show data in colections in controler - use dd e.g.
dd($country_data);
dd($profile_data);
Do you want to display the country in the view with the appropriate Height value from profile_data?
Ps. How to put the code, please use the formatting code - put the code in `` and use camelCase in value name (maintaining good PSR-1 practice) - it is easier to read code.
Well, simply if anyone still looking for this, here is the simple way to select items for dropdown from database to blade view
$users = Users::pluck('name', 'id');
$selectedID = 2;
return view('users.edit', compact('id', 'users'));
add this in the controller function before rendering the view
and in the blade view, simply use this variable as foreach loop as
<select name="user_id" class="form-control" id="exampleFormControlSelect1">
#foreach ($users as $key => $value)
<option value="{{ $key }}" {{ ($key == $selectedID) ? 'selected' : '' }}>
{{ $value }}
</option>
#endforeach
</select>
if you don't want to select all users from DB, you can use where condition before pluck condition as
$users = Users::where('status', 1)->pluck('name', 'id');
works with Laravel 8 and Laravel6

Accessing data separately from multiple tables in single view in blade template laravel

I have three different tables: persons, students and teachers. I was able to join three tables and get data as follows:
public function viewProduct()
{
$persons = Person::with(['students','teachers'])->get();
return view('master.viewPeoples', compact('persons'));
}
I want to access data in my blade. How can I get data of students and teachers table in my blade template? I have the columns rollNum, year, and semester in the students table and the columns salary and courses in the teachers table.
The following source code returns data from the person table only.
#foreach($persons as $person)
{{ $person->name }}
{{ $person->universityNum }}
{{ $person->rollNum }} //returns blank
{{ $person->year }} //returns blank
...
#endforeach
I get all data for students and teachers when I do this:
#foreach($persons as $person)
{{ $person->students }}
{{ $person->teachers }}
#endforeach
But I want to access data of each column of students and teachers table separately like$students->rollNum
try this
#foreach($persons as $person)
{{ $person->name }}
#foreach($person->students as $student)
{{ $student->rollNum }}
{{ $student->year }}
#endforeach
// Do same for teachers here
#endforeach
Hope it helps
Try this
#foreach($persons as $person)
{{ $person->students->rollNum }}
{{ $person->teachers->rollNum }}
#endforeach
or
#foreach($persons as $person)
{{ $person->students_rollNum }}
{{ $person->teachers_rollNum }}
#endforeach

Resources