Storing data from 1 table to another tables in laravel - laravel

I am pretty new to Laravel. I have a Table named Leads and Three other tables named Contacts, Companies, and Opportunities.
What I am trying to do is extract the data from the Leads table to these 3 other tables. Something like this : https://imgur.com/EZGqNQH . The way I want to achieve this is kind of like this: When the user clicked the 'Convert Lead' button, a modal will appear like this: https://imgur.com/EDgVR7U and if the user ticked the checkbox button for the Convert to Opportunity, an extra field will appear for the user to fill in: https://imgur.com/mrypfCC
I have made the necessary files for the process (maybe)
LeadController:
{
return view('leads.create')
->withUsers($this->users->getAllUsersWithDepartments())
->withClients($this->clients->listAllClients())
->withIndustries($this->clients->listAllIndustries())
->withLeadSource($this->leads->listAllSources());
}
public function convertLeads($id)
{
$lead = Lead::findOrFail($id);
$company = new Companies;
$opportunity = new Opportunity;
$contact = new Contact;
$company->lead_id = $lead->id;
$company->name = $lead->company_name;
$company->phone = $lead->company_phone;
$company->email = $lead->company_mail;
$company->address1 = $lead->company_address1;
$company->address2 = $lead->company_address2;
$company->state = $lead->company_state;
$company->zipcode = $lead->company_zipcode;
$company->city = $lead->company_city;
$company->country = $lead->company_country;
$company->save();
$contact->name = $lead->lead_name;
$contact->job_title = $lead->position;
$contact->email = $lead->mail;
$contact->primary_number = $lead->lead_phone;
$contact->description = $lead->description;
$contact->client_id = $lead->client_id;
$contact->save();
Session()->flash('flash_message', 'Lead successfully converted!');
return view('leads.show');
}
/**
* Store a newly created resource in storage.
*
* #param StoreLeadRequest|Request $request
*
* #return \Illuminate\Http\Response
*/
public function store(StoreLeadRequest $request)
{
$getInsertedId = $this->leads->create($request);
Session()->flash('flash_message', 'Lead is created');
return redirect()->route('leads.show', $getInsertedId);
}
public function show($id)
{
return view('leads.show')
->withLead($this->leads->find($id))
->withUsers($this->users->getAllUsersWithDepartments())
->withCompanyname($this->settings->getCompanyName());
}
Route:
Route::get('/data', 'LeadsController#anyData')->name('leads.data');
Route::get('/create', 'LeadsController#create')->name('leads.create');
Route::get('/show/{id}', 'LeadsController#show')->name('leads.show');
Route::get('convertLeads/{id}', 'LeadsController#convertLeads')->name('leads.convertLeads');
Route::get('/my', 'LeadsController#my')->name('leads.my');
Route::get('/mydata', 'LeadsController#myData')->name('leads.mydata');
Route::patch('/updateassign/{id}', 'LeadsController#updateAssign');
Route::patch('/updatestatus/{id}', 'LeadsController#updateStatus');
Route::patch('/updatefollowup/{id}', 'LeadsController#updateFollowup')->name('leads.followup');
});
Route::resource('leads', 'LeadsController');
Route::post('/comments/{type}/{id}', 'CommentController#store');
Views:
<div>
<table width="100%">
<tr>
<th></th>
</tr>
<tr>
{!!Form::open(array('route' => array('leads.convertLeads', $lead->id)))!!}
<td><li>Convert to Contact</li></td>
</tr>
<tr>
<td><li>Convert to Company</li></td>
</tr>
<tr>
<td><label for="chkOpportunity">
<input type="checkbox" id="chkOpportunity" />
Convert to Opportunity
</label>
<div id="dvOpportunity" style="display: none">
{!! Form::label('name', __('Lead Name'), ['class' => 'control-label']) !!}
<div class="form-group" style="padding:5px">
{!! Form::label('country', __('Value'), ['class' => 'control-label']) !!}
{!! Form::text('company_country', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group" style="padding:5px">
{!! Form::label('country', __('Type'), ['class' => 'control-label']) !!}
{!! Form::text('company_country', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group" style="padding:5px">
{!! Form::label('country', __('Stage'), ['class' => 'control-label']) !!}
{!! Form::text('company_country', null, ['class' => 'form-control']) !!}
{!! Form::close() !!}
</div>
</div>
</td>
</tr>
</table>
<div class="modal-footer" style="margin:-13px; margin-top:4px;">
<div align="right">
{!! Form::submit(__('Convert Lead'), ['class' => 'btn btn-primary']) !!}
</div>
</div>
</div>
</div>
I am not sure which part of these are wrong, I think it is the form? When I click the Convert Lead button (to submit) nothing happens. Can anyone help? Thanks in advance.

try to place the form above the table tag
like this
<div>{!!Form::open(array('route' => array('leads.convertLeads', $lead->id)))!!}
<table width="100%">
<tr>
<th></th>
</tr>
<tr>
<td><li>Convert to Contact</li></td>

Related

QueryException error while updating data

Into database not update data, i can't understand my problem, error is below
Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column '_method' in 'field list' (SQL: update trades set _method = PATCH, _token = AcbGEbEyNxX3e2RzRR2cb1SW6NDvkJuDqFevl0Mr, exchange_id = 1, market_id = 1, symbol_id = 45, is_action = 0, tradedate = , rate = 5000, note = hhhhhhhhh, updated_at = 2018-07-21 13:06:13 where trades.user_id = 33 and trades.user_id is not null and trades.deleted_at is null)
This is my controller
public function edit($id)
{
$trade = Trade::findOrFail($id);
$exchanges = Exchange::pluck('exchange','id')->all();
$markets = Market::pluck('market','id')->all();
$symbols = Symbol::pluck('symbol','id')->all();
$reasons = Reason::pluck('reason','id')->all();
return view('member.add-single-trade.edit', compact('trade','reasons', 'exchanges', 'markets', 'symbols'));
}
public function update(Request $request, $id)
{
$input = $request->all();
$tradeID= Auth::user()->trade($id)->update($input);
$reasons=$request->input('reason');
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
$data = array(
'reason_id' =>$reasons,
'trade_id' => $tradeID->id,
);
$test['trade_id']= $tradeID->id;
if($data > 0) {
foreach ($data as $datum) {
$tradeID->tradereason()->update(new TradeReason($datum));
}
}
}
This is my edit.blade.php file
{!! Form::model($trade,['method'=>'PATCH', 'action'=> ['trades\AddSingleTradeController#update',$trade->id]]) !!}
<div class="col-sm-10">
<div class="form-group col-sm-5">
{!! Form::label('exchange_id', 'Exchanges:') !!}
{!! Form::select('exchange_id', [''=>'Choose Options'] + $exchanges , null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] + $markets, null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('symbol_id', 'Symbols:') !!}
{!! Form::select('symbol_id', [''=>'Choose Options']+ $symbals , null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{{ Form::radio('is_action', 1) }} Buy
{{ Form::radio('is_action', 0) }} Sell
</div>
<div class="form-group col-lg-5">
{!! Form::label('tradedate', 'Traded date:') !!}
{!! Form::date('tradedate', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-lg-5">
{!! Form::label('rate', 'Traded Rate:') !!}
{!! Form::text('rate', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('reason', 'Choose Reasons:') !!}
{{Form::select('reason',$reasons,null, array('id'=>'reasons','multiple'=>'multiple','name'=>'reason[]',"class"=>"js-example-basic-multiple form-control", 'data-width'=>'60%', 'data-live-search'=>'true','onchange' => 'all_function()'))}}
</div>
<div class="form-group col-lg-10">
{!! Form::label('note', 'Note:') !!}
{!! Form::textarea('note', null, ['class'=>'form-control', 'rows' => 2, 'cols' => 40])!!}
</div>
<div class="form-group col-lg-4">
{!! Form::submit('Save', ['class'=>'btn btn-success btn-lg']) !!}
</div>
{!! Form::close() !!}
<div class="form-group col-lg-4">
{!! Form::open(['method'=>'DELETE', 'action'=> ['trades\AddSingleTradeController#destroy', $trade->id]]) !!}
<div class="form-group">
{!! Form::submit('Delete', ['class'=>'btn btn-danger btn-lg']) !!}
</div>
</div>
{!! Form::close() !!}
This is my create.blade.php file
<td>{{$trade->stoploss}}</td>
You haven't included your model code (probably you are using $guarded = [];) but probably instead of
$input = $request->all();
you should use:
$input = $request->except('_method');
This is because additional _method field is added to form to pass HTTP verb method when using Form::model and obviously you don't have _method field in your table
EDIT
In case you have more fields you can include more fields to ignore for example:
$input = $request->except('_method', '_token');
or you can only use get fields you really want to get for example:
$input = $request->only('exchange_id', 'market_id');
(Of course you should add more fields to above - this is only example)
You can use $fillable property of the model to tell ORM which attributes (columns) can be mass assignable. Any other fields passed via update and create methods will be discarded. check at Laravel docs

Laravel non-object

I create simple Laravel project. In blog view I have pages index (where is first page of last 5 blogs), Edit, Show, and Create. Now, all working fine if I create new Blog from database (edit/delete and show/read). But I can't create new blog from site. Do you see problem?
BlogControllor
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('blog.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'naslov'=>'Required',
'slug'=>'Required|alpha_dash|min:5|max:255|unique:blogs,slug',
'opis'=>'Required',
'tekst'=>'Required',
'upload_slike' => 'sometimes|image'
]);
$blog = new Blog;
$blog->naslov = $request->naslov;
$blog->slug = $request->slug;
$blog->opis = $request->opis;
$blog->tekst = $request->tekst;
//Sacuvaj novu sliku za blog post
if ($request->hasFile('upload_slike')) {
$image = $request->file('upload_slike');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('slike/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$blog->image = $filename;
}
$blog->save();
return redirect('blog');
}
Route
Route::resource('blog', 'BlogController');
Button on index page for create new Blog
Dodaj novu vest
Page create.blade.php
#extends('layouts.bez-sidebar')
<script src="//cdn.tinymce.com/4/tinymce.min.js"></script>
<script>
tinymce.init({
selector: 'textarea',
plugins: 'link image',
menubar: false
});
</script>
#section('content')
{!! Form::open(['url'=>'blog','class'=>'form-horizontal', 'files' => true]) !!}
<div class="">
<div class="form-group">
{!! Form::label('naslov', 'Naslov', ['class'=>'control-label col-md-2']) !!}
<div class="col-md-10">
{!! Form::text('naslov', null, ['class'=>'form-control', 'placeholder'=>'Unesi naslov']) !!}
{!! $errors->has('naslov')?$errors->first('naslov'):'' !!}
</div>
<div class="form-group">
{!! Form::label('slug', 'Alias:', ['class'=>'control-label col-md-2']) !!}
<div class="col-md-10">
{!! Form::text('slug', null, ['class'=>'form-control', 'required' => '', 'minlenght' => '5', 'maxlenght' => '255', 'placeholder'=>'Unesi alias link za post']) !!}
{!! $errors->has('slug')?$errors->first('slug'):'' !!}
</div>
</div>
<div class="form-group">
{!! Form::label('opis', 'Opis', ['class'=>'control-label col-md-2']) !!}
<div class="col-md-10">
{!! Form::text('opis', null, ['class'=>'form-control', 'placeholder'=>'Ovde upisite kratak opis vesti']) !!}
{!! $errors->has('opis')?$errors->first('opis'):'' !!}
</div>
</div>
<div class="form-group">
{!! Form::label('tekst', 'Tekst', ['class'=>'control-label col-md-2']) !!}
<div class="col-md-10">
{!! Form::textarea('tekst', null, ['class'=>'form-control', 'placeholder'=>'Ovde upisite celu vest']) !!}
{!! $errors->has('tekst')?$errors->first('tekst'):'' !!}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
{{ Form::label('upload_slike', 'Ubacite sliku:')}}
{{ Form::file('upload_slike') }}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
{!! Form::submit('Sačuvaj', ['class'=>'btn btn-primary']) !!}
</div>
</div>
</div>
{!! Form::close() !!}
#stop
And this error
The error in the image shows that the error is occurring when you're opening a form tag to delete. Check line 5 in the screenshot you took.
Are you including a delete function on your create screen; perhaps in the extended view layouts.bez-sidebar? If you are then that could be why $blog->id is causing a trying to get property of non object error.

Laravel a form isn't reset after successful submit

This is my controller:
class GuestbookController extends Controller
{
public function viewAll(Request $request)
{
if ($request->method() === 'POST') {
$this->validate($request, [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
$message = new Message();
$message->username = $request->get('username');
$message->email = $request->get('email');
$message->homepage = $request->get('homepage');
$message->text = strip_tags($request->get('text'));
$message->ip = $request->ip();
$message->browser = get_browser($request->header('User-Agent'))->browser;
$message->save();
}
$messages = Message::sortable(['created_at' => 'desc'])->paginate(25);
return view('Guestbook.viewAll', [
'newMessage' => new Message(),
'messages' => $messages
]);
}
}
I am using this plugin. viewAll handles both GET and POST requests, but the problem is that the form isn't reset when I successfully submit data keeping all the previous input values.
I've checked what the server sends and it seems like it sends inputs with last values in them. I've no idea what to do, please help!
View:
#extends('base')
#section('title', 'Guestbook')
#section('baseContent')
{!! BootForm::open(['model' => $newMessage]) !!}
{!! BootForm::text('username') !!}
{!! BootForm::email('email') !!}
{!! BootForm::text('homepage') !!}
{!! BootForm::textarea('text') !!}
{!! captcha_img() !!}
{!! BootForm::text('captcha') !!}
{!! BootForm::submit('Send') !!}
{!! BootForm::close() !!}
#if (count($messages) > 0)
<table class="table table-bordered">
<tr>
<td>#sortablelink('username', 'Username')</td>
<td>#sortablelink('email', 'Email')</td>
<td>Homepage</td>
<td>#sortablelink('created_at', 'Data added')</td>
<td>Message</td>
</tr>
#foreach ($messages as $message)
<tr>
<td>{{ $message->username }}</td>
<td>{{ $message->email }}</td>
<td>{{ $message->homepage }}</td>
<td>{{ $message->created_at }}</td>
<td>{{ $message->message }}</td>
</tr>
#endforeach
</table>
#else
There is nothing to display here.
#endif
{!! $messages->appends(\Request::except('page'))->render() !!}
#endsection
See all code here.
BootForm is compiled like this
<div class="form-group">
<label for="username" class="control-label col-md-2">Username</label>
<div class="col-md-10">
<input type="text" value={{old('username')}} name="username" class="form-control">
</div>
The old('params') is a helper method which keeps the previous inputs in session. And secondly, you have model associated with it.
I hope this helps

storing data with name of author - laravel 5.2

I have hasMany relation to my model user and reports.
I want to set author name for the reports. (Like a blog-post author)
my model User:
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
model Report
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
and my controller:
public function create()
{
$category = Category::lists('title','id');
return view('dash.reports.create')->with('category', $category);
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
Report::create($request->all());
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
I'm able to set in in phpmyadmin, but how can i set it with my controller?
edit: my view:
{!! Form::open(['url' => '/dash/reports', 'class' => 'form-horizontal']) !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('title', 'Servizio', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('title', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('date', 'Data lavorativa', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-2">
{!! Form::selectRange('day', 1, 31, null, ['class' => 'form-control']) !!}
{!! $errors->first('day', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::selectMonth('month', null, ['class' => 'form-control']) !!}
{!! $errors->first('month', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::select('year', array('2016' => '2016', '2015' => '2015'), null, ['class' => 'form-control']) !!}
{!! $errors->first('year', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('category_id') ? 'has-error' : ''}}">
{!! Form::label('category_id', 'Cliente', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::select('category_id', $category, null, ['class' => 'form-control'] ) !!}
{!! $errors->first('category_id', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
{!! Form::submit('Create', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
Very easy. Replace Report::create... with this.
$user = Auth::user();
$report = new Report($request->all());
$report->author()->associate($user);
$report->save();
Make sure you use Auth; up at the top.
This uses the Auth object to get the current user,
Builds a new Report using the $request data without saving,
Tells the report we're associating $user as the author for the model,
Saves the report with the authorship information.
solution:
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$report->save();
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}

Update data with Laravel Collective forms

I have an edit form with Laravel Collective but when clicking the button, the data do not update. Below are my codes.
Form:
{!! Form::model($post, ['route' => ['/post/update/', $post->id]]) !!}
{{ method_field('PATCH') }}
<div class="form-group">
<div class="row">
<div class="col-lg-6">
{!! Form::label('title', 'Title') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="col-lg-6">
{!! Form::label('category_id', 'Category') !!}
{!! Form::select('category_id', $categories, null, ['class' => 'form-control']) !!}
</div>
</div>
</div>
<div class="form-group">
{!! Form::label('content', 'Content') !!}
{!! Form::textarea('content', null, ['class' => 'form-control', 'rows' => 10]) !!}
</div>
<hr/>
<div class="form-group">
{!! Form::submit('Update', ['class' => 'btn btn-success pull-right']) !!}
</div>
{!! Form::close() !!}
Controller:
public function edit($id)
{
return \View::make('admin/post/edit')->with([
'post' => \DB::table('posts')->find($id),
'categories' => \App\Category::lists('category', 'id')
]);
}
public function update(Request $request, Post $post)
{
$post->update($request->all());
return \Redirect::to('/admin/posts');
}
Routes:
Route::get('/admin/post/edit/{id}', 'Admin\PostController#edit');
Route::patch('/post/update/', [
'as' => '/post/update/',
'uses' => 'Admin\PostController#update'
]);
It's a bit different from the Laracast, and it's confusing me. Framework is new to me and the lack of code to do something is confusing.
I solved it. Mass Assignment. explains what to do if using update or create
So, the update method is:
public function update(Request $request, Post $post)
{
$post->title = $request->title;
$post->category_id = $request->category_id;
$post->content = $request->content;
$post->save();
return \Redirect::to('/admin/posts');
}

Resources