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

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')
]);
}

Related

I have an idea to use auth middleware to retrieve a user's products

i have an idea to use auth middleware to retrieve a user's products but currently i am not able to retrieve that user's products. Instead, it listed all the products of other users. Can you guys give me some ideas to help me complete it. Thank you !!!
This is my ProjectController code:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProjectResource;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::all();
return response([
'projects' => ProjectResource::collection($projects),
'message' => 'Retrieved successfully'
], 200);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
// 'uuid' => 'required|unique:projects',
'user_id' => 'required',
'name' => 'required|max:255',
'status' => 'required',
]);
if ($validator->fails()) {
return response(['error' => $validator->errors(), 'Validation Error']);
}
$projects = Project::create($data);
return response(['projects' => new ProjectResource($projects), 'message' => 'Created successfully'], 201);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
return response(['project' => new ProjectResource($project), 'message' => 'Retrieved successfully'], 200);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
$project->update($request->all());
return response(['project' => new ProjectResource($project), 'message' => 'Update successfully'], 200);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return response(['message' => 'Deleted'], 204);
}
}
This is my ProjectModel code:
<?php
namespace App\Models;
use App\Enums\ProjectStatus;
use App\Http\Traits\Uuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Project extends Model
{
use HasFactory;
use Uuid;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'status',
'user_id',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'id',
'uuid',
];
protected $cast = [
'status' => ProjectStatus::class
];
public function setUuidAttribute()
{
$this->attributes['uuid'] = Str::uuid();
}
}
This is my API Router code:
You have to retrieve the user first in order to filter the products. There are multiple ways to do that. Here's a link to Laravel's documentation on the subject: https://laravel.com/docs/8.x/authentication#retrieving-the-authenticated-user
You also have to filter your query (your query being Project::all()) so that it only retrieves the products for the user. Here's a link to some Laravel documentation related to that: https://laravel.com/docs/8.x/eloquent#retrieving-models
In the end, replacing this $projects = Project::all(); with this $projects = Project::where('user_id', auth()->user()->id); should do the trick.
Try this
public function index()
{
$projects = Project::where('user_id', auth()->id())->get();
return response([
'projects' => ProjectResource::collection($projects),
'message' => 'Retrieved successfully'
], 200);
}

Trying to store and edit product for specific user id

Here I am trying to store and edit the product for a specific id. Wher a user can have some product and those products can be edit for this specific user. I have tried to do this but don't know what`s the problem is happening. can someone help me. Thanks in advance
this is my ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::latest()->paginate(20);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 5) - 1) * 5);
}
function authapi(Request $request)
{
$user = User:: where('email', $request->email)->first();
if(!$user || !Hash::check($request->password, $user->password)){
return response([
'message' => ['These credentials do not match our records.']
],404);
}
$token = $user -> createToken('my-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response,201);
}
function all_app_jsons(){
return Product::all();
}
function search_by_name($name){
return Product::where('name','like','%'.$name.'%')->get();
}
function search_by_id($id){
return Product::where('id',$id)->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//$tag = Product::create($request->all());
//return redirect()->route('admin.tags.index');
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:1024',
]);
$input = $request->all();
// $request->validated();
$input['user_id'] = auth()->user()->id;
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}
Product::create($input);
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
// public function update(Request $request, Product $product)
public function update(Request $request, $productId)
{
$product = auth()->user()->products()->findOrFail($productId);
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}else{
unset($input['logo']);
}
$product->update($input);
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
// function indextwo(){
// //return DB::select("select * from products");
// //DB::table('products')->orderBy('id','desc')->first();
// return Product::orderBy('id', 'DESC')->first();
// }
}
in ProductController.php $product = auth()->user()->products()->findOrFail($productId); in this line said products() id undefined
this is my model Product.php
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function user(){
return $this->belongsTo(User::class);
}
}
This is my User.php model
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* 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',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function products(){
return $this->hasMany(Product::class);
}
}
This is product table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
});
Schema::table('products', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users');
});
}
Note: I can store many products but not for specific users. I can store and edit product every user can access it. But I want a specific user will have some product where other user cant acess
$table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade');
I userd This on projects table

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