Foreach in Yajra DataTable Laravel - laravel

I'm trying to put a foreach loop inside my datatable but it wont work,
P.S. if I remove the foreach everything works fine already,
attached here is my code
$Product = Product::query();
$colors = Color::all();
return Datatables::eloquent($Product)
->addColumn('category_name', function($row) {
$category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
return $category;
})
->addColumn('add_color', function($row) {
$return =
'<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="' . $row->id . '">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>
'.foreach ($colors as $color){.'
<option value="test">test</option>'.}.'
</select>
</div>';
return $return;
});

That won't work, you're attaching a foreach into a string
What you may do is perform the foreach first to prepare the items you want to attach in that string.
E.g.,
<option>something</option>
<option>something more</option>
Before setting the $return do the foreach:
->addColumn('add_color', function($row) {
$options = ''
// here we prepare the options
foreach ($colors as $color) {
$options .= '<option value="test">$color</option>';
}
$return =
'<form class="form-inline" method="post" action="/procurement/add product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="'.$row->id.'">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>' . $options . '</select>
</div>';
return $return;
})

You need to perform foreach outside your return. and then you also need no use or import the $color variable inside your data table. something like this ..
$Product = Product::query();
$colors = Color::all();
return Datatables::eloquent($Product)
->addColumn('category_name', function($row) {
$category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
return $category;
})
->addColumn('add_color', function($row) use ($colors) {
$options = '';
foreach ($colors as $color) {
$options .= '<option value="test">$color</option>';
}
$return =
'<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
<input type="hidden" name= "product_id" value="' . $row->id . '">
<div class="form-group">
<select name="color_id" class="form-control" required autofocus>
</select>
</div>';
return $return;
});

Related

Image saving as tmp in database in Laravel 8

Blade File
<form action="{{route('sproduct.store')}}" method="post" enctype="multipart/form-data"
class="w-75 mx-auto mt-5 mb-5">
#csrf
<div class="form-group mt-2 mb-2">
<label for="formgroupexampleinput">Select Product</label>
<select name="products" id="products">
<option>Select Product</option>
#foreach ($products as $product)
<option value="{{$product->id}}">{{$product->title}}</option>
#endforeach
</select>
</div>
<div class="form-group mt-3 mb-3">
<label for="formgroupexampleinput">Display Images</label>
<input type="file" name="file[]" multiple>
</div>
<input type="submit" class="form-control btn-primary w-25" value="Submit">
</form>
Fuction
public function store(Request $request)
{
if ($request->hasfile('file')) {
foreach ($request->file as $file) {
$fileExt = $file->getClientOriginalExtension();
$image_name = "img_".rand(123456,999999). "." .$fileExt;
$destination_path = public_path('/uploads/products_images/display_images');
$file->move($destination_path, $image_name);
$image = new Image();
$image->image = $file;
$image->product_id = $request->products;
$image->save();
}
return "done";
}
}
Question
hi, I am trying to add images to my images table but the image is saving as a tmp file in the database but saving as a jpg in the given folder. I don't know the solution to this. Please let me know why this is happening and how to fix it.
Thankyou in Advance.
mikenenter code here in comment told me I needed to save the name of the file.
public function store(Request $request)
{
if ($request->hasfile('file')){
foreach ($request->file as $file) {
$fileExt = $file->getClientOriginalExtension();
$image_name = "img_".rand(123456,999999). "." .$fileExt;
$destination_path = public_path('/uploads/products_images/display_images');
$file->move($destination_path, $image_name);
$image = new Image();
$image->image = $image_name;
$image->product_id = $request->products;
$image->save();
}
return "done";
}
}

Call to a member function store() on null

