Symfony 3 - Using ManyToOne and OneToMany and retrieving the data - doctrine

I have a User table and a Job Title table in my database.
I have setup a User entity and a JobTitle entity.
In my User entity I have:
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\JobTitle", inversedBy="users")
* #ORM\JoinColumn(name="job_title_id", referencedColumnName="id")
*/
public $jobTitle;
In my JobTitle entity I have:
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\User", mappedBy="jobTitle")
*/
private $users;
Here is an example setup in User Table:
job_title_id | Username
1 | jdoe
Here is an example setup in job Title Table:
id | job_title
1 | Owner
When I create the user everything is entered into the database as expected.
My issue is displaying the actual job title in my users list page.
Here is my Controller:
/**
* #Route("/users", name="users")
*/
public function listAction()
{
$loggedInUser = $this->getUser();
$users = $this->get('fos_user.user_manager')->findUsers();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
return $this->render('users/users.html.twig', array(
'user' => $loggedInUser,
'users' => $users,
));
}
In my twig template I was trying to use {{ user.jobTitle }}, but I get a conversion to string error which makes sense, but I have not idea how to get the actual job title name to display in the twig page.
If you need more info please let me know.
How do I retrieve the job title name using the job_title_id in the users table?

You haven't shown all your entities, so I'll have to 'guess' based on what I see above.
Looks like this: {{ user.jobTitle }} returns you a JobTitle object. You can confirm by doing a dump.
Since it's an object, I suspect you'll need to do something like this:
{{ user.jobTitle.job_title }}
Or possibly use the JobTitle's object methods (don't know what they are):
{{ user.jobTitle.getJobTitle }}
Or something like that. Try it out.

Related

How can i get article owner user_id and save to notifiable_id field

How can i get article owner user_id and save to notifiable_id field
Suppos
$articlecomment = $article_owner_id
My code:
$articlecomment = new Article_comment();
$articlecomment->user_id = Auth::user()->id;//Comment by user id
$articlecomment->article_id = $request->articleid;
$articlecomment->comment = $request->comment;
$articlecomment->save();
auth()->user()->notify(new ArticleNotification($articlecomment));
//$articlecomment->user()->notify(new ArticleNotification($articlecomment));
Database Screenshot
i want article_owner_user_id on notifible_id field
enter image description here
Solved
$articlecomment->save();
$article = Article::where('id','=',$request->articleid)->first();
if($article->user_id != Auth::User()->id){
$article->user->notify(new ArticleNotification($article));
}
This is database i need article_owner_id on notifible_id field click here to see screenshot
If you have a relationship set up for your Article_comment and Article models, you can access the "Article Owner" through the relation.
For example, define a relation for your "Article" model inside your Article_comment class (assuming Article is the name of your model):
class Article_comment extends Model {
....
public function article() {
return $this->hasOne('App\Article', 'id', 'article_id')
}
....
}
Once you have that set, you can access your relation (and subsequent properties) like so (assuming article_owner_id is a property of your Article model):
$articlecomment->article->article_owner_id
Edit:
Whichever user you call notify on will notify that user. So to notify the article owner, you will need to get the user of the article and call notify from that instance (rather than the auth user). If you set up a relation to the user on your Article class, you can simply call notify from that, or get the user from the article_owner_id and call notify.
Example:
$user = User::where('id', '=', $articlecomment->article->article_owner_id)->first();
$user->notify(new ArticleNotification($articlecomment));
With a relation set on your Article class, you could instead call notify like this:
$articlecomment->article->user->notify(new ArticleNotification($articlecomment));
For more info on Eloquent relationships, see https://laravel.com/docs/5.6/eloquent-relationships#introduction

Laravel eloquent relationship between two table

