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
Related
when a foreign key value is null I want to return a specific value from the model because when I delete the primary key id row and set a null value on the foreign key shows error. how to can I do it please anybody help me?
Here Is My Country Migration Table:
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->id();
$table->string('name', 60)->nullable();
$table->string('country_code', 60)->nullable();
$table->string('capital', 120)->nullable();
$table->string('region', 120)->nullable();
$table->string('currency_code', 120)->nullable();
$table->string('currency_name', 120)->nullable();
$table->string('currency_symbol', 120)->nullable();
$table->string('language_code', 120)->nullable();
$table->string('language_name', 120)->nullable();
$table->bigInteger('flag')->unsigned()->nullable();
$table->foreign('flag')->references('id')->on('media_files')->onDelete('cascade')->onUpdate('cascade');
$table->string('dialling_code', 10)->nullable();
$table->integer('status')->default(0)->unsigned();
$table->timestamps();
});
}
Here Is My City migration Table:
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('zipcode')->nullable();
$table->string('order')->default(null)->nullable();
$table->foreignId('country_id')->nullable()->constrained("countries")->cascadeOnUpdate()->nullOnDelete();
$table->timestamps();
});
City Model:
class City extends Model
{
use HasFactory;
public function country(){
return $this->belongsTo(Country::class,'country_id');
}
}
Frontend Blade:
<tbody>
#foreach($CityList as $City)
<tr>
<td><input type="checkbox" name="id[]"></td>
<td>{{$City->id }}</td>
<td>{{$City->name }}</td>
<td>{{$City->zipcode }}</td>
<td>{{$City->country->name }}</td>
<td>{{$City->country->countrycode }}</td>
<td>{{$City->order }}</td>
<td>{{$City->created_at->diffForHumans()}}</td>
<td>
<i class="fa fa-edit" style="font-size: 17px;"></i>
<button href="{{ route('dashboard.city.delete',$City->id) }}" type="button" value="{{ $City->id }}" class="btn btn-danger delete" data-toggle="tooltip" title="Delete">
<i aria-hidden="true" class="fa fa-trash"></i>
</button>
</td>
</tr>
#endforeach
</tbody>
I can suggest a few ways to solve this
First: Make a default value for the relation, like here
public function country()
{
return $this->belongsTo(...)->withDefault(['name' => 'No country']);
}
Second: Make a mutation in City model to find the name of the country
protected function countryName(): Attribute
{
return Attribute::make(
get: fn ($value) => $this->country-> name ?? 'Not country',
);
}
Notes: This way works only for laravel 9.x +, for older versions
please read this article
You can do this: <td>{{$City->country ? $City->country->name : 'No country found'}}</td>
And make sure you are including countries when fetching cities.
I'm trying to call a variable from a table, but I'm getting an error "Undefined variable $user". I'm trying to make the program display the Username from the user from the table.
I'm using 2 tables, tribes which represents something like a group, and a user which represents.. well.. user.
So I'm trying to connect the two by displaying the creator of a certain "tribe".
User controller:
<?php
namespace App\Http\Controllers;
Use App\Models\User;
use Illuminate\Http\Request;
class tribesController extends Controller
{
public function index($user)
{
$user = User::findOrFail($user);
return view('home',[
'user'=>$user,
]);
}
}
Homepage:
#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">{{ __('Dashboard') }}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
{{ $user->username }}
</div>
</div>
</div>
</div>
</div>
#endsection
Router:
<?php
use Illuminate\Support\Facades\Route;
/*
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', function () {
return view('home');
});
Route::get('/playlist', function () {
return view('playlist');
});
Route::get('/tribe', function () {
return view('tribe');
});
Route::get('/edit', function () {
return view('edit');
});
Auth::routes();
Route::get('/tribe/{user}', [App\Http\Controllers\TribesController::class, 'index'])->name('tribe.index');
Database file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTribesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tribes', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->string('genre');
$table->string('filepath')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tribes');
}
}
model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class tribe extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
use HasFactory;
}
You are treating the url parameter as a object, it can't be an object until you get it. Pass in a user id and then query the ORM for a user matching that id then you can use it as an object!
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
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
I have some problem to get information about item. I read a lot of information on forums stakoverflow. Maybe i can not find the correct information. Maybe someone knows about that hove to solve the problem
I have 4 tables
public function up()
{
Schema::create('db_items', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_weapons', function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->unsigned();
$table->foreign('item_id')
->references('id')->on('db_items')
->onDelete('cascade');
$table->integer('grade_id')->unsigned();
$table->foreign('grade_id')
->references('id')->on('db_item_grades')
->onDelete('cascade');
$table->string('hand')->nullable();
$table->string('name')->nullable();
$table->text('description')->nullable();
$table->string('icon')->nullable();
$table->string('p_atak')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_db_item_category', function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->unsigned()->index();
$table->foreign('item_id')
->references('id')->on('db_items')
->onDelete('cascade');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')
->references('id')->on('db_item_categories')
->onDelete('cascade');
$table->timestamps();
});
}
And 3 models
class DbItem extends Model
{
function weapon()
{
return $this->hasOne(DbItemWeapon::class, 'item_id');
}
function categories()
{
return $this->belongsToMany(DbItemCategory::class,'db_item_db_item_category','item_id','category_id');
}
}
class DbItemWeapon extends Model
{
function DbItem()
{
return $this->belongsTo(DbItem::class);
}
}
class DbItemCategory extends Model
{
function items()
{
return $this->belongsToMany(DbItem::class,'db_item_db_item_category','category_id','item_id')->with('weapon');
}
}
When i try to get some inforamtion it wotrks for example
#foreach($categories as $category)
<li>
<a class="uk-accordion-title" href="#">{{ $category->name }}</a>
<div class="uk-accordion-content">
#foreach( $category->items as $item)
<p>{{ $item->id }}</p>
#endforeach
</div>
</li>
#endforeach
i got the categories wtith their items and i can view the items id which contains in categoryes but if i want to see more information, its not work
$item->weapon->name
Maybe some of the items does not have a weapon, check for the weapon's existence first:
#foreach($categories as $category)
<li>
<a class="uk-accordion-title" href="#">{{ $category->name }}</a>
<div class="uk-accordion-content">
#foreach( $category->items as $item)
#php
$weapon = $item->weapon;
#endphp
<p>{{ $item->id }}</p>
<p>{{ $weapon ? $weapon->name : null }}</p>
#endforeach
</div>
</li>
#endforeach