Laravel Excel import using Maatwebsite Excel package with additional columns from View - laravel

I am trying to import data into MySQL from an Excel file. My table has 2 foreign keys project_id and site_id when importing I am selecting these 2 fields from dropdowns in my View. Is there a way I can map these 2 fields to my import collection? Mind you, the 2 fields do not exist in the import file (for integrity reasons) but they do exist in the table.
Collection
namespace App\Imports;
use App\Proposal;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ProposalsImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return new Proposal([
'building' => $row['building'],
'floor' => $row['floor'],
'area' => $row['area'],
'room' => $row['room'],
'luminaire' => $row['luminaire'],
'actual_qty' => $row['actual_qty'],
'installed_qty' => $row['installed_qty'],
]);
}
}
Controller
public function import()
{
Excel::import(new ProposalsImport, 'proposals.xlsx');
}
View
#extends('projectmanagement/proposals.base')
#section('action-content')
<!-- Main content -->
<section class="content">
<div class="container">
<div class="box">
<div class="box-header">
</div>
<!-- /.box-header -->
<div class="box-body" data-widget="box-refresh">
#if (session('status'))
<div style="padding-top: 0px;padding-bottom: 0px;"
class="alert alert_cust alert-success alert-dismissable fade in">{{ session('status') }}×</div>
#endif
</div>
<div class="row">
<div class="col-lg-12">
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" action="{{ route('proposals.store') }}">
{{ csrf_field() }}
<div class="row">
<div class="col-md-12">
<div class="form-group{{ $errors->has('project_id') ? ' has-error' : '' }}">
<label for="project_id" class="col-md-4 control-label">Project Name</label>
<div class="col-md-6">
<select id="project_id" class="form-control select2" style="width: 100%;"
name="project_id">
<option value="0" disabled selected>Select Project</option>
#foreach ($projects as $project)
<option value="{{$project->id}}">{{ $project->project_name }}</option>
#endforeach
</select>
#if ($errors->has('project_id'))
<span class="help-block">
<strong>{{ $errors->first('project_id') }}</strong>
</span>
#endif
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<br/>
<div class="form-group{{ $errors->has('site_id') ? ' has-error' : '' }}">
<label for="site_id" class="col-md-4 control-label">Site Name</label>
<div class="col-md-6">
<select id="site_id" class="form-control select2" style="width: 100%;"
name="site_id">
<option value="0" disabled selected>Select Site</option>
#foreach ($sites as $site)
<option value="{{$site->id}}">{{ $site->site_name }}</option>
#endforeach
</select>
#if ($errors->has('site_id'))
<span class="help-block">
<strong>{{ $errors->first('site_id') }}</strong>
</span>
#endif
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<br/>
<div class="form-group{{ $errors->has('proposal_file') ? ' has-error' : '' }}">
<label for="proposal_file" class="col-md-4 control-label">Proposal File</label>
<div class="col-md-6">
<input id="proposal_file" type="file" class="form-control" name="proposal_file" required autofocus>
#if ($errors->has('proposal_file'))
<span class="help-block">
<strong>{{ $errors->first('proposal_file') }}</strong>
</span>
#endif
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<br/>
<div class="form-group">
<div class="col-md-4">
</div>
<div class="col-md-6">
<button type="submit" class="btn col-sm-3 col-xs-5 btn-primary">Upload Proposal</button>
</div>
</div>
<br/>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#push('custom_scripts')
<script>
</script>
#endpush
#endsection

Override import controller's construct method, sending all the parameters you need, like this:
class ProposalsImport implements ToModel, WithHeadingRow
{
protected $project_id;
protected $site_id;
public function __construct($project_id, $site_id)
{
$this->project_id = $project_id;
$this->site_id = $site_id;
}
public function model(array $row)
{
return new Proposal([
'building' => $row['building'],
'project_id' => $this->project_id,
'site_id' => $this->site_id
]);
}
}
And then, call it from your Controller like this:
public function import(Request $request)
{
Excel::import(new ProposalsImport($request->project_id, $request->site_id), 'proposals.xlsx');
}

Related

Error store data laravel when have image in pages

