Variable not defined in view in laravel 4 - laravel-4

I've just started to learn laravel. These are the steps i'm following:.
Created a route in routes.php
Created two files in view folder and connected them using yield() and extends().
Created a model in models folder
I'm trying to fetch data from a table named as registrations but it's saying variable not defined
(ErrorException:
Undefined variable: userdata (View: /var/www/laravel/app/views/registrations.blade.php)
)
this is the description of table:
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| email | varchar(255) | NO | UNI | NULL | |
+-------+------------------+------+-----+---------+----------------+
This is the routes.php file
<?php
Route::get('registrations', function(){
$userdata = registration::all();
return View::make('registrations')->with('registrations', $userdata);
});
this is registrations.blade.php located in views folder
#extends('layout')
#section('content')
#foreach($userdata as $data)
<p>{{ $data->name }}</p>
#endforeach
#stop
this is layout.blade.php located in views folder
<!DOCTYPE HTML>
<html>
<head>
<title></title>
</head>
<body>
<h1>layout</h1>
#yield('content')
</body>
</html>
this is the registration.php file located in models folder
<?php
class registration extends Eloquent {};
?>
i'm unable to find the exact problem

In your controller you pass the $userdata collection received from your model as 'registrations', so your view will receive this collection as $registrations.
So from what I can see in your question, the following should work:
#extends('layout')
#section('content')
#foreach($registrations as $data)
<p>{{ $data->name }}</p>
#endforeach
#stop

Related

laravel 6 calling post route to return to the same page for sorting table

I am trying to create a table which the user can sort
I created the following two routes
route::get('/manager', 'Manager\DeadlineController#index')->middleware(['auth', 'auth.manager'])->name('manager.index');
route::post('/manager/{name_id}', 'Manager\DeadlineController#sortByName')->middleware(['auth', 'auth.manager'])->name('manager.sortByName');
from my php artisan route:list
| | GET|HEAD | manager | manager.index | App\Http\Controllers\Manager\DeadlineController#index | web,auth,auth.manager |
| | POST | manager/{name_id} | manager.sortByName | App\Http\Controllers\Manager\DeadlineController#sortByName | web,auth,auth.manager |
and set up my controller as follows
public function index()
{
return view('deadline.index')
->with([
'modules' => Module::all(),
'name_id' => 0
]);
}
public function sortByName($name_id){
if($name_id == 0){
$sortedModule = Module::orderBy('name', 'DESC')->get();
}
else{
$sortedModule = Module::orderBy('name', 'ASC')->get();
}
return view('deadline.index')
->with([
'modules' => $sortedModule,
'name_id' => 1
]);
}
in my view i use the following link to sort
<th scope="col">NAME</th>
but when i use this link in my view I am somehow redirected to my GET route because i get the following error
The GET method is not supported for this route. Supported methods: POST.
What am I missing or doing wrong? Any help or tips will be appreciated. Please ask if I need to provide more details
Update
I change the link in my view to a form tag with a submit button and now it works
<th scope="col">
<form action="{{ route('manager.sortByName', $name_id) }}" method="POST">
#csrf
<button type="submit">NAAM</button>
</form>
</th>
When you click on <a> tag it does GET request, so you need to change your route from POST to GET, also returning view as a response to post method is not good idea,the best solution is GET route

Laravel 5.8 isAdmin Gate?

I'm learning how to use the Gate and #can stuff
in my AuthServiceProvider I have
public function boot()
{
$this->registerPolicies();
$this->registerPostPolicies();
}
public function registerPostPolicies()
{
Gate::define('isAdmin', function($user) {
return $user->roles->where('title', 'like', '%' . 'Admin')->count();
});
}
and in my blade I have
...
#can('isAdmin')
<a aria-disabled="false" href="{{ route('admin.home')}}" target="_self" class="dropdown-item" role="menuitem" ><i class="fa fa-upload"></i> Admin Menu</a>
#endcan
...
For roles I have
| id | title |
+----+-------------+-
| 1 | Admin |
| 2 | User |
| 3 | Group Admin |
| 4 | Site Admin |
+----+-------------+-
Which is why the like %Admin query...
but what I am finding is that the gate doesn't seem to work.. it simply blocks everyone.. I want to enable the Admin menu for anyone with a role title that has Admin in it..
Any suggestions?
You should be using $user->roles() with brackets instead to indicate you are querying from database.
return $user->roles()->where('title', 'like', '%' . 'Admin')->count();
Without (), it has become Collection and you cannot use LIKE with where() when filtering a collection. Refer Collections - Laravel Docs

