How to pass in user id into foreach loop? - laravel

I'm a novice when it comes to PHP and Laravel and am embarrassed that I haven't figured this out yet. I'm trying to provide an option for my user to import their database into the application. However, I need to attach a user id to each row so it can be saved with that user. I've tried multiple attempts to grab that user id and pass it into the foreach loop so it can be saved. Any guidance I can receive, I'd be most grateful. I am using Maatwebsite/Laravel-Excel facade.
Here is my Controller:
class ImportController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user();
$data['user_id'] = $user->id;
$insert[] = [
'user_id' => $value->user_id,
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'title' => $value->title,
'level' => $value->level,
'company' => $value->company,
'email' => $value->email,
'address_1' => $value->address_1,
'address_2' => $value->address_2,
'city' => $value->city,
'state' => $value->state,
'zip_code' => $value->zip_code,
'office_tel' => $value->office_tel,
'mobile_tel' => $value->mobile_tel,
'member_since'=> $value->member_since
];
}
if(!empty($insert)){
DB::table('members')->insert($insert);
Session::flash('flash_message', 'Database successfully imported!');
}
}
}
return back();
}
}
Here is my route:
Route::post('importExcel', 'ImportController#importExcel');
Here is my view:
<button type="button" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#importExcel">Import</button>
<div class="modal fade" id="importExcel" tabindex="-1" aria-labelledby="importExcelLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Import Your Database</h4>
</div>
<div class="modal-body">
<p>Click browse to import your database. Only Microsoft Excel extensions are acceptable. Please label your columns as follows:</p>
<ul>
<li>user_id (leave this column empty)</li>
<li>first_name</li>
<li>last_name</li>
<li>title</li>
<li>level</li>
<li>company</li>
<li>address_1</li>
<li>address_2</li>
<li>city</li>
<li>state</li>
<li>zip_code</li>
<li>office_tel</li>
<li>mobile_tel</li>
<li>member_since</li>
</ul>
<form action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
<input type="file" name="import_file" />
<input type="hidden" name="_token" value="{{csrf_token()}}">
<button type="submit" class="btn btn-primary">Import File</button>
</form>
</div><!-- /.modal-body-->
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Close</button>
</div><!-- /.modal-footer-->
</div><!-- /.modal-content-->
</div><!-- /.modal-dialog-->
</div><!-- /.modal-->
Here is my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
protected $fillable = [
'user_id',
'first_name',
'last_name',
'title',
'level',
'company',
'email',
'address_1',
'address_2',
'city',
'state',
'zip_code',
'office_tel',
'mobile_tel',
'member_since' ];
}

First of all: Where do you set $insert? You have to set this variable with the data you like to import. Despite of that you can try the following:
If I understand you right, the database-field user_id should contain the ID of the logged in user - if so, try in your controller the following in importExcel (see comment):
public function importExcel(Request $request)
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user();
$data['user_id'] = $user->id;
[
'user_id' => $user->id, // Access here the userId of the logged in user
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'title' => $value->title,
'level' => $value->level,
'company' => $value->company,
'email' => $value->email,
'address_1' => $value->address_1,
'address_2' => $value->address_2,
'city' => $value->city,
'state' => $value->state,
'zip_code' => $value->zip_code,
'office_tel' => $value->office_tel,
'mobile_tel' => $value->mobile_tel,
'member_since'=> $value->member_since
];
}
if(!empty($insert)){
DB::table('members')->insert($insert);
Session::flash('flash_message', 'Database successfully imported!');
}
}
}
return back();
}
Hope that helps :)

Related

How to break line in textarea in laravel and then echo it by foreach loop?

