Connecting two tables in mysql - php

I have two tables in my database - vnames and vtypes
vtypes have a name field and a id field, vnames have a id field, name field and a vtypes_id field which is a foreign key connected field. It is connected with the id field in vtypes.
I have Vname and Vtype models -
Vname
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vname extends Model
{
public function vtype() {
return $this->belongsTo('App\Vtype');
}
}
Vtype
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vtype extends Model
{
public function vname() {
return $this->hasMany('App\Vtype');
}
}
When i delete any column in vtype table i want to delete all the vname columns associated with it.
I found a solution like this -
public function vtypeDestroy($id) {
$vtype = Vtype::find($id);
$vtype->vname()->detach();
$vtype->delete();
Session::flash('success', 'The vtype was successfully deleted');
return redirect('/vtypes');
}
but when i run this function i get an error like this - Call to undefined method Illuminate\Database\Query\Builder::detach()
How can i fix it?
And when i want to get the name of the vtype from vname i am not able to do it. I tried like this
#foreach ($vnames as $vname)
{{ $vname->vtype()->name }}
#endforeach
in a view
But i got an error like this -- Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
Please guide me how to fix this two problems which i face now.

Your relation should be as:
Vname Model
class Vname extends Model
{
public function vtype() {
return $this->belongsTo('App\Vtype', 'vtypes_id', 'id');
}
}
Vtype
class Vtype extends Model
{
public function vname() {
return $this->hasMany('App\Vname', 'vtypes_id', 'id');
}
}
Then you can use delete method to delete the relations as:
$vtype = Vtype::find($id);
$vtype->vname()->delete();
$vtype->delete();
And in your view it should be as:
#foreach ($vnames as $vname)
{{ $vname->vtype->name }}
#endforeach
Docs

Please use...
$vtype->vname()->delete();
instead of $vtype->vname()->detach();... Problem solved! For the inverse of it, vname->vtype() you can you dissociate() method... which will set vtype_id to null in vname table. More explanation here
Detach is used for belongsToMany() - belongsToMany() relation... yours is hasMany() - belongsTo().
Also, instead of doing {{ $vname->vtype()->name }}
please do
#foreach ($vnames as $vname)
{{ $vname->vtype->name }}
#endforeach
The reason for this is... when you put the brackets in front of the relation name, it calls a query builder... But here, what you need is the model... So $vname->vtype will give you Vtype Model while $vname->vtype() will give you query builder.

Related

laravel show database values in my blade front end foreign keys values