I am insert data product with images in dashboard, when I try to order the product I have error 404 not found and the URL showing value database in table like http://127.0.0.1:8000/shops/order/[%7B%22id%22:2,%22category_id%22:1,%22name_product%22:%22asdasd%22,%22harga%22:123123123,%22image%22:%22product-images//HapOzHmJPim1kIfmIeCM21xesCnIbR5Z7lpzcO8M.jpg%22,%22published_at%22:null,%22created_at%22:%222022-05-23T16:25:00.000000Z%22,%22updated_at%22:%222022-05-23T16:25:10.000000Z%22,%22kategori%22:%7B%22id%22:1,%22name_category%22:%22Top%22,%22created_at%22:%222022-05-23T16:22:40.000000Z%22,%22updated_at%22:%222022-05-23T16:22:40.000000Z%22%7D%7D].
But when I am insert data product without images in dashboard, and then I try to order the product is successful.
This is my route
Route::post('/shops/order/{shop:id}', [OrderController::class, 'store']);
This is OrderController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\User;
use App\Models\Shop;
class OrderController extends Controller
{
public function store(Request $request)
{
$createOrder = $request->validate([
'user_id' => 'required',
'name_product_id' => 'required',
'size' => 'required',
'no' => 'required',
'address' => 'required'
]);
Order::create($createOrder);
return redirect('shops/order/{shop:id}')->with('success', 'Order is successfully!');
}
}
This is my views
#extends('layouts.main')
#section('container')
<div class="container">
<div class="row mt-5">
#foreach ($shops as $shop)
<div class="card mb-3">
<div class="row g-0">
<div class="col-md-4">
<img src="{{ asset('storage/' . $shop->image) }}" alt="{{ $shop->name_product }}" class="img-fluid rounded-start" style="max-height: 400px; overflow:hidden">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">{{ $shop->name_product }}</h5>
<p>Jenis {{ $shop->category->name_category }}</p>
<p class="card-text fw-bold">Rp.{{ $shop->price }}</p>
</div>
</div>
</div>
</div>
#endforeach
</div>
<div class="row mt-5">
<div class="col align-self-center">
#if (session()->has('success'))
<div class="alert alert-success text-center" role="alert">
{{ session('success') }}
</div>
#endif
</div>
</div>
<form method="POST" action="/shops/order/{{ $shops }}" class="row g-2" enctype="multipart/form-data">
#csrf
<h3 class="text-center mt-2">Detail Delivery</h3>
<div class="col-md-6">
<div class="mb-3">
<select class="form-select" name="user_id" hidden>
#foreach ($users as $name)
<option value="{{ $name->id }}">{{ $name->id }}</option>
#endforeach
</select>
</div>
<div class="mb-3">
<select class="form-select" name="name_produk_id" hidden>
#foreach ($shops as $shops_id)
<option value="{{ $shops_id->id }}">{{ $shops_id->id }}</option>
#endforeach
</select>
</div>
<div class="mb-3">
<label for="address" class="form-label">Address</label>
<textarea class="form-control" #error('address') is-invalid #enderror id="address" name="address" required>
</textarea>
</div>
</div>
<div class="col-md-4">
<label for="size" class="form-label mt-3">Select size :</label>
<select class="form-select" name="size">
<option selected>S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<div class="mt-3">
<label for="no" class="form-label">Nomor Whatsapp</label>
<input class="form-control" #error('no') is-invalid #enderror id="no" name="no" required autofocus">
</div>
<button type="submit" class="btn btn-primary mt-5">Buy Now</button>
</div>
</form>
</div>
#endsection

Livewire & Select2

