how do i automatically generate string i want the string to increment every time i hit submit button for example i have string TEST0001,next should be TEST0002,TEST0003,TEST0004,untill the end.
Migration Table
public function up()
{
Schema::create('leads', function (Blueprint $table) {
$table->increments('id');
$table->string('generate_id');
$table->string('name')->nullable();
$table->timestamps();
});
}
Controller:
public function store(Request $request)
{
//
$this->validate($request, [
'generate_id'=>'required|Unique',
]);
$leads=new lead();
$leads->generate_id=$request->generate_id;
$leads->name=$request->name;
$leads->save();
return redirect()->route('leads.index')
->with('flash_message', 'Success.');
}
Related
I'm trying to make an app where airbnb hosts can have a log of their bookings, I created three models: Home, Guest and Booking. Booking being the main player, I also think there should be a pivot table but I'm not sure which models should it link... I decided to go with booking_guest but I'm getting the following error when I create a booking:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'booking_id' cannot be null (SQL: insert into `booking_guest` (`booking_id`, `guest_id`) values (?, 1), (?, 2))
I do something like this in my BookingController:
public function create(Request $request)
{
$guestIds = Guest::latest()->take(2)->pluck('id');
$home = Home::findOrFail(1);
$booking = new Booking();
$booking->home_id = $home->id;
$booking->guests()->attach($guestIds);
$booking->save();
return response()->json([
'booking' => $booking,
]);
}
I'm not feeling too sure about this configuration, could you guys share some light on me.
These are my models:
class Home extends Model
{
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'guest_home', 'home_id', 'guest_id');
}
public function bookings()
{
return $this->hasMany('App\Models\Booking');
}
}
class Booking extends Model
{
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'booking_guest', 'booking_id', 'guest_id');
}
}
class Guest extends Model
{
public function bookings()
{
return $this->belongsToMany('App\Models\Booking', 'booking_guest', 'guest_id', 'booking_id');
}
}
My migrations:
//Booking guest pivot table
Schema::create('booking_guest', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('booking_id')->index();
$table->foreign('booking_id')->references('id')->on('bookings')->onDelete('cascade')->onUpdate('cascade');
$table->unsignedInteger('guest_id')->nullable()->index();
$table->foreign('guest_id')->references('id')->on('guests')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
Schema::create('guests', function (Blueprint $table) {
$table->increments('id');
$table->string('fullName');
$table->text('country');
$table->timestamps();
});
Schema::create('bookings', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('home_id')->index();
$table->foreign('home_id')->references('id')->on('homes')->onDelete('cascade')->onUpdate('cascade');
$table->timestamp('entryDate')->nullable();
$table->timestamp('exitDate')->nullable();
$table->timestamps();
});
Schema::create('homes', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('host_id')->index();
$table->foreign('host_id')->references('id')->on('hosts')->onDelete('cascade')->onUpdate('cascade');
$table->string('fullAddress')->unique();
$table->integer('rooms')->unique();
$table->timestamps();
});
As you can see from here:
public function create(Request $request)
{
...
$booking = new Booking(); // <-- here
$booking->guests()->attach($guestIds); // <-- here
$booking->save(); // <-- here
...
}
you are creating a new instance of Booking, then associating to it a Guest and then saving the instance of Booking.
However ->attach(...) tries to associate the Booking with the Guest, but the Booking does not exists at that time on the DB.
I would suggest to use Booking::create, so that after that statement, the booking exists on the DB and so you can attach to it the Guest:
public function create(Request $request)
{
$guestIds = Guest::latest()->take(2)->pluck('id');
$home = Home::findOrFail(1);
$booking = Booking::create([ // <- using Booking::create
'home_id' => $home->id // <- using Booking::create
]); // <- using Booking::create
$booking->guests()->attach($guestIds);
return response()->json([
'booking' => $booking,
]);
}
In laravel, I have 3 table
User // for Authentication and Create Another User Once logged in
Expense
Shop
My Purpose- I want user can register and Also, can create another user when they logged in And Can assign user to another Shop as they want..
And Only User in the Same Shop Can see their Expense..
// My User Table
<pre>
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('shop_id')->nullable();
$table->unsignedBigInteger('user_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
</pre>
// My Expense Table
<pre>
Schema::create('expenses', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->date('date');
$table->string('description');
$table->double('amount');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
</pre>
// My Shop Table
<pre>
Schema::create('shops', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('expense_id')->nullable();
$table->unsignedBigInteger('user_id');
$table->string('name');
$table->string('description');
$table->timestamps();
$table->foreign('expense_id')->references('id')->on('expenses');
$table->foreign('user_id')->references('id')->on('users');
});
</pre>
// My User Model
<pre>
public function expense()
{
return $this->hasMany(\App\Expense::class);
}
public function shop()
{
return $this->hasMany(\App\Shop::class, 'user_id');
}
</pre>
// My Expense Model
<pre>
class Expense extends Model
{
protected $fillable = ['date', 'description', 'amount', 'user_id', 'shop_id'];
public function user()
{
return $this->belongsTo(\App\User::class);
}
}
</pre>
// My Shop Model
<pre>
class Shop extends Model
{
protected $fillable = ['name', 'description', 'expense_id', 'shop_id'];
public function user()
{
return $this->belongsTo(\App\User::class, 'user_id');
}
}
</pre>
// Expense Controller
<pre>
public function index(Request $request)
{
$expense = Expense::with(['user'])->get();
return ExpenseResource::collection($expense);
// dd(auth()->user());
}
public function create(Request $request)
{
$request->validate([
'date' => 'required',
'description' => 'required',
'amount' => 'required',
]);
$expense = new Expense();
$expense->user_id = auth()->user()->id;
$expense->date = $request->date;
$expense->description = $request->description;
$expense->amount = $request->amount;
$expense->save();
return new ExpenseResource($expense);
}
</pre>
// in My UserController
<pre>
public function index()
{
$users = User::all();
$shops = Shop::all();
return view('user', compact('users', 'shops'));
// return UserResource::collection($users);
}
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$user = new user();
$user->user_id = auth()->user()->id;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return new UserResource($user);
}
</pre>
Is it make sense?
Any idea, thanks..
As stated in the comments, you'll need to check the current User and constrain the returned Expense records to only those that 1) have a User and 2) match the same Store as the current User. This can be done in a single whereHas() clause:
public function index(Request $request) {
$user = auth()->user(); // If using default `Auth` logic.
$expenses = Expense::whereHas('user', function($subQuery) use($user){
return $subQuery->where('shop_id', '=', $user->shop_id);
})->with(['user'])->get();
return ExpenseResource::collection($expenses);
}
What ->whereHas() does is constrains the query fetching your Expense models to respect the logic you pass it, which in this case is only include Expense models that have a user that has the same shop_id as the currently logged in User.
Note:If the current User does not have a Shop, it might return unexpected results, but you could protect the route to only allow a User with a Shop to access it, etc.
I want to invalidate some inputs.I write these code in store method,but when I test my api on Postman give me 500 error.For example I don't give bodyfield in Body tab.
This is store function in my controller.
public function store(Request $request)
{
$validation=$this->getValidationFactory()->make($request->all(),[
'body'=>'required',
'image'=>'required|mimes:jpeg,png'
]);
if($validation->failed()){
return response()->json(['message'=>'Invalid Input Data!'],400);
}
$article=new Article();
$article->title=$request->title;
$article->body=$request->body;
$article->source=$request->source;
if($article->save()){
$article->categories()->sync($request->categories);
}
$name='article-'.$article->id.'.'.$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(public_path('images'),$name);
$article->image= $name;
$article->save();
return response()->json(['message'=>'save successfully'],200);
}
This is migration file for create article table.
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->text('body');
$table->boolean('is_active')->default(0);
$table->enum('status',['draft','completed','published'])->default('draft');
$table->timestamps();
});
}
And this is Postman screenshot.
I have a many-to-many relationship between my client and tag tables. A client can have many tags, and each tag can be related to multiple clients.
On the client show view, I'm trying to display the client info plus all tags associated to this client.
How do I change the query below to retrieve the client rows with all its related tags?
public function show($id)
{
$client = Client::findOrFail($id);
return view('clients.show')->with(['client' => $client]);
}
Client model
public function clienttag()
{
return $this->belongsToMany('App\Clienttag');
}
Clienttag model
public function client()
{
return $this->belongsToMany('App\Client');
}
Client_clientags table migration
public function up()
{
Schema::create('client_clienttag', function(Blueprint $table)
{
$table->integer('client_id')->unsigned();
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->integer('clienttag_id')->unsigned();
$table->foreign('clienttag_id')->references('id')->on('clienttags')->onDelete('cascade');
$table->timestamps();
});
}
Clients table migration
public function up()
{
Schema::create('clients', function(Blueprint $table)
{
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->rememberToken();
$table->timestamps();
});
}
Clienttags table migration
public function up()
{
Schema::create('clienttags', function(Blueprint $table)
{
$table->increments('id');
$table->string('tag');
$table->text('description');
$table->rememberToken();
$table->timestamps();
});
}
You can use "Eager Loading" methods like the following
public function show($id)
{
$client = Client::with('clienttag')->findOrFail($id);
return view('clients.show')->with(['client' => $client]);
}
Check documentation at http://laravel.com/docs/5.1/eloquent-relationships#eager-loading
Then at your view you can print your tags
#foreach ($client->clienttag as $tag)
{!! $tag->tagname!!} (or whatever your field in clienttags table name is)
#endforeach
I'm trying to make a feedback system where a user can only give one feedback per 'task'-item.
Currently one user can give as many feedbacks as he/she wants but ofcourse I want to limit this, seeing there is a rating behind it, ect..
Any help would be much appreciated!
Thanks
These are my models:
//Feedback
public function user()
{
return $this->belongsTo('App\User');
}
public function tnb()
{
return $this->belongsTo('App\Tnb');
}
//Tnb
public function user()
{
return $this->belongsTo('App\User');
}
public function feedbacks()
{
return $this->hasMany('App\Feedback');
}
// User
public function tnbs()
{
return $this->hasMany('App\Tnb');
}
public function feedbacks()
{
return $this->hasMany('App\Feedback');
}
My database tabels:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
Schema::create('tnb', function (Blueprint $table) {
$table->increments('id');
$table->string('type');
$table->string('name');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onCascade('update')->onDelete('cascade');
$table->integer('group_id')->unsigned();
$table->foreign('group_id')->references('id')->on('groups')->onCascade('update')->onDelete('cascade');
$table->string('desc');
$table->string('slug');
$table->date('startdate');
$table->time('starttime');
$table->date('enddate');
$table->time('endtime');
$table->timestamps();
});
Schema::create('feedbacks', function (Blueprint $table) {
$table->increments('id');
$table->string('score');
$table->string('feedback');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onCascade('update')->onDelete('cascade');
$table->integer('tnb_id')->unsigned();
$table->foreign('tnb_id')->references('id')->on('tnb')->onCascade('update')->onDelete('cascade');
$table->timestamps();
});
I've been trying a couple things in my controller but until now I'm not getting anywhere:
public function store(Request $request, Group $group, Tnb $tnb)
{
$user = auth()->user();
$feedback = new Feedback(
array(
'score' => $request->get('score'),
'feedback' => $request->get('feedback')
));
$feedback->user()->associate($user);
//dd($feedback->user()->whereId(Auth::user()->id)->count());
$tnb->feedbacks()->save($feedback);
\Flash::success('Your feedback has succesfully been sumbitted!');
return redirect()->back();
}
Found the solution!
public function store(Request $request, Group $group, Tnb $tnb)
{
$user = auth()->user();
$feedback = new Feedback(
array(
'score' => $request->get('score'),
'feedback' => $request->get('feedback')
));
$feedback->user()->associate($user);
foreach($user->feedbacks as $feedback)
{
if ($tnb->user_id == $user->id)
{
\Flash::error('You may not give a feedback on your own tasks and bookings!');
return redirect()->back();
if($feedback->user_id == $user->id)
{
\Flash::error('You have already posted a feedback!');
return redirect()->back();
}
}
}
$tnb->feedbacks()->save($feedback);
\Flash::success('Your feedback has succesfully been sumbitted!');
return redirect()->back();
}