So I'm new to laravel and I'm trying to figure out a way to connect my database with my front end!
First this is the villa model for the table villas:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Villa extends Model
{
use HasFactory;
protected $fillable=[
"id", "title", "description", "price", "state", "status", "city_id", "seller_id", "payment_id", "created_at", "updated_at"
];
public function City()
{
return $this -> hasOne(City::class,'id','city_id');
}
public function Seller()
{
return $this -> hasOne(Seller::class,'id','seller_id');
}
public function Payment()
{
return $this -> hasOne(Payment::class,'id','payment_id');
}
}
this is the website controller : and here I'm trying to call the table
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Villa;
use App\Models\City;
use App\Models\VillaImg;
class WebsiteController extends Controller
{
public function index(){
$villas = DB::select('select * from villas');
return view('website',['villas'=>$villas]);
}
this is the website blade which I use this way to call the value but I don't know how to call a foreign key value , for example :
I have the foreign key city_id and I want the show the city name on my front end but don't know how
#foreach ($villas as $user)
{{old('name',$user->title )}}
#endforeach
#foreach ($villas as $user)
{{old('city',$user->I don't know what to write here)}}
#endforeach
Note: this is a code in a div that represents a villa block.
Also, I'm not sure if this is really the correct way to do so and I want to know if there's another efficient way to do that!
here's the route:
Route::get('/',[WebsiteController::class,'index'])->name('home.index');
use eloquent orm instead of db facade...
$villas = Villa::with(['City', 'Seller', 'Payment'])->get();
and then if u need any relation value:
#foreach ($villas as $villa)
{{ $villa->City->property }}
#endforeach

Laravel get record from database in blade view

I would like to known how to get data from database in blade like from User table:
{{ Auth::user()->name }}
I have table user_settings
I would like to get record from this table by logged user id like this:
{{ UserSettings::user()->my_field }}
How can I do that?
Try this on your blade view
{{ \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field }}
In default, model file is inside App folder.
Such direct access to database table is not preferred though, you can return this as a variable from controller function like,
$field = \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field;
return view('view_name',comapact('field'));
and use in blade like
{{$field}}
Another good way is posted by Orkhan in another answer using eloquent relationship.
Hope you understand.
You need to retrieve the UserSettings associated to the authenticated user:
UserSettings::where('user_id', Auth::id())->first()->my_field
You can defined a method named current() to return that for you.
class UserSettings extends Model
{
public static function current()
{
return UserSettings::where('user_id', Auth::id())->first()
}
}
Then use:
UserSettings::current()
On the other had it would better to use one-to-one relationship on user model:
class User extends Model
{
public function settings()
{
return $this->hasOne('App\UserSettings');
}
}
Then use:
Auth::user()->settings->my_field

Display name of table instead of its id Laravel

I have 2 tables, tn_project has id name cv_id_project and tn_activity has id name id, i want to get the name of the project which is cv_project_name rather its id.
Basically when i click add activity i have select option to choose which project that i use, i manage to get the id of selected project but i want its name(i can select up to 3 project in a single activity)
Model
<?php namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Activity extends Model {
protected $table = 'tn_activity';
public $timestamps = false;
public function projectModel(){
return $this->hasMany('Activity\Project','cv_id_project','id');
}
}
VIEW
#foreach($query as $result)
<td>{{$result->projectModel->cv_project_name}}</td>
#endforeach
Controller
public function index(){
return view('landing-page')
->with('title','Landing Page')
->with('query',Activity::with('projectModel')->get())
->with('projects',Project::all());
}
usually it's work but i don't know what makes it error
and then this error occured
Undefined property: Illuminate\Database\Eloquent\Collection::$cv_project_name (View: C:\xampp\htdocs\PKL\netxcel-2-backup2\resources\views\landing-page.blade.php)
Your Activity projectModel is a collection, because it has hasMany relationship. If it's really true, you should get the project name like this.
#foreach ($result->projectModel as $project)
<td>{{$project->cv_project_name}}</td>
#endforeach
However, if it shouldn't have hasMany relationship than you should change the hasMany part

how to use a simple Relationships in laravel

I have two tables like below:
users table:
id - fname - lname
users_projects table:
id - user_id - title
my models are inside a directory called Models:
Users model :
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
//
public function usersProjects()
{
return $this->belongsTo(UsersProjects::class);
}
}
UsersProjects model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UsersProjects extends Model
{
protected $table = 'users_projects';
//
public function users()
{
return $this->hasOne(Users::class);
}
}
now, I want to show last projects :
$projects = UsersProjects::limit(10)->offset(0)->get();
var_dump($projects);
return;
but my var_dump shows last projects ! I want to have fname and lname ! where is my wrong ?
I think you may have your relationships set up a little wrong. If a user can have more than one project, in your user model ...
public function usersProjects()
{
return $this->hasMany(UsersProjects::class);
}
You might want to use a little simpler naming too ...
public function Projects()
{
return $this->hasMany(UserProject::class);
}
(or simply Project if you don't have any other "Project" models)
The in your "Project" class ...
public function User()
{
return $this->belongsTo(User::class);
}
(assuming you rename your model to User instead of "Users". Your table name should be "users" but a model is by nature a singular object. So it's appropriate to call it "User" - and your UsersProjects model should just be UserProject or just Project)
Now if you call the method something other than "User" you will have to add the foreign key name ...
public function SomeOtherName()
{
return $this->belongsTo(User::class, 'user_id');
}
Then ...
$projects = Project::with('User')->limit(10)->offset(0)->get();
Will return a collection of projects with the User eager-loaded. (assuming you have renamed your UsersProjects model to "Project")
#foreach($projects as $project)
...
First Name: {{ $project->User->fname }}
...
#endforeach
Could you specify the relationships between the tables? (one to one, one to many) at first sight, I think that the relations are wrong

Undefined variable laravel 4.1

I am trying to get data from database and pass values to controller. I am new at laravel and thats the first query. Here is my code:
class Cars extends Eloquent
{
}
FleetController.php
public function index()
{
$fleet = Cars::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}
home.blade.php
#extends('layouts.default')
#section('content')
{{ $fleet }}
#stop
The problem is that it shows this at log
Next exception 'ErrorException' with message
'Undefined variable: fleet (View: C:\wamp\www\laravel\app\views\pages\home.blade.php)' in C:\wamp\www\laravel\app\storage\views\7da5cff457f71f3156f90053865b6cb1:2
Stack trace:
You should try using
#if(Session::has('fleet'))
{{Session::get('fleet')}}
#endif
Your '->with()' just flashes the variable to your session. You still need to retrieve it from there though.
Also, you should try creating a model with the same name as your table. If you were to create a model Car that extends Eloquent, it will automatically be linked to your Cars table. Laravel docs:
The lower-case, plural name of the class will be used as the table
name unless another name is explicitly specified.
This part is important as well:
Eloquent will also assume that each table has a primary key column
named 'id'.
Once you got that configured, you'll be able to get the description of a car by simple doing
Car::all()->first()->description;
See also: Laravel docs on eloquent
Update
What should work:
Car.php
class Car extends Eloquent{
//Let's try setting these manually. Make sure they are correct.
protected $table = 'cars';
protected primaryKey = 'id';
}
FleetController.php
public function index()
{
//You have to call the model here, so singular 'Car'.
$fleet = Car::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}
home.blade.php
#extends('layouts.default')
#section('content')
//You can use blade's #if as well:
#if(Session::has('fleet'))
{{Session::get('fleet')}}
#endif
#stop

Categories