I am using Livewire and Slect2 in my project
and I am code to select 2 javascript also but select 2 value is not passed to the database here is my code
My Blade File
<div class="col-12 col-lg-12 col-sm-12">
<div wire:ignore>
<div class="form-group">
<label for="exampleInputRounded0">Section Name</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-globe-asia text-primary"></i></span>
</div>
<select class="form-control rounded-0 " wire:model="cr_classes_id" id="cr_classes_id" style="width: 100%;" tabindex="-1" aria-hidden="true">
#foreach ($classes as $class)
<option value="{{$class->id}}">{{$class->classes_name}}</option>
#endforeach
</select>
</div>
#error('cr_classes_sec_id') <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
</div>
Here is My JS
#push('js')
<script type="text/javascript">
$(document).ready(function () {
$('#cr_classes_id').select2();
$('#cr_classes_id').on('change', function (e) {
var data = $('#cr_classes_id').select2("val");
#this.set('cr_classes_id', data);
});
});
</script>
#endpush
Consol Error
Uncaught TypeError: Cannot read property '$wire' of undefined
at Livewire.value (index.js:31)
at HTMLSelectElement.<anonymous> (ClassRooms:844)
at HTMLSelectElement.dispatch (jquery.min.js:2)
at HTMLSelectElement.v.handle (jquery.min.js:2)
at Object.trigger (jquery.min.js:2)
at HTMLSelectElement.<anonymous> (jquery.min.js:2)
at Function.each (jquery.min.js:2)
at k.fn.init.each (jquery.min.js:2)
at k.fn.init.trigger (jquery.min.js:2)
at n.select (select2.min.js:2)
without wire:ignore Working find and data send to the database
Try this
<div class="col-12 col-lg-12 col-sm-12">
<div wire:ignore.self>
<div class="form-group">
<label for="exampleInputRounded0">Section Name</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-globe-asia text-primary"></i></span>
</div>
<select class="form-control rounded-0 " wire:change="$emit('classChanged', $event.target.value)" style="width: 100%;" tabindex="-1" aria-hidden="true">
#foreach ($classes as $class)
<option value="{{$class->id}}" {{ $cr_classes_id ? 'selected' : ''}} >{{$class->classes_name}}</option>
#endforeach
</select>
</div>
#error('cr_classes_sec_id') <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
</div>
and in component
public $cr_classes_id = '';
public $listeners = [
'classChanged'
];
......
public function classChanged($value)
{
$this->cr_classes_id = $value;
}
try to add ":key="cr_classes_id_key" in your blade file
<div class="col-12 col-lg-12 col-sm-12">
<div wire:ignore :key="cr_classes_id_key">
<div class="form-group">
<label for="exampleInputRounded0">Section Name</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-globe-asia text-primary"></i></span>
</div>
<select class="form-control rounded-0 " wire:model="cr_classes_id" id="cr_classes_id" style="width: 100%;" tabindex="-1" aria-hidden="true">
#foreach ($classes as $class)
<option value="{{$class->id}}">{{$class->classes_name}}</option>
#endforeach
</select>
</div>
#error('cr_classes_sec_id') <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>

Add [title] to fillable property to allow mass assignment on [App\Profile]

I am trying to create edit profile, but when I click on edit profile button I'm getting below error:
Illuminate \ Database \ Eloquent \ MassAssignmentException Add [title]
to fillable property to allow mass assignment on [App\Profile]
show.blade.php :
<#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-4">
<img src="https://scontent-cdt1-1.cdninstagram.com/vp/dcca3b442819fc8b9b63f09b2ebde320/5DA9E3CB/t51.2885-19/s150x150/40101184_290824334847414_1758201800999043072_n.jpg?_nc_ht=scontent-cdt1-1.cdninstagram.com" class="rounded-circle">
</div>
<div class="col-8">
<div class="d-flex align-items-baseline">
<div class="h4 mr-3 pt-2">{{ $user->username }}</div>
<button class="btn btn-primary">S'abonner</button>
</div>
<div class="d-flex">
<div class="mr-3">{{ $user->posts->count() }} article(s) en vente
</div>
Modifier Profile
<div class="mt-3">
<div class="font-weight-bold">
{{ $user->profile->title }}
</div>
<div class="font-weight-bold">
{{ $user->profile->description }}
</div>
</div>
</div>
</div>
<div class="row mt-5">
#foreach ($user->posts as $post)
<div class="col-4">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
</div>
#endforeach
</div>
</div>
#endsection
ProfileController :
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function show(User $user)
{
return view('profile.show', compact('user'));
}
public function edit(User $user)
{
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$data = request()->validate([
'title' => 'required',
'description' => 'required'
]);
$user->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
edit.blade.php :
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Modifier profile</div>
<div class="card-body">
<form method="POST" action="{{ route('profile.update', ['user' => $user]) }}" enctype="multipart/form-data">
#csrf
#method('PATCH')
<div class="form-group">
<label for="title">Titre</label>
<div class="col-md-6">
<input id="title" type="text" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') ?? $user->profile->title }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label for="description">Description</label>
<div class="col-md-6">
<textarea id="description" type="text" class="form-control #error('description') is-invalid #enderror" name="description" autocomplete="description" autofocus>{{ old('description') ?? $user->profile->description }}</textarea>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input #error('image') is-invalid #enderror" id="validatedCustomFile" >
<label class="custom-file-label" for="validatedCustomFile">Choisir une image</label>
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Modifier profile
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarder = [];
public function user()
{
return $this->belongsTo('App\User');
}
}
What am I doing wrong here and how can I get rid of this error?
You have a spelling error, instead of $guarder add this in your model:
protected $guarded = [];
I won't advise using empty guarded but use $fillable instead.
In the same controller model, free access to database fields with
protected $guarded = [];
or
protected $fillable = [];