I'm just wondering why this doesn't work for my Item Controller however on other controller it worked.
Controller for Item
public function store(Request $request, $id)
{
$categories = Category::all();
$userId = Auth::user()->id;
$item = new Item;
$item->store_id = $userId;
$item->name = $request->name;
$item->description = $request->description;
$item->unit_price = $request->unit_price;
$path = $request->image->store('images', 'public');
$item->picture = $path;
$item->category_id = $request->category_id;
$item->is_available = 1;
$item->is_archived = 0;
$item->save();
return redirect('/store/index')->with('status', 'Item successfully added!');
}
HTML form for creating item data
<form method="post" action='{{ url("item/store/$stores->id") }}' enctype="mutlipart/form-data">
#csrf
<input placeholder="Item Name" type="text" name="name" value="{{ old('name') }}" required autocomplete="off">
<input placeholder="Item Description" type="text" name="description" value="{{ old('description') }}" required autocomplete="off">
<input placeholder="000.00" type="decimal" name="unit_price" value="{{ old('unit_price') }}" required autocomplete="off">
<input type="file" name="picture" required>
<label>Category</label>
<select class="form-control" name="category_id">
<option value selected disabled>Select Category</option>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
<button type="submit" class="btn btn-warning">Add</button>
</form>
Thank you for answering
There are no any input file named image your input file name is picture.
if you have a file field, and you try to check it with $request->has(‘file’), it will always return FALSE. For files there is a specific method :
$path = $request->image->store('images', 'public');
$item->picture = $path;
Change to
$path = "no_image.png";
if ($request->hasFile('picture')) {
// $path = $request->picture->store('images', 'public');
$file = $request->picture;
$fName = time() . $file->getClientOriginalName();
$file->move('images', $fName );
$path = 'images/'.$fName;
}
$item->picture = $path;

How to add additional tags to csv import data at time of import