display data from multiple tables and foreign keys in laravel

I have two tables :
bonhomme
+----+--------------+
| id | name |
+----+--------------+
| 1 | Alec Badwin |
| 2 | Maria Quiban |
+----+--------------+
serie
+----+---------------+
| id | name |
+----+---------------+
| 1 | 30 Rock |
| 2 | Good Day L.A. |
+----+---------------+
I have another one called : serie_personnage
+----+-------------+----------+--------------+
| id | bonhomme_id | serie_id | personnage |
+----+-------------+----------+--------------+
| 1 | 1 | 1 | Jack Donaghy |
| 2 | 2 | 2 | Maria Quiban |
+----+-------------+----------+--------------+
I want to display the personnage from serie_personnage and link it in my blade with the name of the bonhomme (in my table bonhomme) associated.
In other words, I want a table in my blade with rows where there is in column 1, the name of the bonhomme and in column 2, the personnage associated.
How can I do that with the relationships in Laravel ? I've tried it but it's not working well.
Controller
public function show($id)
{
$serie = Serie::where('id', $id)->first();
return view('admin.series.castings.show')->withSerie($serie);
}
Model - Serie
public function personnages()
{
return $this->hasMany('App\Models\Admin\SeriePersonnage');
}
public function acteurs()
{
return $this->belongsToMany('App\Models\Admin\Bonhomme', 'serie_personnage', 'serie_id', 'bonhomme_id');
}
Blade
<tbody>
#foreach($serie->acteurs as $acteur)
#foreach($serie->personnages as $personnage)
<tr>
<td>{{ $acteur->nom }}</td>
<td>{{ $personnage->personnage }}</td>
<td>bla</td>
<td>{{ $personnage->rang }}</td>
<td class="has-text-right">
<a class="button is-outlined" href="{{ route('series.show', $serie->id) }}">
Voir
</a>
<a class="button is-outlined" href="#">Editer</a>
</td>
</tr>
#endforeach
#endforeach
</tbody>
My Table in view
I have to help you as French developer as-well! First of all, I would change your controller for a more simple way to get the Serie :
public function show($id)
{
$serie = Serie::findOrFail($id);
return view('admin.series.castings.show')->withSerie($serie);
}
EDIT: I use Model::findOrFail($id); because it throws a Illuminate\Database\Eloquent\ModelNotFoundException. If you don't catch the exception, Laravel will automatically send a 404 HTTP response. It prevent the user to have an error using an obsolete link. See the doc for more informations.
Then I don't think it is a good idea to use foreach loop twice... I would rather use only one foreach loop on the personnages. Then, I would get the actor of the character from the Personnage model. It should looks like the code below:
App\Models\Admin\SeriePersonnage.php
<?php
namespace App\Models\Admin;
use App\Models\Admin\Bonhomme;
use Illuminate\Database\Eloquent\Model;
class SeriePersonnage extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
//Whatever you want to put here
];
/**
* Gets the actor of the character
*/
public function actor() {
return $this->belongsTo(Bonhomme::class);
}
}
Then in your blade view:
<tbody>
#foreach($serie->personnages as $personnage)
<tr>
<td>{{$personnage->actor->nom}}</td>
<td>{{$personnage->personnage}}</td>
<td>bla</td>
<td>{{$personnage->rang}}</td>
<td class="has-text-right"><a class="button is-outlined" href="{{route('series.show', $serie->id)}}">Voir</a> <a class="button is-outlined" href="#">Editer</a></td>
</tr>
#endforeach
</tbody>
You might also add a personnages() methods in your actor model so that you would be able to get all the characters this actor is playing.
Also I would advice you to use English words for variable names, class names and in fact every word in your code, especially if you post for help on English websites. I would also recommend you to change SeriePersonnage to only Personnage if you only manage series (you might also handle movies, Japanese Anime etc, in this case you can ignore my message). Also it would be great to change the row name of serie_personnage from personnage to nom.
Hope it helped you and I didn't do mistakes :P

Nesting Comments Yii2

