В моем приложении пользователи могут создавать личные «группы». У каждого пользователя есть user profile
, и я показываю группы, которые они создали, в своем профиле, например, {{ ucwords(trans($groupCreated->group_title)) }}
, который прекрасно работает.
Я хочу, чтобы заголовок их группы находился внутри зеленого прямоугольника и отображалсясерое поле, если пользователь не создал ни одной группы.
Вот полный код зеленого поля:
@foreach($user->groupsCreated as $groupCreated)<div class="alert alert-success" role="alert"><a href="{{ route('groups.show',$groupCreated->id)}}"> {{ ucwords(trans($groupCreated->group_title)) }}</a></div>@endforeach
Вот что я хочу показать, если группы не созданы:
<!-- <small id="emailHelp" class="form-text text-muted pb-3">Deleted groups are not shown</small>
<div class="alert alert-secondary" role="alert">
This user has no active groups</div> -->
Вот мой оператор if
else
, чтобы это произошло:
@if ($groupCreated())
<small id="emailHelp" class="form-text text-muted pb-3">Deleted groups are not shown</small>
@foreach($user->groupsCreated as $groupCreated)
<div class="alert alert-success" role="alert">
<a href="{{ route('groups.show',$groupCreated->id)}}"> {{ ucwords(trans($groupCreated->group_title)) }}</a>
</div>
@endforeach
@else
<!-- Show if no groups created -->
<!-- <small id="emailHelp" class="form-text text-muted pb-3">Deleted groups are not shown</small>
<div class="alert alert-secondary" role="alert">
This user has no active groups</div> -->
@endif
Я получаю ошибку: Undefined variable: groupCreated
Вот мой GroupController.php
<?php
namespace App\Http\Controllers;
use App\Group;
use Illuminate\Http\Request;
// All Groups pages require login except 'show'
class GroupsController extends Controller
{
public function __construct()
{
$this->middleware('auth', ['except' => 'show']);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$groups = Group::where('created_by_user_id', auth()->id())->get();
return view('groups/index', compact('groups'));
}
/**
* Store the group that a user has joined in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function join(Request $request)
{
$request->validate([
'group_id' => 'required',
]);
$user_id = auth()->id();
$group = Group::find($request->get('group_id'));
if (!$group->isLoggedInUserJoined())
$group->joinedUsers()->attach($user_id);
$redirect = $request->get('redirect', 'groups/joined');
return redirect($redirect)->with('success', 'You joined the group!!');
}
/**
* Remove the user from a group that they have joined in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function unjoin(Request $request)
{
$request->validate([
'group_id' => 'required',
]);
$group = Group::find($request->get('group_id'));
if ($group->isLoggedInUserJoined())
$group->joinedUsers()->detach(auth()->id());
$redirect = $request->get('redirect', 'groups/joined');
return redirect($redirect)->with('success', 'You\'ve left the group.');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function joined()
{
//@todo change query to show groups joined
// $groups = Group::where('created_by_user_id', auth()->id())->get();
// $groups = Group::with('joinedUsers')
$groups = auth()->user()->groupsJoined()->get();
return view('groups/joined', compact('groups'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('groups.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'group_title' => 'required',
'group_description' => 'required',
'group_date' => 'required',
'group_time' => 'required',
]);
$group = new Group([
'group_title' => $request->get('group_title'),
'group_description' => $request->get('group_description'),
'group_date' => $request->get('group_date'),
'group_time' => $request->get('group_time'),
]);
$group->save();
return redirect('/groups')->with('success', 'Group saved!!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// $group = Group::find($id);
$group = Group::with('createdByUser')->where('id', $id)->first();
return view('groups.show', compact('group'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$group = Group::find($id);
return view('groups.edit', compact('group'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'group_title' => 'required',
'group_description' => 'required',
'group_date' => 'required',
'group_time' => 'required',
]);
$group = Group::find($id);
$group->group_title = $request->get('group_title');
$group->group_description = $request->get('group_description');
$group->group_date = $request->get('group_date');
$group->group_time = $request->get('group_time');
$group->save();
return redirect('/groups')->with('success', 'Group updated!');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$group = Group::find($id);
$group->delete();
return redirect('/groups')->with('success', 'Group deleted!');
}
}
и модель группы
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
protected $fillable = [
'group_title',
'group_description',
'group_date',
'group_time',
'created_by_user_id'
];
public static function boot()
{
parent::boot();
static::creating(function ($group) {
$group->created_by_user_id = auth()->id();
});
}
/**
* Get the user that created the group.
*/
public function createdByUser()
{
return $this->belongsTo(User::class, 'created_by_user_id');
}
/**
* Get the users that joined the group.
*/
public function joinedUsers()
{
return $this->belongsToMany(User::class, 'group_joined_user', 'group_id', 'user_id')
->withTimestamps();
}
/**
* Checks whether the currently logged in user is joined to the group.
*/
public function isLoggedInUserJoined()
{
return $this->joinedUsers()->where('users.id', auth()->id())->exists();
}
}
Итак, я добавил следующее в модель
/**
* Fetch the groups created by user
*/
public function groupCreated()
{
return $this->groupCreated()->where('groups.show', auth()->id());
}
Но ошибка:
Неопределенная переменная: groupCreated
Любая помощь?