The name of my controller is ProductController, This is my controller
public function store(Request $request)
{
$request->validate([
'product_name' => 'required',
'product_detail' => 'required',
'product_image' => 'required',
'admin_name' => 'required',
]);
$product_image = $request->file('product_image');
$new_name = rand().'.'.$product_image->getClientOriginalExtension();
$product_image->move(public_path('product_image'), $new_name);
$form_data = array(
'product_image' => $new_name,
);
// Product::create($form_data);
$product = Product::create([
'product_name' => $request->input('product_name'),
'product_detail' => $request->input('product_detail'),
'admin_name' => $request->input('admin_name'),
'product_image' => $new_name,
]);
return redirect('products')->with('success', 'Data Added successfully.');
}
This is my index page where I want to echo it, I have doubt in Product_detail
#foreach($products as $product)
<div class="col-lg-4 col-md-6 portfolio-item filter-Interior">
<div class="portfolio-wrap">
<div class="portfolio-info">
<h4>{{$product->product_name}}</h4>
<p>
<ul style="color: white">
<li>{{$product->product_detail}}</li>
</ul>
</p>
You can use php's inbuilt function nl2br() or you can explode by PHP_EOL and then run the for loop for unordered list.
<p>{!! nl2br($body) !!}<p>
<!-- OR -->
<ul>
#foreach (explode(PHP_EOL, $body) as $item)
<li>{{ $item }}</li>
#endforeach
</ul>

send an email with attachment using a form

I can't understand what the problem may be:
I state that the code without the part of the attachment works
function submit(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'file' => 'mimes:pdf,doc,docx'
]);
$data = array(
'name_data' => $request->name,
'cognome_data' => $request->cognome,
'luogo_data' => $request->luogo,
'date_data' => $request->date,
'telefono_data' => $request->telefono,
'email_data' => $request->email,
'citta_data' => $request->citta,
'provincia_data' => $request->provincia,
'studio_data' => $request->studio,
'lingua_data' => $request->lingua,
'livello_data' => $request->livello,
'lingua2_data' => $request->lingua2,
'livello2_data' => $request->livello2,
'file_data' => $request->file,
'agree_data' => $request->agree
);
Mail::send('mail', $data, function($message) use ($request,$data){
$message->to('pipo#gmail.com', 'piooi')->subject('Send mail ' . $request->name);
$message->from($request->email, $request->name);
if ( isset($data['file_data']))
{
$message->attach($data['file_data']->getRealPath(), array(
'as' => $data['file_data']->getClientOriginalName(),
'mime' => $data['file_data']->getMimeType()));
}
});
Session::flash('success', 'Mail spedita con sucesso');
}
}
I put the piece of the form in question:
<form class="text-left form-email"action="#" enctype="multipart/form-data" method="POST">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Curriculum Vitae:</span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="file" name="file"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Seleziona il file</label>
</div>
</div>
the error that gives the summit is the following:
local.ERROR: Call to a member function getRealPath() on null {"exception":"[object] (Error(code: 0):
Change your mail part to this and see if it works
Mail::send('mail', $data, function($message) use ($request,$data){
$message->to('pipo#gmail.com', 'piooi')->subject('Send mail ' . $request->name);
$message->from($request->email, $request->name);
if($request->hasFile('file')){
$message->attach($request->file->getRealPath(), array(
'as' => $request->file->getClientOriginalName(),
'mime' => $request->file->getMimeType())
);
}
});

Add date into table which is in relation with product in Laravel 6

I have product and auction table. I want to add auction deadline on a specific table using form. when I submit the form the product_id in auction table is not populated and deadline shows time on which form is submited.
Here what I am trying:
I want that the create form get the deadline and store in auction table with product id so I can access it in show method of product.
create.blade.php
#extends('layouts.app')
#section('content')
<div class="mt-3" style="margin-left: 50px;">
<h2>Add new product</h2>
{!! Form::open(['action' => 'ProductsController#store', 'method' => 'POST', 'enctype' =>
'multipart/form-data', 'class' => 'w-50 py-3']) !!}
<div class="form-group">
{{Form::label('name', 'Product Name')}}
{{Form::text('name', '', ['class' => 'form-control', 'placeholder' => 'Product Name'])}}
</div>
<div class="form-group">
{{Form::label('description', 'Product Description')}}
{{Form::textarea('description', '', ['class' => 'form-control', 'placeholder' => 'Product Description', 'rows' => '4'])}}
</div>
<div class="form-group">
{!! Form::Label('category', 'Category') !!}
<select class="form-control" name="category_id">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
{{Form::label('price', 'Product Price')}}
{{Form::number('price', '', ['class' => 'form-control', 'placeholder' => 'Product Price'])}}
</div>
<div class="form-group">
{{Form::label('deadline', 'Auction Deadline')}}
{{Form::date('{{$auction->deadline}}', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('image', 'Product Image')}}
{{Form::file('image', ['class' => '', 'placeholder' => 'Product Image'])}}
</div>
{{Form::submit('Upload Product', ['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
Product Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name', 'price', 'description', 'image',
];
public function category()
{
return $this->belongsTo('App\Category');
}
public function auction()
{
return $this->hasOne('App\Auction');
}
}
ProductsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Product;
use App\Category;
use App\Auction;
class ProductsController extends Controller
{
public function index()
{
$categories = Category::all();
$products = Product::with('category')->latest()->paginate(3);
return view('products.index' ,compact('categories', 'products'));
}
public function create()
{
$categories = Category::all(['id', 'name']);
return view('products.create', compact('categories',$categories));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'category_id' => 'required',
'price' => 'required',
'image' => 'image|nullable',
]);
// Create Product
$product = new Product();
$product->name = request('name');
$product->description = request('description');
$product->category_id = request('category_id');
$product->price = request('price');
$product->image = $fileNameToStore;
$product->save();
$auction = new Auction();
$auction->deadline = request('deadline');
$auction->save();
return redirect('/products')->with('success', 'Product Created');
}
public function show($id)
{
$product = Product::find($id);
return view('products.show', compact('product'));
}
}
you are just creating auction, where is the relation? Delete $product->save(); line. After the $auction->save(); add this line:
$product->auction()->associate($auction);
$product->save();
Final Store method
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'category_id' => 'required',
'price' => 'required',
'image' => 'image|nullable',
]);
// Create Product
$product = new Product();
$product->name = request('name');
$product->description = request('description');
$product->category_id = request('category_id');
$product->price = request('price');
$product->image = $fileNameToStore;
$auction = new Auction();
$auction->deadline = request('deadline');
$auction->save();
$product->auction()->associate($auction);
$product->save();
return redirect('/products')->with('success', 'Product Created');
}
Update for Irrelevant Blade problem
This line is wrong:
{{Form::date('{{$auction->deadline}}', '', ['class' => 'form-control'])}}
You are using blade close string tag in blade string tag.
Should be:
{{Form::date('deadline', '', ['class' => 'form-control'])}}
If auction variable has been passing from controller this will work

