laravel fetch dropdown query data value from model - php

I have a form and there is a dropdown for this. In a view page i want to fetch the data from the model.
model function
public static function allVenueClientList() {
/* Also if possible i want to add ($users = DB::table('clients') join query on this query which is already working for me.
return Client::where('type', static::CLIENT_TYPES['Venue'])
->orWhere('type', static::CLIENT_TYPES['Both'])
->pluck('name', 'id')->all();
*/
$users = DB::table('clients')
->join('users', 'clients.id', '=', 'users.user_id')
->where('users.status', '=', 'Active')
->where('users.id', '!=', '1')
->select('clients.name', 'clients.id')
->get();
return $users;
}
My view page code:
<div class="form-group{{ $errors->has('client_id') ? ' has-error' : '' }}">
{{Form::label('client_id', trans('admin.venue.fields.client_id'),['class' => 'col-md-4 control-label'])}}
<div class="col-md-6">
{{Form::select('client_id',[0 => trans('admin.venue.select.client_id')] + \App\Client::allVenueClientList(), old('client_id', isset($venue) ? $venue->client->id : 0), ['class' => 'form-control select'])}}
#if ($errors->has('client_id'))
<span class="help-block">
<strong>{{ $errors->first('client_id') }}</strong>
</span>
#endif
</div>
How can i get $users data on this dropdown also if it is possible to the first query change as per second query ?

Inside your controller function which defines the above mentioned function of model pass the data by using compact data...
like this $compactdata= your query result.
return view('your view', compact('compactdata'))
and then loop through result in view if it is collection other wise just show result in view withoutloop as you did it above.
Please checkout the syntax error.I am not sure about syntax.

I will admit not entirely understanding the question, but my response is too large for a comment.
It sound like you are going to want to offload some of this into scripts.
script:
function usersearch(client_id)
{
$.post('usersearch', {
_token: $('meta[name=csrf-token]').attr('content'),
client_id: client_id,
}
)
.done(function(data) {
document.getElementById('myotherdropdown').innerHTML = data;
})
.fail(function() {
alert( "I did an oops" );
});
}
Then the current select gets an event
<select name="client_id" onchange=usersearch(this.value)>
in web.php
Route::post('/usersearch', 'JavaController#usersearch');
in JavaController
public function usersearch()
{
$sku = Request::get('client_id');
$options = '';
$result = whatever you need to do here;
foreach($result as $row) {
$options .= "<option value=\"".$row->user_id."\">".$row->user_name."</option>";
}
return $options;
}
Obviously given your setup, things won't be exactly as here, but the idea itself seems to be what you are going for.
If you really want, you can even throw the token around in the script as well for a little extra security.
$.post('usersearch', {
_token: $('meta[name=csrf-token]').attr('content'),
client_id: client_id,
}
Hopefully this is what you were asking for.

Related

How to implement DataTable with parameter 'id' in Laravel (DataTables)?

I am trying to pass the ID value from the blade file into ajax so it the data table will be routed and will call the ProductActivities function in ProductController.
Here's my snippet code for show() function in ProductController:
public function show($id)
{
$product = Product::find($id);
$data = Product::with(['user_modify'], 'id', $product->user_modified)
->where('product_id', '=', $id)->first();
$category = Category::select('category_name')
->where('category_id', '=', $data->product_type)
->pluck('category_name')
->first();
if($data->count() > 0){
return view('product.view', compact('data', 'category'));
}else{
Toastr::error('Product cannot be retrieved.', 'Error');
return view('product.index');
}
}
And here's the snippet code of JavaScript for the DataTable initialization in view.blade.php file:
#push('js')
<script>
$(function () {
$("#prod_log_tbl").DataTable({
responsive:true,
stateSave:false,
scrollY:true,
autoWidth: false,
ajax: {{ url('product/activities', [Request::segment(3)]) }},
order:[0, 'desc'],
searchable: false,
sortable:false,
fixedColumns: true
});
});
</script>
#endpush
line of code for route in web.php:
Route::get('product/activities/{id}', 'Master\ProductController#ProductActivities')->name('product/activities/{id}');
snippet code for the ProductActivities() function in ProductController:
public function ProductActivities($id)
{
$dataAct = Activity::all()->where('subject_id', '=', $id);
return Datatables::of($dataAct)->make(true);
}
And here's the result of my current progress:
In the screenshot of result the URL that ajax shows has additional values after the ID which I think causes of the DataTable error.
I don't know How I am getting this error? How can I implement the passing of ID from the view blade file through DataTable ajax into the ProductController?
P.S. I use Yajra/DataTable package for Laravel.
I think you do not need php echo in you Ajax url, route helper syntax is
{{ route('routeName', ['id' => 1]) }}
you need route name and parameter, another way is using url helper
{{ url('product/activities/', [Request::segment(3)]) }}
Beside this if you want to use model refer documentation, using first() will give you only one object, you need a collection, better considering get().

hide confidential data for multiple users

I have an user named eric which has like user role Former.
I would like the user Eric sees only his confidential information but not those of others.
Would you have any idea how I could make this?
Thank you for your help.
Edit Controller Former
public function index(Request $req)
{
if ($req->search == "") {
$formers = Former::paginate(5);
$formerIdsDown = Cours::where('date_seance', "<=" , Carbon::now())->pluck('fk_former')->toArray();
return view('admin.formers.index', compact('formers', 'formerIdsDown'));
} else {
$validated = $req->validate([
'search' => 'alpha',
]);
$formers = Former::where('nom', 'LIKE', '%' . $validated['search'] . '%')->paginate(5);
$formers->appends($req->only('search'));
$bikeIdsDown = Cours::where('date_seance', "<=" , Carbon::now())->pluck('fk_former')->toArray();
return view('admin.formers.index', compact('formers', 'formerIdsDown'));
}
$user = User::when($has_role, function ($query) {
return $query->where('id', auth()->id());
})
->get();
}
You could handle this in two ways.
Limiting the data from the server
This should be your approach. Here you could add a condition in your query to know if the user has the restricted role in order to limit the data:
# InSomeController.php
$has_role = auth()->user()->hasRole('former'); // checking if the user has the role
$user = User
::when($has_role, function ($query) {
return $query->where('a_column', 'a_value'); // The limitation you want to apply
})
->get(); // executing the query
Limiting in the view
In case you are using blade templating engine.. you can make use of some Blade directives:
# in_some_view.blade.php
#if (auth()->user()->hasRole('former'))
/** Your limited data goes here.. */
#else
/** The default data goes here.. */
#endif
Obs: In both cases I used the hasRole('role') method, replace this with the logic to validate if the user has a given role.

How to add an alert on Laravel 5?

I have a function where:
After I click the link named "hapus", the related data will be deleted and I want to have a popup alert to show that the data has been deleted.
*sorry for my bad english
*hapus technically means destroy
this the code:
public function hapus(Request $request, $id)
{
DB::table('kelompok')
->where('id', $id)
->delete();
return redirect()->back();
}
Use with() in your controller
function hapus(Request $request, $id)
{
DB::table('kelompok')
->where('id', $id)
->delete();
return redirect()->back()->with('alert', 'Deleted!');
}
In your blade template, retrieve the session after being redirected from controller:
#if (session('alert'))
<div class="alert alert-success">
{{ session('alert') }}
</div>
#endif
Extending #pbwned's answer,
you can also use javascript alert box in your blade view to display the flash session/message.
For example:
<script>
var msg = '{{Session::get('alert')}}';
var exist = '{{Session::has('alert')}}';
if(exist){
alert(msg);
}
</script>
Hope it helps =)

