Pass two different array values to controller to detach them with Laravel - laravel

I want to detach some data from my database. I have a table on my view that shows some data with checkboxes. Every tag has it own checkbox. I want to pass all the tag_id's from the tags I've checked. To detach them I also need the domain_id. I've tried some things out but couldn't figure out how I can pass all the domain_id with the tag_id's I've marked.
<tbody>
{!! Form::open(['action' => 'DomainController#detach', 'method' => 'post']) !!}
#foreach($domains as $domain)
<tr>
<td>{{ $domain->name }}</td>
<td>{{ $domain->tld }}</td>
<td id="hello">
#foreach($domain->tags as $tag)
{{ $tag->name }},<br>
#endforeach
</td>
<td>
<input name="domain_id[]" type="hidden" value="{{ $domain->id }}">
#foreach($domain->tags as $tag)
<input type="checkbox" name="tag_id[]" value="{{$tag->id}}"><br>
#endforeach
</td>
</tr>
#endforeach
</tbody>
<div class="btn-group">
<button type="button" dropdown-toggle" data-toggle="dropdown" >Action<span class="caret"></span></button>
<ul class="dropdown-menu" role="menu">
<li><a>
<button>Send</button>
</a></li>
</ul>
</div>
{!! Form::close() !!}
Now I want to get every tag_id and the domain_id of the tags if I mark them with a tick.
As a output I need something like this:
[0] = "domain_id" : 5,
"tag_id" : [0] => 1,
[1] => 2,
[2] => 3,
[1] = "domain_id" : 6,
"tag_id" : [0] => 10,
[1] => 11,
[2] => 12,
currently.. this is what I get
{"domain_id":["5","6","10","13","15","18","19","22","23","24","28"],"tag_id":["273","286","285"]}
I've just marked tags from the domain with id 5, but it gave me all domain_id's and I couln't figure out why..