I have a table notices. Model for this table is Notice.php
In this table I have notice and id column.
I have fetched all notices from notices table and viewed in my view. Here is my controller code for fetching all notices.
public function index()
{
$notice = Notice::orderBy('id','desc')->paginate(5);
return view('teacher.notice')->withNotices($notice));
}
Here is my view code to show all notices.
#foreach($notices as $notice)
{{$notice->id}}
{{ $notice->notices }}
#endforeach
Now I want to put two button inside this foreach loop. One is to confirm and another is remove confirmation.
To store this confirmation data I have created another table named notice_confirmed_student and model for this table is noticeConfirmedStudent.php. In this table have three column:
id
student_id
notice_id
If a student click confirm then his id and notice id will be stored in this table. I have done this perfect. But my problem is, in the foreach loop it shows both two button (confirm and remove confirm) at a time. I want to show confirm button if user already not confirmed for this notice. If user already confirmed for that notice then it should show remove confirmation button.
Here I am giving my blade foreach loop again with button for better understanding. Bellow code is not perfect, I have just written those code to understand my question.
#foreach($notices as $notice)
{{$notice->id}}
{{ $notice->notices }}
<?php $student_id= "select student_id from notice_confirmed_student where notice_id=$notice->id"; ?>
#if ($student_id == $auth::user()->id)
<button>confirm</button>
#else
<button>Remove Confirmation</button>
#endif
#endforeach
Thanks in advance.
Few things are wrong/incorrect here, to make it clear,
Notice <> User relation is Many-Many and notice_confirmed_student is a pivot table. so user model should have relation,
public function confirmedNotices()
{
return $this->belongsToMany(Notice::class, 'notice_confirmed_student')
}
Then in for each loop you can check like,
if(in_array($notice-id, Auth::user()->confirmedNotices->pluck('id')->all())) {
// user confirmed
} else {
// user not confirmed.
}
if I correctly understand your issue, you need to check if record with given id exists notice_confirmed_student table, and then check in your loop. retrieve the confirmed students with your notices.
$notice = Notice::with('notice_confirmed_student_or_whatever_your_relation_method_called)')->orderBy('id','desc')->paginate(5);
then check in loop, if related attribute is not empty like you do in your view
#if($notice->my_attr && $notice->my_attr->user_id == \Auth::user()->id)
// do stuff
#else
// it doesn't has record
#endif

Laravel 5 - setting up relationships