Using a text input field I need to add tags to the records being imported via CSV import module. In the controller, I am automatically adding user id, team id, and timestamp to all imported records and now I need to add user-defined tags to all records at the time of import.
What do in need in my controller to achieve this functionality?
<?php
`namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use SpreadsheetReader;
use Illuminate\Support\Facades\File;
class CsvImportController extends Controller
{
public function parse(Request $request)
{
$file = $request->file('csv_file');
$request->validate([
'csv_file' => 'mimes:csv,txt',
]);
$path = $file->path();
$hasHeader = $request->input('header', false) ? true : false;
$reader = new SpreadsheetReader($path);
$headers = $reader->current();
$lines = [];
$lines[] = $reader->next();
$lines[] = $reader->next();
$filename = str_random(10) . '.csv';
$file->storeAs('csv_import', $filename);
$modelName = $request->input('model', false);
$fullModelName = "App\\" . $modelName;
$model = new $fullModelName();
$fillables = $model->getFillable();
$redirect = url()->previous();
return view('csvImport.parse_import',
compact('headers', 'filename', 'fillables', 'hasHeader', 'modelName', 'lines', 'redirect'));
}
public function process(Request $request)
{
$filename = $request->input('filename', false);
$path = storage_path('app/csv_import/' . $filename);
$hasHeader = $request->input('hasHeader', false);
$fields = $request->input('fields', false);
$fields = array_flip(array_filter($fields));
$modelName = $request->input('modelName', false);
$model = "App\\" . $modelName;
$reader = new SpreadsheetReader($path);
$insert = [];
foreach ($reader as $key => $row) {
if ($hasHeader && $key == 0) {
continue;
}
$tmp = [];
foreach ($fields as $header => $k) {
$tmp[$header] = $row[$k];
}
if (auth()->user()->team_id) {
$tmp['created_by_id'] = auth()->user()->id;
$tmp['created_by_team_id'] = auth()->user()->team_id;
$tmp['created_at'] = now();
}
$insert[] = $tmp;
}
$for_insert = array_chunk($insert, 100);
foreach ($for_insert as $insert_item) {
$model::insert($insert_item);
}
$rows = count($insert);
$table = str_plural($modelName);
File::delete($path);
$redirect = $request->input('redirect', false);
return redirect()->to($redirect)->with('message', trans('global.app_imported_rows_to_table',
['rows' => $rows, 'table' => $table]));
}
My View:
<div class='row'>
<div class='col-md-12'>
<div class="panel panel-default">
<div class="panel-heading">
#lang('global.app_csvImport')
</div>
<div class="panel-body table-responsive">
<form class="form-horizontal" method="POST" action="{{ route('admin.csv_process') }}">
{{ csrf_field() }}
<input type="hidden" name="filename" value="{{ $filename }}"/>
<input type="hidden" name="hasHeader" value="{{ $hasHeader }}"/>
<input type="hidden" name="modelName" value="{{ $modelName }}"/>
<input type="hidden" name="redirect" value="{{ $redirect }}"/>
<table class="table">
#if (isset($headers))
<tr>
#foreach ($headers as $field)
<th>{{ $field }}</th>
#endforeach
</tr>
#endif
#if($lines)
#foreach ($lines as $line)
<tr>
#foreach ($line as $field)
<td>{{ $field }}</td>
#endforeach
</tr>
#endforeach
#endif
<tr>
#foreach ($headers as $key => $header)
<td>
<select name="fields[{{ $key }}]">
<option value=''>Please select</option>
#foreach ($fillables as $k => $fillable)
<option value="{{ $fillable }}"
#if (strtolower($header) === strtolower($fillable)) selected #endif>{{ $fillable }}</option>
#endforeach
</select>
</td>
#endforeach
</tr>
</table>
<button type="submit" class="btn btn-primary" id="btn-import">
#lang('global.app_import_data')
</button>
<button type="submit" class="btn btn-primary" id="btn-import2">
#lang('global.app_import_data')
</button>
</form>
</div>
</div>
</div>

Login using username or email in codeigniter

I am unable to login with email address. login is done through username only, when i try to login with email it redirect me to login page.
Please help me, so i can login with email also.
I checked many online sources but not helpful for me.
My Controllers:
STORE_ACCOUNTS_CONTROLLER
function get_with_double_condition($col1, $value1, $col2, $value2)
{
$this->load->model('mdl_store_accounts');
$query = $this->mdl_store_accounts->get_with_double_condition($col1, $value1, $col2, $value2);
return $query;
}
YOURACCOUNTS_CONTROLLER
function submit_login()
{
$this->load->module('site_security');
$this->load->module('store_accounts');
$submit = $this->input->post('submit',TRUE);
if ($submit=="Submit") {
//process the form
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','required|min_length[5]|max_length[60]|callback_username_check');
$this->form_validation->set_rules('pword','Password','required|min_length[7]|max_length[35]');
if ($this->form_validation->run()==TRUE) {
//figure out user_id
$col1 = 'username';
$value1 = $this->input->post('username', TRUE);
$col2 = 'email';
$value2 = $this->input->post('email', TRUE);
$query = $this->store_accounts->get_with_double_condition($col1, $value1, $col2, $value2);
foreach ($query->result() as $row) {
$user_id = $row->id;
}
//send them to the private page
$this->_in_you_go($user_id, $login_type);
$remember = $this->input->post('remember', TRUE);
if ($remember=="remember-me") {
$login_type = "longterm";
}
else
{
$login_type = "shortterm";
}
}
else
{
echo validation_errors();
}
}
}
function username_check($str)
{
$this->load->module('site_security');
$this->load->module('store_accounts');
$error_msg = "You did not enter a correct username and/or password.";
$col1 = 'username';
$value1 = $str;
$col2 = 'email';
$value2 = $str;
$query = $this->store_accounts->get_with_double_condition($col1, $value1, $col2, $value2);
$num_rows = $query->num_rows();
if ($num_rows<1) {
$this->form_validation->set_message('username_check', $error_msg);
return FALSE;
}
foreach ($query->result() as $row) {
$pword_on_table = $row->pword;
}
$pword = $this->input->post('pword', TRUE);
$result = $this->site_security->_verify_hash($pword, $pword_on_table);
if ($result==TRUE) {
return TRUE;
}
else
{
$this->form_validation->set_message('username_check', $error_msg);
return FALSE;
}
}
My Model:
STORE_ACCOUNTS_MODEL
function get_with_double_condition($col1, $value1, $col2, $value2)
{
$table = $this->get_table();
$this->db->where($col1, $value1);
$this->db->or_where($col2, $value2);
$query=$this->db->get($table);
return $query;
}
My View:
LOGIN_PAGE
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form class="form-signin" action="<?= $form_location ?>" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputText" class="sr-only">Username or Email address</label>
<input type="text" name="username" value="<?= $username?>" id="inputEmail" class="form-control" placeholder="Username or Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="pword" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" value="remember-me"> Remember me
</label>
</div>
<button name="submit" value="Submit" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</div>
</div> <!-- /container -->
Your form is only POST username.
In case of email this don't validate in code
$this->form_validation->set_rules('username','Username','required|min_length[5]|max_length[60]|callback_username_check');
and $value2 will be empty
$value2 = $this->input->post('email', TRUE);
I didnt read the whole code ill provide you with a simple code that will be effective :
View File:
<form action='controller.php' method='POST'>
<input type='email' name='email'>
<input type='password' name='pass'>
<input type='submit' value='login' name='login'>
</form>
Controller.php
(define the model in constructor first in order to execute the statement $this->login_model->login();)
if(isset($_POST['login'])){
$condition=$this->login_model->login();
if(!empty($condition) && isset($condition)){
redirect('');//redirect to where ever you want or you can set the session as well
}}
login_model.php
public function login(){
$email=$_POST['email'];
$password=$_POST['pass'];
$this->db->select('*');
$this->db->from('table_name');
$this->db->where('email',$email);
$this->db->where('pass',$password);
$q= $this->db->get()-results();
return $q;
}

Laravel 5.4 Multiple upload and Inserting data

Hello everyone and thank you in advance, first of all sorry if my code is so confused I am still learning ^^.
I am trying to make a product with different attribute plus 3 different images(making the product gallery) and a feature image,
I have succeed to create the attributes and feature image.
The problem is with the 3 image for the gallery I cant store (neither in DB or image folder)
I have Two tables (product and productgallery) the relation between them is hasMany (I am using Laravel 5.4)
This the error I got after run the code
SQLSTATE[HY000]: General error: 1364 Field 'product_id' doesn't have a default value (SQL: insert into `product_galleries` (`updated_at`, `created_at`) values (2017-05-13 20:58:20, 2017-05-13 20:58:20))
(sorry for my English which for sure will make it harder to understand my question)
ProductController
public function store(UploadRequest $request)
{
$product = new Product();
$product->product_name = $request->product_name;
$product->product_description = $request->product_description;
if($request->hasFile('product_preview')) {
$file = Input::file('product_preview');
$filename = time(). '-' .$file->getClientOriginalName();
$product->product_preview = $filename;
$file->move(public_path().'/images/product-feature', $filename);
}
$product->category_id = $request->category_id;
$product->color_id = $request->color_id;
$product->size_id = $request->size_id;
$product->material_id = $request->material_id;
// $product->fantasia_id = $request->fantasia_id;
$productgallery = new ProductGallery();
if($request->hasFile('fileToUpload[]')) {
$files = Input::file('fileToUpload[]');
foreach ($request->$files as $photo) {
$filename = time(). '-' .$photo->getClientOriginalName();
$productgallery->product_images = $filename;
$photo->move(public_path().'/images/product-gallery', $filename);
$productgallery->product_id = 1;
}
}
$product->save();
$productgallery->save();
return $this->create()->with('success', 'Uploaded Successfully');
}
Upload request (FormRequest)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UploadRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'product_name' => 'required|max:120',
'category_id' => 'required|integer',
'product_preview' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
];
$fileToUpload = count($this->input('fileToUpload'));
foreach(range(0, $fileToUpload) as $index) {
$rules['fileToUpload.' . $index] = 'image|mimes:jpeg,bmp,png|max:2000';
}
return $rules;
}
}
the view for the form
#extends('layouts.backend-master')
#section('styles')
<link rel="stylesheet" href="">
#endsection
#section('content')
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<h1>Add a new product</h1>
<form action="{{route('products.store')}}" method="post" enctype="multipart/form-data">
<div class="input-group">
<label for="product_name">Name of the product</label>
<input type="text" name="product_name" id="product_name"/>
</div>
<div class="input-group">
<label for="product_description">Product Description</label>
<textarea type="text" name="product_description" id="product_description" rows="8"></textarea>
</div>
<div class="input-group">
<label for="product_preview">Feature Image:</label>
<input type="file" name="product_preview" id="file">
</div>
<div class="input-group">
<label for="category_id">Category</label>
<select name="category_id" id="category_id">
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->category_name }}</option>
#endforeach
</select>
</div>
<div class="input-group">
<label for="color_id">Color</label>
<select name="color_id" id="color_id">
#foreach($colors as $color)
<option value="{{ $color->id }}">{{ $color->color_name }}</option>
#endforeach
</select>
</div>
<div class="input-group">
<label for="size_id">Size</label>
<select name="size_id" id="size_id">
#foreach($sizes as $size)
<option value="{{ $size->id }}">{{ $size->size_name }}</option>
#endforeach
</select>
</div>
<div class="input-group">
<label for="material_id">Material</label>
<select name="material_id" id="material_id">
#foreach($materials as $material)
<option value="{{ $material->id }}">{{ $material->material_type }}</option>
#endforeach
</select>
</div>
<div class="input-group">
<label for="fileToUpload">Product Gallery:</label>
<input type="file" name="fileToUpload[]" id="fileToUpload" multiple >
</div>
<button type="submit" class="btn">Add</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
#endsection
#section('scripts')
#endsection
thank you
You'll need to look at Laravel relationships API documentation. Here's a link to read more about it Laravel 5.4 Eloquent Relationships
Quick tip to fix that
You should add a foreign key in your database/migration file
For a migration you can simply add
$table->foreign('product_id')->references('id')->on('products');
And add this method to your Product model
public function productgallery(){
return $this->hasMany(Productgallery::class);
}
and this to your Productgallery model
public function product(){
return $this->belongsTo(Product::class);
}
Note: You'll still need to populate the product_id field within your request
Package solution
I'd recommend you use a 3rd party package for that matter, as it will be less work, cleaner and more solid to use.
You can look more into spatie's medialibrary for Laravel
I think this is what you want.
This will create a new Product and create a new ProductGallery for each image passed in $request->file('fileToUpload[]'):
$product = new Product();
$product->product_name = $request->product_name;
$product->product_description = $request->product_description;
if($request->hasFile('product_preview')) {
$file = Input::file('product_preview');
$filename = time(). '-' .$file->getClientOriginalName();
$product->product_preview = $filename;
$file->move(public_path().'/images/product-feature', $filename);
}
$product->category_id = $request->category_id;
$product->color_id = $request->color_id;
$product->size_id = $request->size_id;
$product->material_id = $request->material_id;
// $product->fantasia_id = $request->fantasia_id;
// First save the product (so that you have it's ID)
$product->save();
// Then create galleries
if($request->hasFile('fileToUpload[]')) {
$files = Input::file('fileToUpload[]');
foreach ($files as $photo) {
$productgallery = new ProductGallery();
$filename = time(). '-' .$photo->getClientOriginalName();
$productgallery->product_images = $filename;
$photo->move(public_path().'/images/product-gallery', $filename);
$productgallery->product_id = $product->id; // Save it to the newly created product
$productgallery->save();
}
}
return $this->create()->with('success', 'Uploaded Successfully');

Resources