I have part of my website where users or admins can add restaurant list (is really like posts, just different naming)
There is some fixed inputs such as (title, description and map) I also need a part where users/admins can add restaurants menu this options is obviously can be different for each restaurant as their menu is a short list or long list.
So what I need is like + button where people can add fields and named their menu items with another field for the price of each item.
So my question is how to achieve this option?
What do I have at the moment?
Restaurant migrate:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRestaurantsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('restaurants', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->unique();
$table->string('slug')->unique();
$table->string('description')->nullable();
$table->string('image')->nullable();
$table->string('menu')->nullable();
$table->string('address')->nullable();
$table->integer('worktimes_id')->unsigned();
$table->integer('workday_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->string('verified')->default(0);
$table->string('status')->default(0);
$table->timestamps();
});
Schema::table('restaurants', function($table) {
$table->foreign('worktimes_id')->references('id')->on('worktimes');
$table->foreign('workday_id')->references('id')->on('workdays');
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('restaurants');
}
}
That's all, I still didn't create CRUD controller for restaurant because I'm holding for this option and your opinions.
Thanks.
UPDATE
STORE METHOD:
public function store(Request $request)
{
//Validating title and body field
$this->validate($request, array(
'title'=>'required|max:225',
'slug' =>'required|max:255',
'image' =>'sometimes|image',
'description' => 'required|max:100000',
'address' => 'sometimes|max:500',
'user_id' => 'required|numeric',
'verified' => 'sometimes',
'status' => 'required|numeric',
));
$restaurant = new Restaurant;
$restaurant->title = $request->input('title');
$restaurant->slug = $request->input('slug');
$restaurant->description = $request->input('description');
$restaurant->address = $request->input('address');
$restaurant->user_id = $request->input('user_id');
$restaurant->verified = $request->input('verified');
$restaurant->status = $request->input('status');
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'restaurant' . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/');
$request->file('image')->move($location, $filename);
$restaurant->image = $filename;
}
// menu
$newArray = array();
$menuArray = $request->custom_menu; //Contains an array of Menu Values
$priceArray = $request->custom_price; //Contains an array of Price Values
//Creating new array with ARRAY KEY : MENU VALUES and ARRAY VALUE: PRICE VALUES
foreach ($menuArray as $key => $singleMenu) {
$newArray[$singleMenu] = $priceArray[$key];
}
//Output : array("Menu01" => "Price01", "Menu02" => "Price 02", "Menu03" => "Price 04", "Menu04" => "Price 05")
//Converting array to json format to store in your table row 'custom_menu_price'
$jsonFormatData = json_encode($newArray);
//Output like: {"Menu01":"Price01","Menu02":"Price 02","Menu03":"Price 04","Menu04":"Price 05"}
// Save in DB
//
//
//
// To retrieve back from DB to MENU and PRICE values as ARRAY
$CustomArray = json_decode($jsonFormatData, TRUE);
foreach ($CustomArray as $menu => $price) {
echo "Menu:".$menu."<br>";
echo "Price:".$price."<br>";
}
// menu
$restaurant->save();
$restaurant->workdays()->sync($request->workdays, false);
$restaurant->worktimes()->sync($request->worktimes, false);
//Display a successful message upon save
Session::flash('flash_message', 'Restaurant, '. $restaurant->title.' created');
return redirect()->route('restaurants.index');
What you can do is
1) add another one table row for custom_menu_price in your migration file
$table->string('custom_menu_price')->nullable();
2) Modify your form
<form method="POST" action="{{ ...... }}">
{{ csrf_field() }}
//I'm Looping the input fields 5 times here
#for($i=0; $i<5; $i++)
Enter Menu {{ $i }} : <input type="text" name="custom_menu[]"> //**Assign name as ARRAY
Enter Price {{ $i }} : <input type="text" name="custom_price[]"> //**Assign name as ARRAY
<br><br>
#endfor
<input type="submit" name="submit">
</form>
3) In your controller
public function store(Request $request) {
//Validating title and body field
$this->validate($request, array(
'title'=>'required|max:225',
'slug' =>'required|max:255',
'image' =>'sometimes|image',
'description' => 'required|max:100000',
'address' => 'sometimes|max:500',
'user_id' => 'required|numeric',
'verified' => 'sometimes',
'status' => 'required|numeric',
));
$restaurant = new Restaurant;
$restaurant->title = $request->input('title');
$restaurant->slug = $request->input('slug');
$restaurant->description = $request->input('description');
$restaurant->address = $request->input('address');
$restaurant->user_id = $request->input('user_id');
$restaurant->verified = $request->input('verified');
$restaurant->status = $request->input('status');
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'restaurant' . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/');
$request->file('image')->move($location, $filename);
$restaurant->image = $filename;
}
// menu
$newArray = array();
$menuArray = $request->custom_menu; //Contains an array of Menu Values
$priceArray = $request->custom_price; //Contains an array of Price Values
//Creating new array with ARRAY KEY : MENU VALUES and ARRAY VALUE: PRICE VALUES
foreach ($menuArray as $key => $singleMenu) {
$newArray[$singleMenu] = $priceArray[$key];
}
//Output : array("Menu01" => "Price01", "Menu02" => "Price 02", "Menu03" => "Price 04", "Menu04" => "Price 05")
//Converting array to json format to store in your table row 'custom_menu_price'
$jsonFormatData = json_encode($newArray);
//Output like: {"Menu01":"Price01","Menu02":"Price 02","Menu03":"Price 04","Menu04":"Price 05"}
// Save in DB
$restaurant->custom_menu_price = $jsonFormatData;
// menu
$restaurant->save();
$restaurant->workdays()->sync($request->workdays, false);
$restaurant->worktimes()->sync($request->worktimes, false);
//Display a successful message upon save
Session::flash('flash_message', 'Restaurant, '. $restaurant->title.' created');
return redirect()->route('restaurants.index');
}
inside your front.restaurantshow view:
#php
// To retrieve back from DB to MENU and PRICE values as ARRAY
$CustomArray = json_decode($restaurant->custom_menu_price, TRUE);
#endphp
#foreach ($CustomArray as $menu => $price)
Menu Name: {{ $menu }} <br>
Menu Price: {{ $price }} <br><br>
#endforeach
Hope it makes sense.
Related
I am trying to edit code I found on a GitHub repository of Laravel Daily https://github.com/LaravelDaily/Laravel-8-Import-CSV.This is a system that matches the fields of the DB table and a .csv document before loading the data into the database. I'm trying to add some more fields to the table, but I'm getting an error Undefined index: phone_number because I don't have phone_number in the CSV document.
import_fields.blade
<tr>
#foreach ($csv_data[0] as $key => $value)
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">
<select name="fields[{{ $key }}]">
#foreach ($db_field as $field)
<option value="{{ (\Request::has('header')) ? $field : $loop->index }}"
#if ($key === $field) selected #endif>{{ $field }}</option>
#endforeach
</select>
</td>
#endforeach
</tr>
public function parseImport(CsvImportRequest $request)
{
if ($request->has('header')) {
$headings = (new HeadingRowImport)->toArray($request->file('csv_file'));
$data = Excel::toArray(new ContactsImport, $request->file('csv_file'))[0];
} else {
$data = array_map('str_getcsv', file($request->file('csv_file')->getRealPath()));
}
if (count($data) > 0) {
$csv_data = array_slice($data, 0, 2);
$csv_data_file = CsvData::create([
'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
} else {
return redirect()->back();
}
// I have added this function here to get fields from my table
$contact = new Contact;
$table = $contact->getTable();
$db_field = \Schema::getColumnListing($table);
return view('import_fields', [
'headings' => $headings ?? null,
'csv_data' => $csv_data,
'csv_data_file' => $csv_data_file,
'db_field' => $db_field
]);
}
public function processImport(Request $request)
{
$data = CsvData::find($request->csv_data_file_id);
$csv_data = json_decode($data->csv_data, true);
foreach ($csv_data as $row) {
$contact = new Contact();
$table = $contact->getTable();
$db_field = \Schema::getColumnListing($table);
foreach ($db_field as $index => $field) {
if ($data->csv_header) {
if (array_key_exists($field, $request->fields)) {
$contact->$field = $row[$request->fields[$field]];
}
} else {
if (array_key_exists($index, $request->fields)) {
$contact->$field = $row[$request->fields[$index]];
}
}
}
$contact->save();
}
return redirect()->route('contacts.index')->with('success', 'Import finished.');
}
My migration file is here
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('middle_name')->nullable();
$table->string('last_name');
$table->string('email');
$table->string('phone_number');
});
Also, this is the structure of CSV I have
id first_name last_name email phone
When i do dd request here i get this result
public function processImport(Request $request)
{
dd($request->fields);
//RESULT
array:5 [▼
"id" => "id"
"first_name" => "first_name"
"last_name" => "last_name"
"email" => "email"
"phone" => "phone_number"
]
I get this error when I try to match phone from CSV with phone_numberfrom db
SQLSTATE[HY000]: General error: 1364 Field 'phone_number' doesn't have a default value (SQL: insert into contacts (email, first_name, id, last_name, updated_at, created_at) values (asorbie0#paginegialle.it, Ariela, 1, Sorbie, 2023-02-06 09:15:20, 2023-02-06 09:15:20))
[UPDATES]
if i add phone field on db table like this
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('middle_name')->nullable();
$table->string('last_name');
$table->string('email');
$table->string('phone')->nullable();
$table->string('phone_number')->nullable();
and but trying to match value off phone to phone_number when uploading data from excel file , now i am getting this error.
Undefined index: phone_number
I want to ask, I want to post notification data but based on the number of existing users. I've tried like this but only post 1 data, while there are 2 user data, please help.
$acc = $registrant->update([
'approval' => 1,
'description' => $request->description,
]);
$notification = new Notification();
$roleuser = User::where('is_admin', 4)->orWhere('is_admin', '3')->get();
foreach ($roleuser as $key => $value) {
$notification->user_id = $value->id;
$notification->type = 'Menunggu Pelatihan';
$notification->title = 'Pendaftar menunggu untuk pelatihan';
$notification->message = "halo " . $value->name . " Pendaftar dengan NIP " . $registrant->nip . " menunggu untuk pelatihan";
$notification->save();
}
Hello everyone I'm getting confused because when I'm running a code with some condition only 1 column getting updated and the others column stay null, I'm sure there is no typo with the column name in table nor in code here is my code :
public function solusi_line($id)
{
$idasli = base64_decode($id);
$solusi = solusi::where('request_id', $idasli)->orderBy('created_at', 'asc')->get();
$count = solusi::where('request_id', $idasli)->orderBy('created_at', 'desc')->count();
$cekakun = Session::get('id');
$adminkah = Admin::where('user_id', $cekakun)->count();
// dd($solusi);
//jika admin ke bagian sini
if ($adminkah != 0) {
# code...
return view('admin.detail_feedback', compact('solusi', 'count'));
} else {
return view('user.detailfeedback_user', compact('solusi', 'count'));
}
//klo user kebagian user
}
public function FirstFeedback($id)
{
$datas = Kirim::where('id', $id)->first();
return view('admin.detailprogress', compact('datas'));
}
//solusi dari admin
public function solusiPost(Request $request)
{
$itungsolusi = solusi::where('request_id', $request->idRequest)->count();
$data = new solusi();
$data->request_id = $request->idRequest;
$data->pengirim_id = Session::get('id');
$data->penerima_id = $request->idPenerima;
$data->solusi = $request->solusi;
$file = $request->file('lampiran_solusi');
if (!empty($file)) {
$ext = $file->getClientOriginalExtension();
$name = time() . '.' . $ext;
$file->move('upload/lampiran/', $name);
$data->lampiran = $name;
$data->url_lampiran = url('upload/lampiran') . "/" . $name;
} else {
$data->lampiran = null;
$data->url_lampiran = null;
}
if ($data->save()) {
//matiin sementara
$check = DB::table('kirims')->where('id', $data->request_id)->first();
$user = Kirim::find($check->id);
// dd($user);
if (!is_null($user)) {
// $user->update(['status' => 'CheckByUser', 'status_feedback' => 'Ya']);
$user->update(['remarks' => 'Ya', 'status' => 'CheckByUser', 'status_feedback' => 'Ya']);
}
//just status column is success to update but not the remarks and status_feedback column
$id_solusi = $data->id;
$thisUser = DB::table('kirims')
->join('simpan_users', 'kirims.pengirim_id', '=', 'simpan_users.user_id')
->join('solusis', 'kirims.id', '=', 'solusis.request_id')
->where('kirims.id', $data->request_id)
->where('solusis.id', $id_solusi)
->select('kirims.email', 'kirims.ticket_id', 'solusis.solusi', 'solusis.lampiran', 'solusis.url_lampiran')
->first();
// dd($thisUser);
here the problem
$check = DB::table('kirims')->where('id', $data->request_id)->first();
$user = Kirim::find($check->id);
// dd($user);
if (!is_null($user)) {
// $user->update(['status' => 'CheckByUser', 'status_feedback' => 'Ya']);
$user->update(['remarks' => 'Ya', 'status' => 'CheckByUser', 'status_feedback' => 'Ya']);
}
//just status column is success to update but not the remarks and status_feedback column
I really appreciate for any help, I getting stuck because laravel not showing error too, thank you.
You should check your Kirim model, where you need to define $fillable property. Something like below.
class Kirim extends Model {
protected $fillable = ['remarks', 'status', 'status_feedback',''];
// All fields inside $fillable array can be mass-assigned
}
use update statement like this.
$user->remarks = 'Ya',
$user->status = 'CheckByUser',
$user->status_feedback = 'Ya'
$user->update();
few days ago i faced the same issue and fixed it as i told you .
I need to cache the results from Steam API parsing. And so the cached result lasts 15 minutes. I have a code:
public function load()
{
if (Auth::guest()) return response()->json(['success' => false, 'msg' => 'You need login!']);
$inventory = $this->getInventory(file_get_contents('http://steamcommunity.com/inventory/' . $this->user->steamid64 . '/570/2?l=russian&count=5000', true));
if (!$inventory) {
return response()->json(['success' => false, 'msg' => 'Error']);
}
$items = [];
$items_with_prices = json_decode(\Storage::get('prices.txt'));
$items_with_prices_by_key = [];
foreach ($items_with_prices->items as $item_price_key => $item_price_data) {
$items_with_prices_by_key[$item_price_key] = $item_price_data->price;
}
foreach ($inventory['rgInventory'] as $info) {
$item = $inventory['rgDescriptions'][$info['classid'] . '_' . $info['instanceid']];
if ($item['tradable'] == 0) continue;
$price = 0;//InventoryController::getItemPrice($item['market_hash_name']);
if (array_key_exists($item['market_hash_name'], $items_with_prices_by_key)) {
$price = $items_with_prices_by_key[$item['market_hash_name']];
}
if (!$price) continue;
if ($price < 1) $price = 0.64;
$type = $this->getType($item['type']);
$items[] = [
'id' => $info['id'],
'classid' => $item['icon_url'],
'price' => round($price, 2),
'type' => $type
];
}
usort($items, function($a, $b){
return ($b['price'] - $a['price']);
});
return response()->json(['success' => true, 'items' => $items]);
}
This code only works when a site user clicks on the "show my items" button and a request is sent to the list of user items in Steam Dota 2. Now if click constantly to get a list of items, Steam can block the server’s IP address for 24 hours. As I understand it, I need to throw the result of a $inventory variable into the cache. I create database table cache with fields id, user_id, items, date.
How can I now cache the result from a $inventory variable of 15 minutes?
Here is basic caching in laravel
$rememberTimeInSeconds = 3600;
$cachedResult = Cache::remember('name_of_your_cache', $rememberTimeInSeconds, function(){
// It can be any logic I just showing a simple query.
$users = User::all();
return $users;
});
how to take the auto increment value to post.
here I insert two tables successfully, I create a condition after insertion, then update the data.
I have two tables, the first 'service' table and the second table 'customer_address'
customer_address table, has id_address as autoincrement.
when inserting data into two tables, I want to get the value id_address in the customer_address table. to be updated to the 'service' table.
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
//'id_alamat' => this autoincrement
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db-> select('id_alamat')-> from('customer_address')->where('id_kota', $kot)->get()-> result();
foreach($sheet as $value) {
$hsl = array(
'id_muat' => $value - > id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}
when I updated the 'service' table I updated everything. how to update based on the data input only?
You must send id_alamat from view to your controller and make a unique code not just using autoincrement.
for example:
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
'id_alamat' => $row['id_alamat'],
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db->select('id_alamat')->from('customer_address')->where('id_kota', $kot)->get()-> result();
//change $sheet to $isi
foreach($isi as $value) {
$hsl = array(
'id_muat' => $value->id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}