How to pass variable from foreach to view?

I'm trying to pass a variable from foreach to my view. So I can access this using in my select form. Because I have two tables M:M relationship between departments and user. I need to get all the department_name where the user_id belong. For me able to send a data via department_name Here what I did please take a look.
DB Diagram:
department_user
As you can see here user_id is the id of the user and document_id is where the users belong.
Model:
Department:
public function users()
{
return $this->belongsToMany('\App\Models\User', 'department_user');
}
User:
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Controller:
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
foreach ($departmentRecipient as $department)
{
$department->users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
}
return view('document.create')->with('department', $department);
}
I'm getting all the users_id when I die and dump my variable departmentRecipient.
View:
<div class = "form-group">
<label for = "recipient" class = "control-label">Recipient:</label>
<select name = "recipient[]" multiple class = "form-control select2-multi" id = "myUserList">
#foreach ($department as $list)
<option value = "{{ $list->user_id }}">{{ $list->department_name }}</option>
#endforeach
</select>
</div>
I wanted to foreach the $department in my Controller to my select form. But it always says.
Trying to get property of non-object (View: C:\Users\JohnFrancis\LaravelFrancis\resources\views\document\create.blade.php)
Goal:
Use the following loop to iterate through the department users and add them to pivot table.
foreach($request->department as $departmentId)
{
foreach(Department::find($departmentId->id)->users()->get() as $user1) //find the users belonging to the current department
{
$document->sentToUsers()->sync([ $user1->id => ['sender_id' => $user->id]],false );
}
}
Also remove the following code form your getDocuments() as it is redundant:
foreach ($departmentRecipient as $department)
{
$department->users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
}
I don't see user_id property in your dumped value of $departmentRecipient object, that is why you are getting the error you mentioned. However, there is a users array inside of $departmentRecipient object, which you made inside your foreach loop. You are plucking every user_id which are in individual department and setting in a property named users of $departmentRecipient object, and so you are getting an array inside users property. Here I have a solution for you,
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
$departmentUsers = array();
foreach ($departmentRecipient as $department)
{
$users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
foreach ($users as $userId) {
$departmentUsers[$userId] = $department->department_name;
}
}
return view('document.create')->with('department', $department)->with('departmentUsers', $departmentUsers);
}
and inside of your view loop through the variable $departmentUsers, like this,
#foreach ($departmentUsers as $userId => $departmentName)
<option value = "{{ $userId }}">{{ $departmentName }}</option>
#endforeach
This will work but as your department contains multiple users so you will get individual department name multiple time in your select2 dropdown. If you share more of what is your goal by select2 then may be I can help you to solve your problem in other way.
Moreover if you are interested to use of Eloquent then you can get rid of lots of foreach looping.
In your case you can have multiple users against each department. So to make it work correctly with your forearch code. You need to make sure you are getting one user record against each depart. So modify following line of code in controller.
$department->users = DB::table('department_user')->where('department_id', '=', $department->id)->pluck('user_id');
But you want to display all users of department then you have to change foreach loop code into view.
Try This Code
App/Department
public function users()
{
return $this->belongsToMany('App\Entities\User', 'department_user', 'user_id', 'department_id');
}
App/User
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Controller
use App/User;
public function getDocuments($userId,User $User)
{
$getSpecificUser = $User->with('departments')->find($userid);
return view('document.create')->compact('getSpecificUser');
}
View
#foreach ($getSpecificUser as $getUser)
#if(empty($getUser->departments) === false)
#foreach ($getUser->departments as $departments)
<option value = "{{ $getUser->id }}">{{ $departments->department_name }}</option>
#endforeach
#endif
#endforeach