Laravel flash message validation

I am creating a CRUD of books and what I wanted to do is like the generated auth files that if someone registers and didn't input any in the textbox, a flash message will return. I am doing that now in my crud but I can only make a flash message when a book is successfully created. This is my store function
public function store(Request $request)
{
$this->validate($request, [
'isbn' => 'required|',
'title' => 'required',
'author' => 'required',
'publisher' => 'required'
]);
Session::flash('msg', 'Book added!');
$books = $request->all();
Book::create($books);
return redirect('books');
}
And in my home.blade.php
#if(Session::has('msg'))
<div class="alert alert-success">
{{ Session::get('msg') }}
</div>
#endif
This actually works but I want to show some ready generated error flash when someone didnt complete fields. How can I do that?
It's pretty simple, first there's a sweet nice feature that is the redirect()->with()
So your controller code could be:
public function store(Request $request)
{
$this->validate($request, [
'isbn' => 'required|',
'title' => 'required',
'author' => 'required',
'publisher' => 'required'
]);
if(Book::create($books)){
$message = [
'flashType' => 'success',
'flashMessage' => 'Book added!'
];
}else{
$message = [
'flashType' => 'danger',
'flashMessage' => 'Oh snap! something went wrong'
];
}
return redirect()->action('BooksController#index')->with($message);
}
Then on your view:
#if (Session::has('flashMessage'))
<div class="alert {{ Session::has('flashType') ? 'alert-'.session('flashType') : '' }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{{ session('flashMessage') }}
</div>
#endif
Bonus you can put this on your footer, so the alerts boxes will vanish after 3 seconds:
<script>
$('div.alert').delay(3000).slideUp(300);
</script>
You could get the individual errors for a field
{!! $errors->first('isbn'); !!}
or you can get all the errors
#foreach ($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
you can use try catch like this
try{
$books = $request->all();
Book::create($books);
Session::flash('msg', 'Book added!');
}
catch(Exception $e){
Session::flash('msg', $e->getmessage());
}

laravel Undefined offset: 0

