postman 404 Not Found - laravel

I'm a beginner in laravel API I want to display list of articles (method index),I already created model Article, but I can not.
Hi, I'm a beginner in laravel API I want to display list of articles (method index),I already created model Article, but I can not.
ArticleController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Article;
use App\Http\Resources\Article as ArticleResource;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$articles= Article::paginate(15);
return ArticleResource::collection($articles);
}
create_table_articles
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('body');
$table->timestamps();
});
}
AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
ArticlesTableSeeder
<?php
use Illuminate\Database\Seeder;
class ArticalesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Article::class,30)->create();
}
}
ArticleFactory.php
<?php
/* #var $factory \Illuminate\Database\Eloquent\Factory */
use Faker\Generator as Faker;
$factory->define(App\Article::class, function (Faker $faker) {
return [
'title' => $faker->text(50),
'body' => $faker->text(200)
];
});
App\Resources\Article.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Article extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(ArticalesTableSeeder::class);
}
}
routes/api.php
//list
Route::get('articles','ArticleController#index');
//list single
Route::get('article/{id}','ArticleController#show');
//create article
Route::post('article','ArticleController#store');
//update articles
Route::put('article','ArticleController#store');
//delete article
Route::delete('articles','ArticleController#destroy');

Laravel automatically prefixes routes in the routes/api.php file with the route prefix /api
You need to make a request to:
http://127.0.0.1:8000/api/articles
Rather than
http://127.0.0.1:8000/articles
You can change this in your RouteServiceProvider if your prefer:
https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L66-L72

Related

Image value should be null when image is not uploaded

Employee Controller
<?php
namespace App\Http\Controllers;
use App\Talent\Employee\Requests\EmployeeCreateRequest;
use App\Talent\Employee\EmployeeManager;
use Illuminate\Http\Response;
use App\Talent\User\UserManager;
use App\Talent\Documents\DocumentManager;
use Illuminate\Support\Facades\Hash;
class EmployeeController extends Controller
{
public function __construct(private EmployeeManager $employeeManager,private UserManager $userManager,private DocumentManager $documentManager)
{
}
public function store(EmployeeCreateRequest $request){
$validated = $request->validated();
$userArray=[
'name'=>$validated['first_name']." ".$validated['last_name'],
'email'=>$validated['email'],
'password'=>Hash::make("Introcept#123"),
'role'=>'user'
];
$userCreate=$this->userManager->store($userArray);
return $this->employeeStore($validated,$userCreate,$request);
}
public function employeeStore($validated,$userCreate,$request){
if($request->hasFile($validated['avatar']))
{
$validated['avatar']=$validated['avatar']->store('employeeimages','public');
}
else
{
$validated['avatar']='null';
}
$userId=$userCreate->id;
$userIdArray=[
'user_id'=>$userId,
'status'=>'Active',
];
$employeeArray=array_merge($validated,$userIdArray);
$employeeCreate=$this->employeeManager->store($employeeArray);
$employeeId=$employeeCreate->id;
foreach($validated['documents'] as $document){
$name=$document->getClientOriginalName();
$type=$document->getClientMimeType();
$path=$document->store('employeedocuments','public');
$documentArray=[
'employee_id'=>$employeeId,
'original_name'=>$name,
'type'=>$type,
'path'=>$path,
];
$documentCreate=$this->documentManager->store($documentArray);
}
return response([
'userId'=>$userId,
'employeeId'=>$employeeId,
'message'=>'Personal detail added successfully',
],Response::HTTP_OK);
}
}
Employee.php
<?php
namespace App\Talent\Employee\Model;
use App\Talent\Documents\Model\Document;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $fillable = [
'first_name',
'last_name',
'email',
'contact_number',
'date_of_birth',
'current_address',
'pan_number',
'bank_account_number',
'avatar',
'status',
'user_id',
];
**EmployeeRequest.php**
<?php
namespace App\Talent\Employee\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EmployeeCreateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|email|unique:employees,email',
'contact_number'=>'required|string',
'date_of_birth'=>'required|date',
'current_address'=>'required|string',
'pan_number'=>'string|nullable',
'bank_account_number'=>'string|nullable',
'avatar' => 'nullable|image|mimes:jpg,jpeg,png',
'documents'=>'required',
'documents.*'=>'max:5000|mimes:pdf,png,jpg,jpeg',
];
}
public function messages()
{
return [
'documents.max' => "Error uploading file:File too big.Max file size:5MB",
];
}
}
EmployeeMigration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->restrictOnDelete();
$table->string('status');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('contact_number');
$table->date('date_of_birth');
$table->string('current_address');
$table->string('pan_number')->nullable();
$table->string('bank_account_number')->nullable();
$table->string('avatar')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
};
I am trying to create an API that stores employee personal details into the database. Here, image field is optional so I made avatar field nullable in both migration and validation request as well. But when I try save details into the database without uploading image it shows undefined avatar. I don't know what happening here any help or suggestions will be really appreciated. Thank you.
You are using the string value of null instead of the keyword null.