I have a comment table, like below:
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | | NULL | |
| parent_id | int(11) | NO | | 0 | |
| post_id | int(11) | NO | | NULL | |
| body | text | NO | | NULL | |
| date | datetime | NO | | NULL | |
| status | tinyint(1) | NO | | 0 | |
+-----------+--------------+------+-----+---------+----------------+
Comment parent_id by defautl is 0, if comment is answered, parent id insert in parent_id column.
And make a relation with User Table with below code:
public function getPosts()
{
return $this->hasMany(Post::className(), ['category_id' => 'id']);
}
How can i show nesting?
First, you need to define the relation inside your Comment model class:
public function getChildComments()
{
return $this->hasMany(self::className(), ['parent_id' => 'id']);
}
That defines the entity relationship to itself. I think it is always good to also keep related logic or handlers into helper/callable methods in the same class in a way that doesn't require having to load them all at once from database. What comes next should answer the question:
How can i show nesting?
CASE01: Inside a RESTFul application
Simply override fields() inside Comment class to always output child comments:
public function fields()
{
$fields = parent::fields();
$fields['childs'] = 'childComments';
return $fields;
}
That's it. yii\rest\Serializer should take care of the recursive representation and you'll get something similar to this when outputting a list of comments:
CASE02: Inside a HTML web view
There is probably many ways to achieve it. The easiest and cleanest way I could think of is to tie on the template engine that Yii is already using to re-render the view holding child comments in a recursive way. As a working example, add something like what follows to your index.php file:
<?php
use yii\helpers\Html;
use yii\widgets\ListView;
use yii\data\ActiveDataProvider;
use app\models\Comment;
?>
<?= ListView::widget([
'dataProvider' => new ActiveDataProvider([
'query' => Comment::find(),
]),
'itemView' => '_comment',
'itemOptions' => ['style' => 'padding: 10px 50px; border: 1px solid red'],
]); ?>
Then create that _comment.php file:
<?php
use yii\helpers\Html;
use yii\widgets\ListView;
use yii\data\ActiveDataProvider;
?>
<div style="background-color: skyblue; padding: 5px 15px">
<h4><?= Html::encode($model->id) ?></h4>
<p><?= Html::encode($model->name) ?></p>
</div>
<?php
if ($model->getChildComments()->count()) {
echo ListView::widget([
'dataProvider' => new ActiveDataProvider([
'query' => $model->getChildComments(),
]),
'itemView' => '_comment',
'itemOptions' => ['style' => 'padding: 10px 0 10px 50px; border: 1px dotted blue'],
]);
}
?>
The template will create a new instance of itself each time it finds childComments linked to the represented one. With that bit of CSS paddings to show the nesting, that code should output this:

Laravel 5 Eloquent relationship get the data

I have two table.
(Persons)
+------+------+
| id | name |
+------+------+
| 1 | John |
+------+------+
| 2 |Albert|
+------+------+
(Motors)
+------+------+------+
| id | name | age |
+------+------+------+
| 1 | 1 | 20 |
+------+------+------+
| 2 | 2 | 21 |
+------+------+------+
| 3 | 1 | 20 |
+------+------+------+
In "motors.name" i have the ids of people.
I have two models.
(Motors)
class Motors extends Eloquent
{
public function person(){
return $this->hasMany('App\Persons', 'id');
}
}
(Persons)
class Persons extends Eloquent
{
protected $table = 'persons';
public function motors(){
return $this->belongsTo('App\Motors', 'name', 'id');
}
}
1 controller
class PrototypeController extends Controller
{
public function names(Request $request) {
$res = Motors::get()->person->name;
return view('pages.prototype', compact('res'));
}
}
1 view
<ul class="list">
#foreach ($res as $row)
#if (!empty($row->name))
<li class="list-group-item">
{!! $row->name !!}
</li>
#endif
#endforeach
</ul>
I'd like tosee the rerelational dara in view, not the ids. How can it be solved?
This code isn't good:
$res = Motors::get()->person->name;
Thanks in advance for your help.
Let me try to answer this. You should try to follow conventions to make it easier to work with Laravel.
Your motors.name column should be called person_id. Your model for motors table should be called Motor.php (singular of motors). The same for persons table, Person.php.
In your Motor.php file, your relationship will be:
public function person(){
return $this->belongsTo('App\Person');
}
If you follow conventions, you don't need to add the second parameter to the relationship name. Note that I put App\Person, you should have App\Persons if you decide to maintain the file naming you are using.
In your Person.php file, your relationship will be:
public function motors(){
return $this->hasMany('App\Motor');
}
Your foreach will be:
#foreach ($res as $row)
#if (!empty($row->person))
<li class="list-group-item">
{!! $row->person->name !!}
</li>
#endif
#endforeach
Note how I check:
#if (!empty($row->person))
and not:
#if (!empty($row->person->name))
It has to be done like this, because if $row->person is null, it will throw an error when you do $row->person->name

Resources