hide action button if roles have relationship with users - php

Hi I am working on Role Based authentication in Laravel and every thing works fine but I have problem in Role section.
I want to hide action buttons like Edit and Delete from my Roles List Page those roles which have been assigned to users can't be delete but other roles which haven't assigned to user yet can be deleted.
Role Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('role_typ');
$table->string('role_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
User migration
class AddColumnsToUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
});
}
user model
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
Role Controller
// Role Management
public function Rolelist()
{
$roles = Role::paginate(10);
return view('admin.roles', compact('roles'));
}
Role list blade page
<div class="card">
<div class="card-header">
<h3 class="card-title">All Role List</h3>
<div class="card-tools">
<a href="{{ route('roleform') }}" class="btn btn-block btn-success btn-sm">Add Role <i
class="fas fa-user-plus"></i></a>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>ID</th>
<th>Role Name</th>
<th>Role Type</th>
<th>Created</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($roles as $role)
<tr>
<td>{{ $role->id }}</td>
<td>{{ $role->role_name }}</td>
<td>{{ $role->role_typ }}</td>
<td> {{ \Carbon\Carbon::createFromTimeStamp(strtotime($role->created_at))->diffForHumans() }}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>

In the Role model you should have users method which contains HasMany relationship to User model. After that when you get the roles you should use Role::withCount('users');
Then in the blade file you can use $role->users_count to check how many users you have attached to this role.
https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models

Related

How to show images in a datatable after submitting them in a form?