Laravel authorization/policy prevents access for everyone

I found similar title and similar asked question on this website when I was researching to solve the problem. But none of posted answers helped me. This question might be duplicated but I could not solve the problem using existing questions on StackOverflow.
I'm trying to prevent access to users who are not logged in OR who are not member of "School" model!
In "web.php" file I used "middleware("auth")" to prevent access to users who are not logged in.
Now I created a "Policy" named "SchoolPolicy" to prevent access to users who are not member of "Schools" database/model.
When I call "view" method from SchoolPolicy, it prevents access for all authorized and unauthorized users!
I also checked and I realized "School" model returns "null" when I try to catch "user_id" foreign key from "schools" table.
The below piece of code is the way I created "Schools" table using Migration:
Schema::create('schools', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('school_name');
$table->string('school_address')->nullable();
$table->string('school_email');
$table->string('school_phone')->nullable();
$table->string('url');
$table->longText('descriptions')->nullable();
$table->timestamps();
});
This is the route to view any school which is created by any user (URL can be dynamic)
Route::group(['middleware' => 'auth'], function () {
Route::get('/schools/{url}', [ViewSchool::class, 'index'])->name('yourschool.show');
});
And this is "School" model. I used php artisan make:model School command to create this model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Auth;
class School extends Model{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_id',
'school_name',
'school_address',
'school_email',
'school_phone',
'url',
'descriptions'
];
}
In this section I created School Policy. However I used Laravel 8 but I also registered created Policy manually
SchoolPolicy
<?php
namespace App\Policies;
use App\Models\School;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class SchoolPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*
* #param \App\Models\User $user
* #return mixed
*/
public function viewAny(User $user)
{
//
}
/**
* Determine whether the user can view the model.
*
* #param \App\Models\User $user
* #param \App\Models\School $school
* #return mixed
*/
public function view(User $user, School $school)
{
return $user->id == $school->user_id;
}
}
In AuthServiceProvider.php I registered SchoolPolicy like this:
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use App\Models\User;
use App\Models\School;
use App\Policies\SchoolPolicy;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
School::class => SchoolPolicy::class
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
}
}
"ViewSchool.php" file where I want to use authorize method:
<?php
namespace App\Http\Controllers\Schools;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\School;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
class ViewSchool extends Controller
{
public function index (School $school) {
$this->authorize('view', $school);
return view('layouts.viewschool');
}
}
I tried many ways to solve the problem, but none of them properly worked:
First Try:
public function index (School $school) {
$this->authorize('view', $school);
}
Second Try:
public function index () {
$this->authorize('view', School::class);
}
I even tried to print any output from School model but I receive "null":
public function index (School $school) {
dd($school->user_id);
}
I followed all tutorials on YouTube and official Laravel website, but in my examples I gave you, authorization doesn't work properly.
Please help me to solve this problem.
Thank you

Policies Laravel not sending variable to controller