How to fix query in edit view?

i'm setting up a new project to perform multi language form but i'm stuck in edit form i don't know how to handle that
I created my controller and create view the only thing i need is edit view
so you can check my create view in bellow that work fine :
<div class="card-body text-center">
{!! Form::open(['route' => 'content.store', 'method' => 'Post']) !!}
<div class="card">
<div class="card-body">
<div class="form-group">
<label class="mx-4" for="my-input">{{ __('content/form.country_t') }}:</label>
<input id="my-input " type="text" name="country" placeholder="{{ __('content/form.country') }}">
<label class="mx-4" for="my-input">{{ __('content/form.city_t') }}:</label>
<input id="my-input" type="text" name="city" placeholder="{{ __('content/form.city') }}">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="card col-xs-12 p-0">
<nav>
<div class="nav nav-pills nav-fill card-header" id="nav-tab" role="tablist">
#foreach (config('translatable.locales') as $la=>$desc)
<a class="nav-item nav-link" id="nav-home-tab" data-toggle="tab" href="#{{ $la }}" role="tab" aria-controls="nav-home" aria-selected="true">{{ $desc }}</a> #endforeach
</div>
<div class="tab-content py-3 px-3 px-sm-0 card-body" id="nav-tabContent">
#foreach (config('translatable.locales') as $la=>$desc)
<div class="tab-pane fade px-4" id="{{ $la }}" role="tabpanel" aria-labelledby="nav-home-tab">
<div class="form-group">
<label for="my-input" class="">{{ __('content/form.title') }}</label>
<input id="my-input" class="form-control" type="text" name="translations[{{ $la }}][title]">
</div>
<div class="form-group">
<label for="my-input" class="">{{ __('content/form.body') }}</label>
<input id="my-input" class="form-control" type="text" name="translations[{{ $la }}][body]">
</div>
</div>
#endforeach
</div>
</nav>
</div>
<button type="submit" class="row col-12 mt-2 mx-auto btn btn-primary">{{ __('content/form.submit') }}</button>
</div>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
and this is my controller :
public function store(Request $request)
{
$contents = new Content;
// $contents->fill($request->all());
$this->fillRequest($request,$contents);
$contents->User()->associate(\Auth::user());
$contents->saveOrFail();
return redirect()->route('content.index')->with('success','با موفقیت ساخته شد');
}
private function fillRequest(Request $request, Content $model)
{
//fill model on fillable variables
$model->fill($request->only($model->getFillable()));
$model->saveOrFail();
foreach ($request->translations as $la => $desc) {
//if title field is null ignore the translations
// in case of there is a translation... delete it
if (!$desc["title"]) {
if ($model->hasTranslation($la)) {
$model->deleteTranslations($la);
}
continue;
}
//create new translation if not exists
$model->translateOrNew($la)->fill($desc);
$model->saveOrFail();
}
return $model;
}
I need to know how can i create edit view exactly same as my create view above