Bookmark an article in Laravel

I am trying to create a functionality for a user to be able to bookmark and article and remove the article from his bookmarks as well. The functionality to bookmark an article works just fine, but when I try to remove the article from the bookmarks then it does not work and instead it inserts the same record but with the article_id being NULL.
Here is my controller:
public function postBookmark() {
$user_id = Auth::user()->id;
$article_id = Input::get('id');
$bookmark = Bookmark::where('user_id', '=', $user_id)->where('article_id', '=', $article_id);
$article = Article::where('id', '=', $article_id);
$article = $article->first();
// I want to check if the article has been already bookmarked by the same user
// but this if statement always returns true
if(!empty($bookmark)) {
$bookmark = Bookmark::create(array(
'user_id' => $user_id,
'article_id' => $article_id,
));
if($bookmark) {
return View::make('article.view')
->with('article', $article)
->with('bookmarked', true);
}
} else {
// Does not work
$bookmark->delete();
return View::make('article.view')
->with('article', $article)
->with('bookmarked', false);
}
return Redirect::route('article-all')
->with('global', 'We were unable to bookmark the article. Please, try again later.');
}
And here is part of my view:
{{ Form::open(array('action' => 'BookmarkController#postBookmark')) }}
<input
type="checkbox"
name="id"
onClick="this.form.submit()"
value="{{ $article->id }}"
id="bookmark"
{{ $bookmarked ? 'checked' : '' }}
/>
<label for="bookmark">Bookmark</label>
{{ Form::close() }}
I do also have a route with a post method for this functionality. I would highly appreciate if anyone could give any idea of why it does not work.
You are not executing your bookmark query.
The $boomark variable in your code example is a Illuminate\Database\Eloquent\Builder object and empty($boomark) will return always false because there is a object stored.
To execute a query you can use get() for example. In your case you want only one result, then you use first() to retrieve the first found bookmark object.
Change:
$bookmark = Bookmark::where('user_id', '=', $user_id)->where('article_id', '=', $article_id);
To this:
$bookmark = Bookmark::where('user_id', '=', $user_id)->where('article_id', '=', $article_id)->first();
Then it should work fine.
If you really want, changing the condition if(!empty($bookmark)) to if ($bookmark->count()) { might do the trick, but it will do another query with COUNT() to the DB and it is not really a good way of doing it.
The problem is with if(!empty($bookmark)), because $bookmark has a QueryBuilder instance, it will never be empty.
The preferred way would be using Eloquent model relations. With relationships you could check by Article::has('bookmark') for instance.
Thanks for the help. I ended up using both of your solutions.
public function postBookmark() {
$user_id = Auth::id();
$article_id = Input::get('id');
$bookmark = User::find($user_id)->bookmarks()->where('article_id', '=', $article_id)->first();
if(empty($bookmark)) {
$bookmark = Bookmark::create(array(
'user_id' => $user_id,
'article_id' => $article_id,
));
if($bookmark) {
return Redirect::route('article-get', array('article_id' => $article_id));
}
} else {
$bookmark->delete();
return Redirect::route('article-get', array('article_id' => $article_id));
}
return Redirect::route('article-all')
->with('global', 'We were unable to bookmark the article. Please, try again later.');
}
Nonetheless, what I really needed to fix was my view. For some reason the id of my input was not being submitted properly, so I ended up creating a hidden field for it as well.
{{ Form::open(array('action' => 'BookmarkController#postBookmark')) }}
<input
type="checkbox"
name="id"
onClick="this.form.submit()"
value="{{ $article->id }}"
id="bookmark"
{{ $bookmarked ? 'checked' : '' }}
/>
<input
type="hidden"
name="id"
value="{{ $article->id }}"
/>
<label for="bookmark">Bookmark</label>
{{ Form::close() }}

Categories