I made a form where I add a product with fields like name, price, image and its category. Now I would like to display them in a datatable and I was able to do that. The problem is that for the display, all the fields are displayed but the images alone do not come and shows an icon of an image not loaded. Here's a bit of that in the capture I submitted.
The blade.php:
#extends('layouts.appadmin')
#section('title')
Livres
#endsection
#section('contenu')
<div class="card">
<div class="card-body">
<h4 class="card-title">Livres</h4>
<div class="row">
<div class="col-12">
<div class="table-responsive">
<table id="order-listing" class="table">
<thead>
<tr>
<th>Order #</th>
<th>Nom du livre</th>
<th>Prix</th>
<th>Image</th>
<th>Statut</th>
<th>Catégorie</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($livres as $livre)
<tr>
<td>{{$livre->id}}</td>
<td>{{$livre->nomLivre}}</td>
<td>{{$livre->prixLivre}}</td>
<td><img src="/storage/{{$livre->image}}" alt=""></td>
<td>
#if ($livre->statusLivre ==1)
<label class="badge badge-success">Activé</label>
#else
<label class="badge badge-success">Désactivé</label>
#endif
</td>
<td>{{$livre->categorie->category_name}}</td>
<td>
<button class="btn btn-outline-primary">View</button>
<button class="btn btn-outline-danger">Delete</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script src="Administrateur/js/data-table.js"></script>
#endsection
</body>
</html>
Just below, It's the controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Categorie;
use App\Models\Livre;
class LivreController extends Controller
{
//
public function ajouterlivre()
{
$categories = Categorie::all();
return view('admin.ajouterlivre', [
'categories' => $categories,
]);
}
public function sauverlivre(Request $request)
{
$request->validate([
'nomLivre' => 'required|unique:livres',
'prixLivre' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'categorie_id' => 'required',
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'storage/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
Livre::create($input);
return redirect('/ajouterlivre')->with('status', 'Un livre a été ajouté avec succès');
}
public function livre()
{
$livres = Livre::get();
return view('admin.livres')->with('livres', $livres);
}
The migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLivresTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('livres', function (Blueprint $table) {
$table->increments('id');
$table->string('nomLivre')->unique();
$table->integer('prixLivre');
$table->string('image');
$table->integer('statusLivre')->default(0)->nullable();
$table->integer('categorie_id')->unsigned();
$table->foreign('categorie_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('livres');
}
}
You see that the images are not loaded, right? What could have caused this? Thank you for your attention.

parent id for category and subcategory

I use L8 And I have a category table ,it has parent_id for my subcategories
categories table
Category model
categoryController
SubCategoryController
categories.blade
sub_categories.blade
In my subcategory-index.blade.php I want to show categories but I just can show them with their id (parent id)
I don't know how to show categories title instead of their id.
I have this migration for categories table :
public function up()
{
Schema::dropIfExists('categories');
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('parent_id')->default(123);
$table->string('title');
$table->longText('description');
$table->tinyInteger('status')->comment('status is 1 when a category is active and it is 0 otherwise.')->nullable();
$table->rememberToken();
$table->softDeletes();
$table->timestamps();
});
}
and this is my category model :
class Category extends Model
{
use HasFactory;
protected $fillable = [
'parent_id','title' , 'description', 'status',
];
public function children(){
return $this->hasMany(Category::class , 'parent_id');
}
public function post(){
return $this->hasMany(Post::class);
}
}
And my subcategory controller :
...
public function index()
{
$parent_id = Category::with('parent_id')->get();
$subcategories = Category::where('parent_id' ,'!=', 123)->get();
return view('admin.subcategories.subcategories-index' , compact('subcategories'));
}
...
And the part for show subcategory title in category-index.blade.php :
<table class="table table-bordered">
<tr>
<th>#</th>
<th>id</th>
<th>title</th>
<th>category</th>
<th>status</th>
<th>operation</th>
</tr>
#foreach($subcategories as $subcategory )
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $subcategory['id'] }}</td>
<td>{{ $subcategory['title'] }}</td>
<td>{{ $subcategory['parent_id']}}</td>
<td>
#if($subcategory['status']==0 or $subcategory['status']==NULL)
inactive
#else
active
#endif
</td>
<td>
<form method="POST" action="{{ route('subcategory.destroy',$subcategory->id) }}">
<a class="btn btn-info" href="{{ route('subcategory.show' , $subcategory->id) }}">show</a>
<a class="btn btn-primary" href="{{ route('subcategory.edit' , $subcategory->id) }}">edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger"> delete</button>
</form>
</td>
</tr>
#endforeach
</table>
Thanks for telling me what to do :>
To get subcategories
$sub_categories = Category::whereNotNull('parent_id')->get();
To get sub-categories with parent
$sub_categories_with_parent = Category::with('parent')->whereNotNull('parent_id')->get();
To fetch categories
$categories = Category::whereNull('parent_id')->get();
To fetch categories with children
$categories_with_childern = Category::with('children')->whereNull('parent_id')->get();
You might have to redefine your relations as well:
public function parent()
{
return $this->belongsTo(Category::class);
}
public function children()
{
return $this->hasMany(Category::class , 'parent_id');
}
In migration define relation as well
$table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
Make parent field nullable
$table->unsignedBigInteger('parent_id')->nullable()->default(123);
The line down below is incorrect. Because with() is used to get relational data and parent_id is not a relation name.
$parent_id = Category::with('parent_id')->get();
If your route contains the id or slug of the category, you can use it, but I think it doesn't, because your index function doesn't accept any route parameter. So I assume you are trying to fetch all categories and subcategories. But in this case, the second line of the index function doesn't make sense at all.
If you want to all categories:
$categories = Category::where('parent_id', null)->with('children')->get();
I see you use 123 for top-level categories, and it looks high enough. But nullable is a better practice for that purpose.
If you need a specific category and its subcategories:
// web.php
Route::get('category/{slug}', [CategoryController::class, 'index']);
// CategoryConteroller.php
public function index($slug)
{
$category = Category::where('slug', $slug)->with('children')->get();
}

Tried to using belongsTo in Laravel but its not working