I'm new at Laravel, and I'm trying to make Policies that will prevent user that doesn't have id_level 1 which is admin to access InventarisController, but the InventarisPolicy doesn't send variable to InventarisController.
it's my Inventaris Policies
InventarisPolicy.php
<?php
namespace App\Policies;
use App\{User, Level};
use Illuminate\Auth\Access\HandlesAuthorization;
class InventarisPolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* #return void
*/
public function __construct()
{
//
}
public function inventaris_add(User $user)
{
$user->id_level == 1;
// dd($user);
// $user->id_level == 2;
}
}
it's my Inventaris Controller
InventarisController.php
<?php
namespace App\Http\Controllers;
use App\{Inventaris, DetailPinjamanView};
// use Illuminate\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
// use App\Http\Controllers\Auth\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class InventarisController 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()
{
// $viewpinjaman = DetailPinjamanView::all();
$this->authorize('inventaris_add', $user);
$inventaris = Inventaris::all();
return view('index', compact('inventaris'));
}

Undefined constant 'App\Product' when i run php artisan db:seed laravel6

i'm using laravel6 and i want to create 100 products in table products.bit its give me error.
hi, i'm using laravel6 and i want to create 100 products in table products.bit its give me error.
ProductFactory.php
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
use App\Product;
use Faker\Generator as Faker;
$factory->define(Product::class, function (Faker $faker) {
return [
'title'=> $faker->sentence(5),
'description' => paragraph()
];
});
databaseSeed.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
factory(App\Product,100)->create();
}
}
tableproducts
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
your wrong factory(App\Product, 100)->create(); change this to
factory(App\Product::class, 100)->create();
in databaseSeed.php:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
factory(App\Product::class, 100)->create();
}
}
and other error in ProductFactory.php:
change paragraph() to $facker->paragraph()
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
use App\Product;
use Faker\Generator as Faker;
$factory->define(Product::class, function (Faker $faker) {
return [
'title'=> $faker->sentence(5),
'description' => $faker->paragraph()
];
});
include your Product model in databaseSeed.php.
<?php
use Illuminate\Database\Seeder;
use App\Product;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
factory(Product,100)->create();
}
}

MorphMany laravel relation does not work for some reason

I am using laravel 5.6 version, here is my Test model file
<?php
namespace App\Model\data\Models;
use Illuminate\database\Eloquent\Model;
class Test extends Model
{
protected $guarded = ['id'];
protected $table = 'tests';
/*
* Test - TestTranslation relation
* Test has many translations
*/
public function translations()
{
return $this->hasMany('App\Model\Data\Models\TestTranslation');
}
/*
* Test - Image relation
* Test can have an thumbnail
*/
public function thumbnails()
{
return $this->morphMany('App\Model\Data\Models\Image', 'type');
}
}
Here is my Image model
<?php
namespace App\Model\Data\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $guarded = ['id'];
protected $table = 'images';
/*
* Image belongs to Post, Account, Comment
*/
public function type()
{
return $this->morphTo();
}
}
Here is my Database scheme for Images table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->enum('type', ['avatar', 'thumbnail', 'generic'])->default('generic');
$table->integer('type_id')->unsigned()->nullable();
$table->enum('type_type',[
"Account",
"Comment",
"Post",
"Skill",
"Test"
])->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
In AppServiceProvider I linked 'Test' to my model file:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Model\Data\Models\Account;
use App\Model\Data\Models\EmailChangeConfirmation;
use App\Model\Observers\Common\AccountObserver;
use App\Model\Observers\Common\EmailChangeConfirmationObserver;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
Relation::morphMap([
'Account' => 'App\Model\Data\Models\Account',
'Comment' => 'App\Model\Data\Models\Comment',
'Post' => 'App\Model\Data\Models\Post',
'Skill' => 'App\Model\Data\Models\Skill',
'Test' => 'App\Model\Data\Models\Test'
]);
if(env('APP_ENV') != 'testing') {
Account::observe(AccountObserver::class);
EmailChangeConfirmation::observe(EmailChangeConfirmationObserver::class);
}
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
if ($this->app->environment('local', 'testing')) {
$this->app->register(DuskServiceProvider::class);
}
}
}
As you can see, I have more morhpMany types, and all of them works fine. But for some reason, this Test relation that I added recently always returns an empty collection, even tough I am sure that test has thumbnails. Cause:
in this screenshot, I have records in database that each test has two images. Their ID matches ids of created tests and type is "Test". I tried to clear all caches, run composer dump-autoload but none of them helped.
Maybe someone can help identify what is wrong here? Because as I said before other types as Post, Account works fine.

Resources