A form won't output values in the way you want as it cannot generate subarrays, so as mentioned in my comment, you will have to improvise. Your bottom line is you need to associate the domain_id with each tag_id in some way so you can database it, or whatever.
I suggest creating your tag checkbox like this in your view
<td>
#foreach($domain->tags as $tag)
<input type="checkbox" name="tag_id[]" value="{{$domain->id}}:{{$tag->id}}"><br>
#endforeach
</td>
when submitted, it should format the tag_id in the request object like this
[0] = "tag_id" : [0] => 5:1,
[1] => 5:2,
[2] => 5:3,
[3] => 6:10,
[4] => 6:11,
[5] => 6:12,
Now you can loop over the tag_id array and separate the domain_id and tag_id fields to do whatever you need to (your example didn't say what you wanted to to do with them)
foreach ($request->tag_id as $item) {
$arrItem = explode(':', $item);
// $arrItem[0] is your domain_id for the tag_id $arrItem[1]
// other logic here
}

Related

i want to assign the post to some users and determine if this post is featured for him or not using laravel 8

Hi there the following is working well for me, this snippet of code will add new post and assign it to some users.
what i need is to specify that the assigned post is featured or not for a user.
TABLES
posts
id - integer
title - string
users
id - integer
name - string
post_user
id - integer
post_id - integer
user_id - integer
assigned - Char[Y/N]
VIEW
<form>
<input type="text" class="form-control" name="title" value="">
#foreach ($users as $user)
<tr >
<td>{{ $user->name }}</td>
<td>
<div class="checkbox checkbox-inverse">
<input type="checkbox" name="users[]" value="{{ $user->id }}">
</div>
</td>
<td><input type="checkbox" value="" name="featured[]"> </td>
</tr>
#endforeach
</form>
CONTROLLER
$new_post = [
"title" => $request['title'],
];
$assignees = $request['users'];
$post = Post::create($new_post);
$post->users()->attach($assignees);
What i need is to merge the assignees array with featured array to send the big array to the attach or sync method as follows
$post = Post::create($new_post);
<!-- $post->users()->attach($assignees); -->
$post->users()->sync([1 => ['featured' => 'Y'], 2 => ['featured' => 'N'], 3 => ['featured' => 'N']]);
I want to add the value of "featued" field in "post_user" table as follows
--------------------------------
post_id | user_id | featured
--------------------------------
1 | 1 | Y
1 | 2 | N
1 | 3 | N
--------------------------------
The second part is
How to display the previously checked in "users" and "featured" checkboxes.
VIEW:
#foreach ($users as $user)
<input type="checkbox" name="users[{{ $user->id }}]" value="{{ $user->id }}">
<input type="checkbox" name="featured[{{ $user->id }}]" value="{{ $user->id }}">
#endforeach
If I understand correctly then what you need is:
VIEW:
#foreach ($users as $user)
<input type="checkbox" name="users[{{ $user->id }}]" value="{{ $user->id }}">
<input type="checkbox" name="featured[{{ $user->id }}]" value="{{ $user->id }}">
#endforeach
CONTROLLER:
$inserts = [];
foreach ($request->users as $userId) {
$inserts[] = [
'post_id' => $request->post_id,
'user_id' => $userId,
'featured' => isset($request->featured[$userId])
]
}
Explanation:
Request will send data like:
"users" => [
1 => 1,
2 => 1,
3 => 1
]
"featured" => [
1 => 1
]
where index is $user->id. This way you can tell if checkbox for specific user was ticked

Storing data from 1 table to another tables in 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>

Trying to get property of non-object - laravel 5.4

I am using Laravel eloquent relationship, when i use
{{$subject->cat}}
i receive a json response like below
{"id":13,"name":"Fsc","created_at":"2017-10-23 00:00:00","updated_at":"2017-10-23 00:00:00"}
as i have 2nd object "name" here i tried
{{$subject->cat->name}}
but got error
Trying to get property of non-object
while i am using same approach for other table and copied same method here but getting error.
See my Blade file code, i am calling object inside foreach loop
#foreach ($subjects as $subject)
<tr>
<td width="8%">{{$subject->id}}</td>
<td width="22%">{{$subject->subject}} </td>
<td width="22%">{{$subject->cat->name}}</td>
<!-- <a class="btn btn-success btn-sm" href="{{route('subjects.show', $subject->id)}}"><i class="fa fa-eye"></i></a> | -->
<i class="fa fa-pencil"></i> |
{!! Form::open(['route' => ['subjects.destroy', $subject->id], 'method' => 'DELETE', 'class' => 'delete-form']) !!}
{{ Form::button('<i class="fa fa-times" aria-hidden="true"></i>', ['class' => 'btn btn-danger btn-sm pull-left', 'type' => 'submit']) }}
{!! Form::close() !!}
</td>
</tr>
#endforeach
First Use json_decode($json);
Takes a JSON encoded string and converts it into a PHP variable.
Then
Use {{$subject->cat}}
Just use json_decode like:
$var = json_decode($subject, true);
Then you can use:
{{$subject->cat->name}}
See more here!
Hope this helps you!
You need to decode your json and then use like this:
$result = json_decode ($subject->cat);
echo $result->name;
Use your variable name in place of $result
For insight here is pastebin demo
Try this
$cat = json_decode($subject->cat); // returns object
{{ $cat['name'] }}
or
$cat = json_decode($subject->cat, true); // returns array
{{ $cat['name'] }}

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

pass multiple id's from checkboxes to my controller with Laravel

I have a products table in my database. I'm getting the name of the products from my DB and print theire names in a bootstrap table on my blade. Currently there is a edit button on every row line. If I'm pressing the button I'm passing the ID of this product to my controller edit function. Now I want to add checkboxes for every product in this table and if I set for example two ticks ( so two different products ) I want to pass both ID's at the same time to my controller.
Looks like this:
{!! Form::open(['action' => 'ProductController#tags']) !!}
#foreach($products as $product)
<tr>
<td>
{!! Form::checkbox('check', $product->id) !!}
</td>
<td>
{{ $product->name }}
</td>
<td>
#foreach($product->tags as $tag)
{{$tag->name}},
#endforeach
</td>
<td>
{{ $product->created_at->format('d.m.y') }}
</td>
<td>
<a href="{{ action('ProductController#edit', ['id' => $product->id]) }}">
<button class="btn btn-default" style="float: right;">Edit</button>
</a>
</td>
</tr>
#endforeach
{!! Form::close() !!}
As you see, I've set the product id as a seccond parameter for every checkbox, but this haven't worked well of course. Can someone tell me a way how I can give every checkbox the ID of the product and pass their ID's to my controller at the same time, if they are marked with a tick ?
Thanks for taking the time :)
Have you tried accepting multiple checkbox values as array by adding '[]' to the checkbox name?
{!! Form::checkbox('check[]', $product->id) !!}
I believe that this Form facade was from Laravel 4, i never used it, but i think that this will generate an input, with checkbox type, a name of 'check' and the id as the value, right?
Did you tried to set the name to 'check[]'? This way all checked ids will be in one array 'check' in your request. In Laravel 5 at least, you can try to dump the request['check'] and this should return an array os checked ids

Resources