im using Laravel 6.2
I want to make a inventory database system. i have 2 modals Produk and Stock.
in that case, i want to input data p_name and sku from ProdukTable and place it into StockTable using Eloquent ORM.
I tried using belongsTo(),
Here's my modal Produk code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
public $table = 'produk';
protected $primaryKey = 'pid';
protected $fillable = [
'pid',
'p_nama',
'sku',
'p_harga',
'status'
];
}
Here's my modal Stock code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stock extends Model
{
public $table = 'stock';
protected $primaryKey = 'sid';
protected $fillable = [
'sid',
'p_nama',
'sku',
'p_stock_min',
'p_stock',
'status'
];
public function produk()
{
return $this->belongsTo('App\Produk', 'pid');
}
}
My StockController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Stock;
use App\Produk;
use RealRashid\SweetAlert\Facades\Alert;
class StockController extends Controller
{
public function index()
{
$datas = Stock::paginate(5); // 5 record per pages
return view('stock.list', compact('datas'));
// $datas = Stock::all();
// return $datas;
}
. . . .
}
My View stock.blade
<div class="body">
<div>
<i class="zmdi zmdi-account-add"></i> Tambah Stock
<a style="margin: 2px;" href="{{ route('stock.index')}}" class="btn btn-primary btn-sm"><i class="zmdi zmdi-refresh"></i></a>
</div>
<div class="col-sm-12">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
</div>
<table class="table table-bordered table-striped table-hover dataTable js-exportable">
<thead>
<tr>
<th class="text-center" style="width:5%">#</th>
<th class="text-center" style="width:25%">Nama Produk</th>
<th class="text-center" style="width:10%">SKU Produk</th>
<th class="text-center" style="width:8%">Min. Stock</th>
<th class="text-center" style="width:8%">Stock</th>
<th class="text-center" style="width:10%">Status</th>
<th class="text-center" style="width:10%">Aksi</th>
</tr>
</thead>
<tbody>
#if(!empty($datas) && $datas->count())
#foreach($datas as $data)
<tr>
<th class="text-center">{{ $loop->iteration }}</th>
<td>{{ $data->produk }}</td>
<td>{{ $data->p_nama }}</td>
<td>{{ $data->p_stock_min }}<code> pcs</code></td>
<td>{{ $data->p_stock }}<code> pcs</code></td>
<td class="text-center">{{ $data->status }}</td>
<td class="text-center">
<i class="zmdi zmdi-edit"></i></span>
<i class="zmdi zmdi-delete"></i></span>
</td>
</tr>
#endforeach
#else
<tr>
<td colspan="8">Data tidak ditemukan! Silahkan buat data Stock terlebih dahulu.</td>
</tr>
#endif
</tbody>
</table>
{!! $datas->links() !!}
</div>
Migration Stock
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStocksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stock', function (Blueprint $table) {
$table->bigIncrements('sid');
$table->bigInteger('produk_id')->unsigned();
$table->string('p_nama');
$table->string('sku');
$table->integer('p_stock_min');
$table->integer('p_stock')->nullable();
$table->string('status');
$table->timestamps();
});
Schema::table('stock', function (Blueprint $table) {
$table->foreign('produk_id')->references('pid')->on('produk')
->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stock');
}
}
Response when i add data direct from PMA
[{"sid":1,"produk_id":6,"p_nama":"kopi1","sku":"12345678","p_stock_min":20,"p_stock":800,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"},
{"sid":2,"produk_id":7,"p_nama":"kopi2","sku":"87654321","p_stock_min":20,"p_stock":600,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"}]
i dunno where's my mistake ?
just want to add data p_produk into stock table using select form, and when i select it sku data will be generate as same as data on table Produk.
In your Stock model you should put the foreign key in the belongsTo relation. Edit the method like so:
public function produk()
{
return $this->belongsTo('App\Produk', 'produk_id');
}
Using Laravel conventions the relationship produk should be defined as
public function produk()
{
return $this->belongsTo(Produk::class, 'produk_id', 'pid');
}
To dynamically change the value of sky in the readonly input on create.blade.php based on the option selected by the user in select control showing $produk->p_nama:
Give an id to the readonly input for sku
<div class="form-group">
<label for="sku">SKU:</label>
<input type="text" class="form-control form-control-lg" name="sku" id="skuSelected" readonly/>
</div>
Track the option selected in select control
<select class="form-control select2" name="p_name" onChange="setSku(this);">
#foreach($produks as $produk)
<option value="{{ $produk->pid }}">{{ $produk->p_nama }}</option>
#endforeach
</select>
Handle the change in selection via javascript
<script>
function setSku(sel) {
const sku = sel.options[sel.selectedIndex].text;
document.getElementById('skuSelected').value = sku;
}
</script>
because you are not naming your columns on the laravel naming conventions
you have to define it all by yourself if you want to use this naming like this :
public function produk()
{
return $this->belongsTo('App\Produk', 'pid' , 'id');
}
as belongsTo takes $relatedModel , $foreignKey , $ownerKey in a row

Laravel 7. How to fetch records from various tables using foreign key in laravel?

Laravel 7 and 2 tables: comp, computers.
I would like to display in the view index.blade.php the name of the computer e.g. DELL, IBM, LENOWO instead of id of this name.
What the foreach syntax should look like to retrieve the computer name from the computers table.
And when you add a new PC, what should the dropdownlist look like?
class CreateCompTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('comp', function (Blueprint $table) {
$table->id();
$table->integer('name_id')->unsigned();
$table->string('number');
$table->string('year');
$table->timestamps();
$table->foreign('name_id')->references('id')->on('computers')
->onDelete('cascade');
});
}
Table Computers
class CreateComputersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('computers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
CompControllers
namespace App\Http\Controllers;
use App\Comp;
use Illuminate\Http\Request;
class CompController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$comp = Comp::latest()->paginate(5);
return view('comp.index',compact('comp'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('comp.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name_id' => 'required',
'number' => 'required',
'year' => 'required',
]);
comp::create($request->all());
return redirect()->route('comp.index')
->with('success','xxx.');
}
/**
* Display the specified resource.
*
* #param \App\Comp $comp
* #return \Illuminate\Http\Response
*/
public function show(Comp $comp)
{
return view('comp.show',compact('comp'));
}
View index.blade.php
#extends('comp.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Comp</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('comp.create') }}"> Add comp</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>L.p</th>
<th>Name comp</th>
<th>Number comp</th>
<th>Year</th>
<th width="250px">Acction</th>
</tr>
#foreach ($comp as $comp)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $comp->name_id }}</td>
<td>{{ $comp->number }}</td>
<td>{{ $comp->year }}</td>
<td>
<form action="{{ route('comp.destroy',$comp->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('comp.show',$comp->id) }}">View</a>
<a class="btn btn-primary" href="{{ route('comp.edit',$comp->id) }}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
#endsection
On Comp model, make a belongsTo relation :
public function computer()
{
return $this->belongsTo('App\Computer', 'name_id');
}
Now you can access this relation, from your blade, as:
#foreach($comp as $comp)
<tr>
<td>{{ $comp->computer->name }}</td>
</tr>
#endforeach

Getting data from foreign key on view (Laravel 5.6)

I already searched for answers but I couldn't find any answer that could solve my problem.
I have 2 tables: phones and phone_types. The first one has a foreign key associated with the phone_types primary key. I want to show on view the name of phone_type through phone object. Something like $phone->phone_type->name.
My code generates this error: Trying to get property of non-object (View: /home/ablono/dev/MisServices/resources/views/painel/phones/home.blade.php)
My code is listed below.
phone_types miration table:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePhoneTypesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('phone_types', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 20);
$table->string('description', 30);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('phone_types');
}
}
```
phones migration table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePhonesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('phones', function (Blueprint $table) {
$table->increments('id');
$table->string('ddd')->default('13');
$table->string('number', 20);
$table->integer('phone_type_id')->unsigned();
$table->foreign('phone_type_id')
->references('id')
->on('phone_types')
->onDelete('cascade');
$table->timestamps();
});
Schema::create('phone_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('phone_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('phone_id')
->references('id')
->on('phones')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('phone_user');
Schema::dropIfExists('phones');
}
}
I didn't code anything on PhoneType model, but here is the code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PhoneType extends Model
{
//
}
Phone model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
public function users()
{
return $this->belongsToMany(\App\User::class);
}
public function phoneType()
{
return $this->hasMany(\App\PhoneType::class);
}
}
Method that is sending that to view:
public function index()
{
$phones = Phone::all();
return view('painel.phones.home', compact('phones'));
}
Part of view that is listing data:
<table class="table">
<thead>
<th>ID</th>
<th>DDD</th>
<th>Número</th>
<th>Tipo de Telefone</th>
<th width="150px">Ações</th>
</thead>
<tbody>
#foreach($phones as $phone)
<tr>
<div class="loading"></div>
<td>{{ $phone->id }}</td>
<td>{{ $phone->ddd }}</td>
<td>{{ $phone->number }}</td>
<td>{{ $phone->phone_type_id->name }}</td>
<td>
<i class="fa fa-lg fa-phone" title="Visualizar usuários que usam {{ $phone->number }}"></i>
<i class="fa fa-lg fa-pencil" title="Editar {{ $phone->number }}"></i>
<i class="fa fa-lg fa-times" title="Excluir {{ $phone->number }}"></i>
<i class="fa fa-lg fa-eye" title="Visualizar {{ $phone->number }}"></i>
</td>
</tr>
#endforeach
</tbody>
</table>
Change your relationship to belongsTo():
public function phoneType()
{
return $this->belongsTo(\App\PhoneType::class, 'phone_type_id');
}
And in view
<td>{{ $phone->phone_type->name }}</td>
Please check your eloquent model relationship. And accessing the eloquent property is like .
$main-model->$sub-model(method name of model which you want access)->property
Note: When you access method please convert method name in to snake case

Categories