Laravel pass id from blade template to store controller

I am trying to pass id to store controller as I need to save business_id that is being retrieved from another table. However I get:
Missing argument 2 for App\Http\Controllers\EventController::store()
Here's my view:
#extends('master') #section('title', 'Live Oldham')
#section('content')
<div class="col-lg-y col-lg-offset-3">
<ul class="list-group-list">
#foreach ($business->businesses as $business)
<li class="list-group-item">
<a target="_blank" href="{{ url('business/' . $business->id) }}"> {{($business->name) }}</a>
</li>
#endforeach
</ul>
</div>
#endsection
Controller:
class EventController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$id = Auth::id();
$business = User::where('id', $id)
->with('businesses')
->first();
return view('events.viewEvent', compact('business'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
return view('events.addEvent')
->with('Business', Business::find($id));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request, $id)
{
$event = new Event;
$event->startdate = $request->input('startdate');
$event->enddate = $request->input('enddate');
$event->title = $request->input('title');
$event->frequency = $request->input('frequency');
$event->description = $request->input('description');
$event->business_id = $id;
$event->save();
}
form:
#extends('master') #section('title', 'Live Oldham')
#section('content')
<div class="container">
<!-- Alert Messages -->
#if (session('message'))
#if (session('message')=="success")
<div class="alert alert-success">
Event Created
</div>
#else
<div class="alert alert-danger">
There has been a fatal error! Apologies, we are working to fix it!
</div>
#endif
#endif
<!-- JQuery UI init -->
<script>
$( function() {
$( document ).tooltip();
} );
</script>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Create Event</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ action('EventController#store') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
<div style="display:none;" class="title_message form-control alert-warning"></div>
<label for="title" class="col-md-4 control-label">Event Title</label>
<div class="col-md-6">
<input id="title" type="text" class="form-control" placeholder="Event title"
title="What is the event title?" name="title" value="{{ old('title') }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('frequency') ? ' has-error' : '' }}">
<div style="display:none ;" class="frequency_message form-control alert-warning"></div>
<label id="frequency2" for="frequency" class="col-md-4 control-label">Frequency</label>
<div class="col-md-6">
<select class="form-control" name="frequency" id="frequency">
<option selected disabled>Choose event frequency...</option>
<option value="One">One-time Event</option>
<option value="Daily">Daily</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Yearly">Yearly</option>
</select>
#if ($errors->has('frequency'))
<span class="help-block">
<strong>{{ $errors->first('frequency') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('startdate') ? ' has-error' : '' }}">
<div style="display:none ;" class="startdate_message form-control alert-warning"></div>
<label id="startdate2" for="startdate" class="col-md-4 control-label">Event Start Date</label>
<div class="col-md-6">
<input id="startdate" type="date" class="form-control" placeholder="Start Date"
title="When does the event start?" name="startdate" value="{{ old('startdate') }}">
#if ($errors->has('startdate'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('enddate') ? ' has-error' : '' }}">
<div style="display:none ;" class="enddate_message form-control alert-warning"></div>
<label id="address3" for="enddate" class="col-md-4 control-label">Event End Date</label>
<div class="col-md-6">
<input id="enddate" type="date" class="form-control" placeholder="End Date"
title="When does the event end?" name="enddate" value="{{ old('enddate') }}">
#if ($errors->has('enddate'))
<span class="help-block">
<strong>{{ $errors->first('enddate') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<div style="display:none ;" class="description_message form-control alert-warning"></div>
<label id="description2" for="description" class="col-md-4 control-label">Event Description</label>
<div class="col-md-6">
<textarea id="description" type="text" class="form-control" placeholder="Event description"
title="Here goes event description" name="description" value="{{ old('description') }}">
</textarea>
#if ($errors->has('description'))
<span class="help-block">
<strong>{{ $errors->first('description') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" id="submit" class="btn btn-success">
Add Event
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
You can pass the id to the form action
<form method="POST" action="{{ action('EventController#store', $business->id) }}" class="form-horizontal" role="form">
...
</form>

Resources