I am trying to diplay an error mesasge in case the field selected is duplicated in db.For this I am using laravel validation required unique. I am having problem with redirect
Here is store controller
public function store() {
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id'),
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
// Validation has failed.
return Redirect::to('insur_docs/create')->with_input()->with_errors($validation);
} else {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
// redirect
return Redirect::to('/');
}
}
Here is the route
Route::get('insur_docs/create', array('as' => 'insur_docs.create','uses' => 'Insur_DocController#create'));
create controller
public function create() {
$cars = DB::table('cars')->orderBy('Description', 'asc')->distinct()->lists('Description', 'id');
return View::make('pages.insur_docs_create', array(
'cars' => $cars
));
}
insur_docs_create.blade.php
<div id="div-1" class="body">
{{ Form::open(array('url' => 'insur_docs/store', 'class'=>'form-horizontal','id'=>'inline-validate')) }}
<div class="form-group">
{{ Form::label('ownership_cert', 'Ownership Certificate', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('ownership_cert', array('' => '', '1' => 'Yes', '0' => 'No'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid ownership certificate',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('authoriz', 'Authorization', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('authoriz', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid authorization date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('drive_permis', 'Drive Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('drive_permis', array('' => '', '1' => 'Active', '0' => 'Not active'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid drive permission',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('sgs', 'SGS', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('sgs', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid sgs date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('tpl', 'TPL', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('tpl', isset($v->sgs) ? $v->sgs : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid tpl date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('kasko', 'Kasko', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('kasko', isset($v->kasko) ? $v->kasko : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid kasko date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('inter_permis', 'International Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('inter_permis', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid international permission date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('car', 'Car', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('car', $cars, Input::old('class'), array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid car',
'class' => 'form-control'))
}}
{{ $errors->first('car') }}
</div>
</div>
{{ Form::submit('Save', array('class' => 'btn btn-success btn-line')) }}
<input type="button" value="Back" class="btn btn-danger btn-line" onClick="history.go(-1);
return true;">
<div>
#foreach($errors as $error)
<li>{{$error}}</li>
#endforeach
</div>
{{ Form::close() }}
I t displays this error :
Undefined offset: 0
It might be that you are using a get, using post might help. Other than that you are mixing model and controller code. It's always a good idea to seperate these. For instance your redirects should be done inside the controller and not in the model.
http://laravel.com/docs/validation
http://laravelbook.com/laravel-input-validation/
http://culttt.com/2013/07/29/creating-laravel-4-validation-services/
It's also better to do stuff on $validator->passes() and then else return with errors.
Controller
public function store() {
$data = [
"errors" => null
];
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id')
);
$validation = Validator::make(Input::all(), $rules);
if($validation->passes()) {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
return Redirect::to('/');
} else {
$data['errors'] = $validation->errors();
return View::make('pages.insur_docs_create', $data);
}
}
Your errors will be available in your view under $errors. Just do a {{var_dump($errors)}} in your blade template to verify that they are there.
View
#if($errors->count() > 0)
<p>The following errors have occurred:</p>
<ul>
#foreach($errors->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
#endif
I Think this is a really better answer from this refrenece
Laravel 4, ->withInput(); = Undefined offset: 0
withInput() doesn't work the way you think it does. It's only a function of Redirect, not View.
Calling withInput($data) on View has a completely different effect; it passes the following key value pair to your view: 'input' => $data (you get an error because you're not passing any data to the function)
To get the effect that you want, call Input::flash() before making your view, instead of calling withInput(). This should allow you to use the Input::old() function in your view to access the data.
Alternatively, you could simply pass Input::all() to your view, and use the input[] array in your view:
View::make(...)->withInput(Input::all());
which is translated to
View::make(...)->with('input', Input::all());
As for your comment, I recommend doing it like so:
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
$category = Input::get('category');
$location = Input::get('location');
$type = Input:: get('type');
$data = compact('position_options', 'category_options', 'location_options', 'category', 'type', 'location');
return View::make('jobsearch.search', $data);
also thinks about laravel resource controller. because when we call no parameter get method, it redirects to the show method with ignoring our function name.
eg:-Route::get('hasith', 'Order\OrderController#hasith');----->
this parameter rederect to this function
public function show($id, Request $request) {
//code
}

Resources