undefined variable stopping if else statement from working - laravel

In my app, users can create personal 'groups'. Each user has a user profile and I show the groups that they've created on their profile like this {{ ucwords(trans($groupCreated->group_title)) }} which works great.
I want their group title to be inside a green box, and to show a grey box if no groups have been created by the user.
Here's the full code for the green box:
#foreach($user->groupsCreated as $groupCreated)<div class="alert alert-success" role="alert"> {{ ucwords(trans($groupCreated->group_title)) }}</div>#endforeach
Here's what I want to 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> -->
Here's my if else statement to make this happen:
#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">
{{ ucwords(trans($groupCreated->group_title)) }}
</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
The error I get is Undefined variable: groupCreated
Here is my 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!');
}
}
and the Group Model
<?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();
}
}
So, I added the following to Model
/**
* Fetch the groups created by user
*/
public function groupCreated()
{
return $this->groupCreated()->where('groups.show', auth()->id());
}
But the error is:
Undefined variable: groupCreated
Any help?

The problem is probably #if ($groupCreated()). What is this line supposed to do?
If you just want to check if the user has any groups you can use #if ($user->groupsCreated->count() > 0).

Related

How to check if many-to-many relation already exists in create and update

Every time I create a new book or update it with the same author, a new instance of the same author creates in DB
This is my codes here
Here is the BooksController
<?php
namespace App\Http\Controllers;
use App\Models\Author;
use App\Models\Book;
use Illuminate\Http\Request;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$books = Book::orderBy('created_at', 'desc')->with('authors')->paginate(5);
return view('books.index', [
'books' => $books
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('books.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'author_name' => 'required',
'title' => 'required',
'release_year' => 'required|numeric',
'status' => 'required',
]);
I think I need to check here
// check if author already exists..
$authors = Author::all();
foreach($authors as $a){
if($a->name == $request->input('author_name')){
$author = $a;
}else{
}
}
Here if I have Glukhovski in the database and create a new book with the same author, another Glukhovski is added in the database, so I think there must be a way to check and if the author already exists, assign it to the book through the pivot table?
$author = Author::create([
'name' => $request->input('author_name')
]);
$book = Book::create([
'title' => $request->input('title'),
'release_year' => $request->input('release_year'),
'status' => $request->input('status')
]);
$book->authors()->attach($author->id);
return redirect('/books');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$book = Book::find($id);
return view('books.show')->with('book', $book);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$book = Book::find($id);
return view('books.edit')->with('book', $book);
}
/**
* 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([
'author_name' => 'required',
'title' => 'required',
'release_year' => 'required',
'status' => 'required',
]);
... and here as well
// check if author already exists.....
//
$author = Author::create([
'name' => $request->input('author_name')
]);
$book = Book::find($id);
$book -> update([
'title' => $request->input('title'),
'release_year' => $request->input('release_year'),
'status' => $request->input('status')
]);
$book->authors()->sync($author->id);
return redirect('/books');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
Book::find($id)->delete();
return redirect('books');
}
}
Pivot table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAuthorBookTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('author_book', function (Blueprint $table) {
$table->id();
$table->foreignId('author_id');
$table->foreignId('book_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('author_book');
}
}
you can check first for author in this way before you create the author, if author doesn't exist, it will create a new one
$author = Author::where('name',$request->input('author_name'))->first();
if(!$author){
$author = Author::create([
'name' => $request->input('author_name')
]);
}

Separate user logins all behave as one user?

I'm using Laravel 6 and currently users can login and submit a Group which get's stored in the database.
I've just noticed that if I create a fresh Group for, say user#1 .. and then logout and register as user#2, I see the same Group for both users.
Somehow the Groups CRUD has globalized to all users?
I've tried to go through the code but can't see where this has gone wrong. It was all working last week!
GroupController.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::all();
return view('groups/index', 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);
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!');
}
}
Groups index page
<tbody>
#foreach($groups as $group)
<tr>
<td>{{$group->created_at->format('d M, Y')}}</td>
<td>{{$group->group_title}}</td>
<td>Members</td>
<td>Image link</td>
<td>
Edit
</td>
<td>
<form action="{{ route('groups.destroy', $group->id)}}" method="post">
#csrf
#method('DELETE')
<button class="btn btn-sm btn-danger" type="submit">Delete</button>
<!-- fas fa-trash fa-fw text-danger -->
</form>
</td>
</tr>
#endforeach
</tbody>```
Get the groups that belongs to the authenticated user
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$groups = auth()->user()->groups;
return view('groups.index', compact('groups'));
}
Provided a relationship setup in your app/User.php model
public function groups()
{
return $this->hasMany('App\Group');
}
And a migration for groups table like this
Schema::create('groups', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('group_title');
$table->text('group_description');
$table->date('group_date');
$table->time('group_time');
$table->timestamps();
});
Given you specify which user created the group
/**
* 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_created = Group::create([
'user_id' => auth()->id(),
'group_title' => $request->get('group_title'),
'group_description' => $request->get('group_description'),
'group_date' => $request->get('group_date'),
'group_time' => $request->get('group_time'),
]);
if ($group_created) {
return redirect('/groups')->with('success', 'Group saved!!');
}
return redirect('/groups')->with('failed', 'Could not create group');
}

How to implement many to many nova resource without building custom tool

I am currently building a timetable generation system, I have these models below which are Subject and Teacher as the two main models with their nova resources, I have created a pivot model SubjectAllocation (has a nova resource) with a pivot table subject_allocations with fields teacher_id and subject_id. I would like to be able to use SubjectAllocation nova resource to select a teacher and allocate multiple subjects to this teacher but currently, I have no lack of it. Tried pulling in this package dillingham/nova-attach-many to attach to the SubjectAllocation model and this package to pick teachers records sloveniangooner/searchable-select but it cannot store data in the pivot table.
Subject Allocation Resource
<?php
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Http\Requests\NovaRequest;
use NovaAttachMany\AttachMany;
use Sloveniangooner\SearchableSelect\SearchableSelect;
class SubjectAllocation extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'App\SubjectAllocation';
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
SearchableSelect::make('Teacher', 'teacher_id')->resource("teachers"),
AttachMany::make('Subjects')
->showCounts()
->help('<b>Tip: </b> Select subjects to be allocated to the teacher'),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
Fields Methods in Subject Resource
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Subject Name', 'name')
->withMeta(['extraAttributes' => ['placeholder' => 'Subject Name']])
->sortable()
->creationRules('required', 'max:255', 'unique:subjects,name')
->updateRules('required', 'max:255'),
Text::make('Subject Code', 'code')
->withMeta(['extraAttributes' => ['placeholder' => 'Subject Code']])
->sortable()
->creationRules('required', 'max:255', 'unique:subjects,code')
->updateRules('required', 'max:255')
,
Textarea::make('Description')
->nullable(),
BelongsToMany::make('Teachers'),
];
}
Fields method in Teacher Resource
public function fields(Request $request)
{
return [
ID::make()->sortable(),
BelongsTo::make('User')
->searchable(),
Text::make('First Name', 'first_name')
->withMeta(['extraAttributes' => ['placeholder' => 'First Name']])
->sortable()
->rules('required', 'max:50'),
Text::make('Middle Name', 'middle_name')
->withMeta(['extraAttributes' => ['placeholder' => 'Middle Name']])
->sortable()
->nullable()
->rules('max:50'),
Text::make('Last Name', 'last_name')
->withMeta(['extraAttributes' => ['placeholder' => 'Last Name']])
->sortable()
->rules('required', 'max:50'),
Text::make('Teacher Code', 'teacher_code')
->withMeta(['exraAttributes' => [ 'placeholder' => 'Teacher Code']])
->sortable()
->creationRules('required', 'max:50', 'unique:teachers,teacher_code')
->updateRules('required', 'max:50'),
BelongsToMany::make('Subjects'),
];
}
Any suggestion on how I can make it work or a better solution, would appreciate very much
Without build custom tool, use following method:
// app\Nova\SubjectAllocation.php
public function fields(Request $request)
{
return [
ID::make()->sortable(),
// SearchableSelect::make('Teacher', 'teacher_id')->resource("teachers"),
SearchableSelect::make('Teacher', 'teacher_id')->resource(\App\Nova\Teacher::class)
->displayUsingLabels(),
AttachMany::make('Subjects','subject_id')
->showCounts()
->help('<b>Tip: </b> Select subjects to be allocated to the teacher')
->fillUsing(function($request, $model, $attribute, $requestAttribute) {
$a = json_decode($request->subject_id, true);
$teacher = \App\Teacher::find($request->teacher_id);
if(count($a)==0){
// Error processing because no subject is choosen
}else if(count($a)==1){
$model['subject_id'] = $a[0];
}else{
$model['subject_id'] = $a[0];
array_shift ($a); // Remove $a[0] in $a
$teacher->subjects()->sync(
$a
);
}
})
];
}

Showing posts from specific user in Laravel

I have a question about showing posts from specific user. I'm building a basic keeping records website for my brothers company. I made a redirected login for normal users(workers in company) and for admin(company manager). So I'm new at Laravel and programming, a did everything for this website and all I need is how to show posts on admin profile for specific user. On admin profile I'll make pages for all workers profiles and on specific page I need to show posts for that specific user. How can I do that? Making new Controller?
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$post = Post::all();
return view('posts.tabela')->with('posts', $post);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'br_kesice' => 'required',
'ime' => 'required',
'br_telefona' => 'required',
'posao' => 'required',
'cijena' => 'required',
'placanje' => 'required',
'popust' => 'required',
'datum_preuz' => 'required',
'datum_izdav' => 'required',
'smjena' => 'required',
'radnik' => 'required',
'status' => 'required'
]);
$post = new Post;
$post->br_kesice = $request->input('br_kesice');
$post->ime = $request->input('ime');
$post->br_telefona = $request->input('br_telefona');
$post->posao = $request->input('posao');
$post->cijena = $request->input('cijena');
$post->placanje = $request->input('placanje');
$post->popust = $request->input('popust');
$post->datum_preuz = $request->input('datum_preuz');
$post->datum_izdav = $request->input('datum_izdav');
$post->smjena = $request->input('smjena');
$post->radnik = $request->input('radnik');
$post->status = $request->input('status');
$post->user_id = auth()->user()->id;
$post->save();
return redirect('/home');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Post::find($id);
if(auth()->user()->id !==$post->user_id){
return redirect('/posts')->with('error', 'Nedozvoljen pristup!');
}
return view('posts.edit', compact('post', 'id'))->with('post', $post);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'br_kesice' => 'required',
'ime' => 'required',
'br_telefona' => 'required',
'posao' => 'required',
'cijena' => 'required',
'placanje' => 'required',
'popust' => 'required',
'datum_preuz' => 'required',
'smjena' => 'required',
'radnik' => 'required',
'status' => 'required'
]);
$post = Post::find($id);
$post->br_kesice = $request->input('br_kesice');
$post->ime = $request->input('ime');
$post->br_telefona = $request->input('br_telefona');
$post->posao = $request->input('posao');
$post->cijena = $request->input('cijena');
$post->placanje = $request->input('placanje');
$post->popust = $request->input('popust');
$post->datum_preuz = $request->input('datum_preuz');
$post->datum_izdav = $request->input('datum_izdav');
$post->smjena = $request->input('smjena');
$post->radnik = $request->input('radnik');
$post->status = $request->input('status');
$post->save();
return redirect('/home');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Post extends Model
{
protected $table = 'posts';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
}
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Post;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts(){
return $this->hasMany('App\Post');
}
public function is_admin(){
if($this->admin)
{
return true;
}
return false;
}
}

ErrorException in SessionGuard.php | Getting error when trying to register user while creating new order

I want user to register and also buy a package. To do that I took input for registration details and package details. Now when I'm processing order to save package details in session and register, I get this error : Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\View\View given, called in C:\xampp\htdocs\rename\app\Traits\OrderRegister.php on line 63 and defined. I'm using an trait to register user and return back to function when registration is complete.
OrderController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Package;
use App\ListingType;
use Illuminate\Support\Facades\Auth;
use App\Order;
use Carbon\Carbon;
use App\Traits\OrderRegister;
class OrderController extends Controller
{
use OrderRegister;
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index($type)
{
$listingtype = ListingType::where('type', '=', $type)->first();
if ($listingtype) {
$packages = $listingtype->packages()->get();
return view('packages.index', compact('packages'));
}
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
$package = Package::where('id', '=', $id)->first();
if (Auth::check()) {
return view('order.create_loggedin', compact('package'));
}
else {
return view('order.create_register', compact('package'));
}
}
/**
* Process a new order request. Store order values in session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function process(Request $request)
{
$order = ['package_id' => $request->package_id, 'order_qty' => $request->no_of_listing];
session(['order' => $order]);
if (Auth::guest()) {
return $this->register($request); // need to check session for orders available in OrderRegister trait.
}
return $this->store($request);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if($request->session()->has('order')) {
$package = Package::where('id', '=', $request->package_id )->first();
if($request->user() == Auth::user()) {
for( $n=1;$n<=$request->no_of_listing;$n++) {
$order = new Order;
$order->package_id = $request->package_id;
$order->user_id = Auth::user()->id;
$order->expire_at = Carbon::now()->modify('+'.$package->duration_in_months.' months');
$order->save();
}
return redirect('/');
}
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
trait : OrderRegister.php
<?php
namespace App\Traits;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
trait OrderRegister
{
use RedirectsUsers;
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'username' => 'required|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
$user->profile()->save(new UserProfile);
return $user;
}
/**
* Execute the job.
*
* #return void
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));
return $this->store($request);
}
/**
* Get the guard to be used during registration.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
I could not find any solution for this error so created my own thread for the first time please someone help.
It throws an error because you are trying to login a vue.
in your OrderController.php you are using create method which return a view.
this method will override the create method on your trait.
So you have something like this :
Auth::guard($this->getGuard())->login(/* A view */);
you can at least rename the method on the trait from create to createUser for example.
then you call it from the guard like this :
Auth::guard($this->getGuard())->login($this->createUser($request->all()));

Resources