How to validate the inputs from user in Laravel - php

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.

Related

How to use UUID instead of a slug for ticket

I am currently navigating to a ticket using the slug set by the title example blah-blah-blah and want to use uuid instead of 336c64de-5dcb-34bc-9511-a48242b9zzzb. What is the best approach to take for Laravel 8? I am using Laravel Jetstream with Livewire stack.
Current model code
public function getRouteKeyName()
{
return 'slug';
}
public function setSlugAttribute($slug)
{
$this->attributes['slug'] = Str::slug($slug);
}
public function path()
{
return '/tickets/' . $this->slug;
}
Ticket Migration
Schema::create('tickets', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->foreignId('ticket_type_id');
$table->string('slug')->unique();
$table->string('title');
$table->text('body');
$table->string('email')->nullable();
$table->string('url')->nullable();
$table->boolean('locked')->default(false);
$table->unsignedInteger('visits')->default(0);
$table->timestamps();
});
add uuid in migration
$table->uuid('uuid')->unique();
if you want to use uuid for foreign key you have to add
$table->uuid('ticket_type_id');
You can override boot() method of model and set closure to the creating event.
public function boot()
{
parent::boot();
static::creating(function($user) {
$user->uuid = (string) Str::uuid();
});
}

Laravel related model attributes are empty?

I'm trying to give ability on user to see his orders. I have created relationships but when i (dd) the result of the function, the related model attributes are empty.
I don't know what is wrong.
Here is my buyer function
//Buyer Orders
public function myOrders()
{
$user = User::find(auth()->user()->id);
$user = $user->products();
dd($user);// related model attributes shows empty
return view('myOrders')->with(compact('user'));
}
and here is my user
public function products()
{
return $this->hasMany(Products_model::class);
}
public function orders()
{
return $this->hasMany(Order::class);
}
public function allOrdersBuyerSeller()
{
return $this->hasMany(OrderProduct::class);
}
products_model
public function orders()
{
return $this->belongsToMany('App\Order', 'order_product');
}
public function user()
{
return $this->belongsTo('App\User');
}
User Migration
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Product Migration
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('pro_name');
$table->integer('pro_price');
$table->text('pro_info');
$table->integer('stock');
$table->integer('category_id');
$table->string('image')->nullable();
$table->timestamps();
$table->bigInteger('seller_id')->unsigned()->index();
$table->foreign('seller_id')->references('id')->on('users')->onDelete('cascade');
});
}
I would like to see the attributes of the table like price, name, info, img and etc.
Barring the comments about your code, the reason you're not seeing the result of your products query is that you're not passing a closure to the query.
$user = $user->products();
Currently, $user is a QueryBuilder instance. Until you use a closure, like first(), get(), paginate(), etc, you won't be able to see the rows. Modify your code to the following:
$products = $user->products;
// OR
$products = $user->products()->get();
If you omit the (), it will load the relationship using products()->get(), unless already loaded.
Edit: You likely need to include foreign keys to your relationships as the Model name won't match:
User.php
public function products(){
return $this->hasMany(Product_model::class, "seller_id", "id");
}
Probably best to review the contents of the documentation for Relationships; https://laravel.com/docs/5.8/eloquent-relationships. There's a lot of incorrect practices going on with your naming, querying, etc.

laravel auto create random string

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

Laravel 5.5 BelongsToMany returns empty

I'm trying to use a belongsToMany relation, i never had any problems with it but for some reason it returns empty.
I've set up my relation in the Store model like this:
public function images()
{
return $this->belongsToMany('App\Images', 'images_stores', 'image_id', 'store_id');
}
When i test the relationship it returns no error just a empty collection although it's not. This is the way i access the data:
public function edit($id)
{
$store = Store::find($id);
dd($store->images);
return view('admin.pages.store.edit', compact('store'));
}
But it would just return a empty collection, i hope someone could help me out with this. These are my migration file's but i don't think the problem is inside the migration files.
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('path');
$table->timestamps();
});
// pivot table
Schema::create('images_stores', function (Blueprint $table) {
$table->increments('id');
$table->integer('image_id')->unsigned()->nullable();
$table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');
$table->integer('store_id')->unsigned()->nullable();
$table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');
$table->timestamps();
});
// store table
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('location');
$table->string('email');
$table->timestamps();
});
Thanks guys.
I think the ids are inverted. Try this:
public function images()
{
return $this->belongsToMany('App\Images', 'images_stores', 'store_id', 'image_id');
}

How to query pivot table using Eloquent in Laravel 5

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

Categories