I have been struggling a little with my application and asked a lot of questions, and before I go any further, I just want to make sure that my relationships are ok.
So I am creating an application whereby you can generate different documents based on the input you provide. So, I create a project, and within that project there is a select field which has different types of documents. If I select DocumentA for example, the create form for DocumentA will be displayed to the user. If I choose DocumentB, the create form for DocumentB will be displayed. Now although these forms are different and take different inputs, I wanted a way whereby I would not have to create a new table for every document type. So I came up with the following.
So within a project, I select I want to create DocumentA. I am then displayed the view documentA.create. This view has hidden inputs for the document name and description. The form fields labels are the key in the document_data table, and the value is the input for this field. So, if I create DocumentA, my database might look like this
project
id | projectName |
------------------
1 | Project One |
------------------
document
id | projectId | documentName |
--------------------------------
1 | 1 | DocumentA |
--------------------------------
document_data
id | documentId | key | value |
----------------------------------------------
1 | 1 | clientName | Google |
----------------------------------------------
2 | 1 | projectName | Analytics |
----------------------------------------------
3 | 1 | Contact | Mr Sharp |
----------------------------------------------
4 | 1 | startDate | 29/12/2016 |
----------------------------------------------
Where I am struggling at the moment is that the foreign key documentId is in the document_data table. However, things are only working if I set a foreign key in both of my Models classes e.g.
class Document extends Model
{
protected $table = 'documents';
protected $guarded = [];
public function documentData()
{
return $this->hasMany('App\DocumentData', 'documentId');
}
}
class DocumentData extends Model
{
protected $table = 'document_data';
protected $guarded = [];
public function document()
{
return $this->belongsTo('App\Document', 'documentId');
}
}
If I dont set it in both classes, I get a MethodNotAllowedHTTP exception with no information about it. I have been able to create documents without problem, the problem comes when I need to update. The edit page for DocumentA has a form starting like this
{{ $document }}
{!! Form::model($project->document, [
'class'=>'form-horizontal',
'method' => 'PATCH',
'route' => ['projects.documents.update', $project, $project->document]
]) !!}
Now when I output $document above, I get the correct document that I am working on, as I should do. However, in the update function, if I output $document on its own or if I do
public function update(Request $request, Project $project, Document $document)
{
dd($project->document);
return null;
}
I see both DocumentA and DocumentB. Shouldnt the update only be passed DocumentA?
Why would this be? Any information or advice hugely appreciated.
Many thanks
I think the issue is the relationship between project and document. You probably have document belongsTo project, and project hasMany document, as you can have many documents with projectId = 1. Isn't it?
It what I said is okay, when you write $project->document, it brings you all the documents that belong to that project. It's confusing because you named the relationship 'document' instead of 'documents'.
You can do 2 things:
1- If each project can have only 1 document, change the relationship in the 'Project' model to hasOne Document. Then, if you do $project->document it will bring you only one.
2- If your app allows a project to have multiple documents, leave the relationship as hasMany (I'd recommend to rename it to documents instead of document), and pass the $document object to the update form, instead of passing the $project and trying to access the document from there.
Please let me know if I missed the point of your question and I'm totally wrong

laravel 5 update in database

I created a row in my 'movies' table called 'slug' where i want to store the slug of the titles of my movies.the problem is i already have 250 movies and i don't want to manually enter the slug to each one of them so i am trying to make a script to automatically update all the slugs.But i failed to do that:
This is my code in FilmController.php:
class FilmController extends Controller {
public function film()
{
$title = DB::table('movies')->select('title');
$slug = str_replace(" ","-",$title);
DB::table('movies')->update(array('slug' => $slug));
}
}
And this is in my routes:
Route::get('update','FilmController#film');
This is the error that pops up when i go to localhost/update:
Object of class Illuminate\Database\Query\Builder could not be converted to string
Can somebody tell me how could i change my code so i can put in my slug field in all the movies the title of the movie with '-' insted of space between the words?
$title is an object containing all titles, and not a string,so str_replace will not work on it
you can try using a loop to update each record according to its title
something like
$titles = DB::table('movies')->select('title','id')->get();
foreach ($titles as $title){
$slug = str_replace(" ","-",$title->title);
DB::table('movies')->where('id',$title->id)->update(array('slug' => $slug));
}
I recomend use a seeder if you want to make a script that update or create default info on your database.
Laravel Database Seeding doc
And title have a collection of titles not a single title.

Laravel 4 - Check if a database value is true

Im running Laravel 4 for my app ... Im a newbie.
I have created a small little application using the standard built in authentication and everything is working fine.
I have the User.php model and the routes file taking care of all my requests.
What i want to do, is add administrators, i have added a field in my users table which is named 'is_admin' .. its an integer of 1 or 0.
What i want to be able to do is something like the following
if is_admin() {
// Do stuff here if im an admin
}
Can anyone help me out with how i can achieve that .. All i have at the moment is a database column.
Cheers,
Actually you may check if the user is an admin ot not using this:
if(Auth::user()->is_admin) {
//...
}
Because Auth::user() returns the currently logged in user and is_admin field is available in the users table so if a user is logged in then you may simply check by checking the Auth::user()->is_admin property of the logged in user model. If a user is admin then the value is 1 and this will be true and for 0 result will be false in the if condition.
If you want to add a method in the user model then you may try this way:
public function isAdmin()
{
return $this->is_admin;
}
So you may check like:
$user = User::find(1);
if($user->isAdmin()) {
//...
}
$val = (bool)DB::table(DB::raw('DUAL'))->whereExists(function($query) use ($userId)) {
$query->from = 'users';
$query->where('id', $userId)->where('is_admin', 1)->select(DB::raw(1));
})->first([DB::raw(1)]);
This will run a SELECT 1 FROM DUAL WHERE EXISTS (SELECT 1 FROM users WHERE id = X and is_admin = 1 query which will return a boolean if the row exists or not.
DUAL is a dummy table in MySQL and used so we don't have to go trough a table. DB::raw(1) is used as we don't need to fetch column data for this, we just want true/false.
If you're already logged and you're using Laravels Auth you can just do as #WereWolf mentioned.

Resources